简体   繁体   English

从PHP中的MySQL返回多行

[英]returning multiple rows from mysql in php

I'm trying to write a PHP-script that will fetch multiple rows from MySQL and return them as a JSONObject, the code works if I try to only fetch 1 row but if I try to get more than one at a time the return string is empty. 我正在尝试编写一个PHP脚本,该脚本将从MySQL获取多行并将其作为JSONObject返回,如果我仅尝试获取1行但一次尝试获取多个返回字符串,则该代码有效是空的。

$i = mysql_query("select * from database where id = '$v1'", $con);
$temp = 2;
while($row = mysql_fetch_assoc($i)) {
    $r[$temp] = $row;
    //$temp = $temp +1;
}

If I write the code like this it returns what I expect it to, but if I remove the // from the second row in the while loop it will return nothing. 如果我这样编写代码,它将返回我期望的结果,但是如果我从while循环的第二行中删除//,它将不会返回任何内容。 Can anyone explain why this is and what I should do to solve it? 谁能解释这是为什么以及我应该怎么做才能解决?

  1. You are using an obsolete mysql_* library. 您正在使用过时的mysql_ *库。

  2. You are SQL injection prone. 您很容易进行SQL注入。

  3. Your code is silly and makes no sense. 您的代码很愚蠢,没有任何意义。

If you really wan to stick to it, why simply not do: 如果您真的想坚持下去,为什么不这样做:

while($row = mysql_fetch_assoc($i)) {
 $r[] = $row;
}

echo json_encode($r);

And finally, an example using PDO: 最后,使用PDO的示例:

$database = 'your_database';
$user = 'your_db_user';
$pass = 'your_db_pass';

$pdo = new \PDO('mysql:host=localhost;dbname='. $database, $user, $pass);
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

try
{
    $stmt = $pdo->prepare("SELECT * FROM your_table WHERE id = :id");

    $stmt->bindValue(':id', $id);

    $stmt->execute();

    $results = $stmt->fetchAll(\PDO::FETCH_ASSOC);
}
catch(\PDOException $e)
{
    $results = ['error' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine());   
}

echo json_encode($results);

You don't need the $temp variable. 您不需要$temp变量。 You can add an element to an array with: 您可以使用以下方法向数组添加元素:

$r[] = $row;

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

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