用表中一行的值填充数组


populating an array with values from a row in a table

我有代码,我不确定它是否正确,结构是否可行。这是代码:

$host="localhost";
$username="sample1";
$password="1234";
$db_name="sampledb";
mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");
function example1(array1) {
//is this allowed??
  $array1 = array();
  $ctr = 0;
  $ctr1=1;
  $sql="SELECT names FROM tblnamelist";
  $result=mysql_query($sql);
  $row=mysql_fetch_array($result);
  $count=mysql_num_rows($result);
  //I also want to populate the array1 with all the values that was retrieved in the query then return it as an array
  if($count!=0) {
    while($ctr1<=$count) {
      $array1[$ctr]=$row[$ctr];
    }
  }
}

基本上,我的问题是如何用从查询中检索到的值填充array1

我建议返回数组,我不喜欢引用系统,因为函数的用户并不真正知道函数在做什么。。。

function get_results()
{
  $array1 = array();
  $sql="SELECT names FROM tblnamelist";
  $result=mysql_query($sql);
  while($row=mysql_fetch_array($result))
  {
      $array1[] = $row;
  }
  return $array1;
}
$array = get_results();
function example1(&$array1) {
  //is this allowed?? -- yes, but you have to do it by reference see & in the definition
  $array1 = array();

您不需要创建额外的数组来检索结果,使用此函数返回关联数组:

while($row=mysql_fetch_array($result){
echo $row['field_name'];
}

在您的情况下:

  $sql="SELECT names FROM tblnamelist";
  $result=mysql_query($sql);
  while($row=mysql_fetch_array($result)){
  echo $row['field_name'];
} 

如果结果中只有一行,则不需要while循环。

使用此

 if ($count!=0)
  {
    while($row=mysql_fetch_array($result))
    {
      array_push($array1,$row['names']);
    }
  }
 print_r($array1);

不需要计数,因为while将遍历任何值只需将行分配给数组1

$result=mysql_query($sql); 
while($row=mysql_fetch_array($result)) { 
    $array1[]=$row;
} 

如果您在下面多次使用此方法,则可能需要为数组提供一个逻辑索引;

while($row=mysql_fetch_array($result)) { 
    $array1[$row['myUniqueRowID']]=$row;
} 

您可以重写while循环,使其看起来像这样。下面的代码将从$result获得一个新的$row,直到没有更多结果为止。(您不需要$count变量)

$array1 = array();
while($row = mysql_fetch_array($result)) {
    $array1[] = $row['names'];  // Insert the value of $row['names'] to the end of the array
}
// return your array, or use Jakub's method.
return $array1;

当然,如果您对这些值所做的只是将它们打印到屏幕上,那么您还可以使用Harshal的解决方案。如果你想让函数返回一个数组,你的函数可以是:

function getNamesArray() {
    $sql="SELECT names FROM tblnamelist";
    $result=mysql_query($sql);
    // this is the result array that this function will return
    $array1 = array();
    // loop while there are rows in the mysql result
    while($row = mysql_fetch_array($result)) {
        // Insert the value of $row['names'] to the end of the array
        $array1[] = $row['names'];  
    }
    return $array1;
}
// test the function:
$test = getNamesArray();
var_dump($test);

不过,您应该考虑使用事先准备好的语句。看看PDO和MySQLi。不鼓励使用mysql_函数。