我正在尝试将查询中的结果转换为数组。
转过来
$result = mysql_query("SELECT * FROM WHATEVER");
进入
$result = array('id' => 1, 'name' => 'bob');
但我不想要print_r()
,我想回复php可执行代码。
谢谢!
答案 0 :(得分:2)
尝试:
$records = array();
$query = mysql_query("SELECT * FROM WHATEVER ");
while ($result = mysql_fetch_assoc($query)) {
$records[] = $result;
}
现在您可以使用$records
作为(可重复使用的)数组。
Please, don't use mysql_*
functions in new code。它们不再被维护,deprecation process已经开始了。请参阅red box?转而了解prepared statements,并使用PDO或MySQLi - this article将帮助您确定哪个。如果您选择PDO here is a good tutorial。
答案 1 :(得分:1)
您可以使用PDO和PDOStatement::fetchAll()
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
$dbh = new PDO($dsn, $user, $password);
$sth = $dbh->prepare("SELECT * FROM WHATEVER");
$sth->execute();
$results = $sth->fetchAll(); // get all rows
var_dump($results);
//to get only first row:
$result = $results[0];
答案 2 :(得分:0)
尝试:
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
printf("ID: %s Name: %s", $row["id"], $row["name"]); //or echo
}
答案 3 :(得分:-1)
易:
$result = mysql_query("SELECT * FROM WHATEVER ");
if($result)
{
$result = mysql_fetch_array($result,MYSQL_ASSOC);
/*
manipule $result according you need
*/
print_r($result);
}
else{
echo mysql_error();
}