简体   繁体   English

通过SQL查询创建数组

[英]Make an array from SQL query

I'm trying to go to my DB, get info from a bunch of columns based on two variables, and return all the values of all of those columns into a php list (or array), so for example, the final result would be something like $output = array($foo,$bar,$hello); 我正在尝试进入数据库,从基于两个变量的一堆列中获取信息,并将所有这些列的所有值返回到php列表(或数组)中,例如,最终结果将是像$output = array($foo,$bar,$hello);

Here is the code I have right now to connect to the DB and my query, I know I am missing the vital code here, hoping someone can help me, thanks. 这是我现在用于连接数据库和查询的代码,我知道我在这里缺少重要的代码,希望有人可以帮助我,谢谢。

<? php

$var1 = 20.0;
$var2 = 15.0;

function getFromDB($var1, $var2){

mysql_connect("localhost", "test", "test") or die (mysql_error());
mysql_select_db("test") or die(mysql_error());
$queryString = "SELECT * from table1 WHERE foo=".$var1."AND bar=".$var2;
$go = mysql_query($queryString);
while($row = mysql_fetch_array($go)){
echo $row['col1']; 
echo $row['col2'];
echo $row['col3'];

}
}

getFromDB($var1,$var2);
?>

The idea is to have the values of col1, 2, and 3 in an array. 想法是在数组中具有col1、2和3的值。 Thanks! 谢谢! Sam 山姆

Either one of these will work: 这些方法之一将起作用:

while($row = mysql_fetch_array($go)){
  $output[] = array($row['col1'], $row['col1'], $row['col1']);
}

or: 要么:

while($row = mysql_fetch_array($go)){
  $output[] = $row;
}

The one you should use depends on how the $row-data looks like. 您应该使用哪个取决于$ row-data的外观。

$data = array ();
while ( $row = ...)
{
    // appends the contents of $row to a new value in $data
    $data[] = $row;
}

print_r ($data); // <-- to see the output
$array = array();
while ($row = mysql_fetch_array($go)) {
    $array[] = array($row['col1'], $row['col2'], $row['col3']);
}

Please note that you should stop using mysql_* functions. 请注意,您应该停止使用mysql_*函数。 They're being deprecated. 他们已被弃用。 Instead use PDO (supported as of PHP 5.1) or mysqli (supported as of PHP 4.1). 而是使用PDO (自PHP 5.1起受支持)或mysqli (自PHP 4.1起受支持)。 If you're not sure which one to use, read this SO article . 如果您不确定要使用哪个,请阅读这篇SO文章

Replace 更换

echo $row['col1'];
echo $row['col2'];
echo $row['col3'];

with

$array = $row;

and return $array . 并返回$array

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM