简体   繁体   中英

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.

$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. Can anyone explain why this is and what I should do to solve it?

  1. You are using an obsolete mysql_* library.

  2. You are SQL injection prone.

  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:

$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. You can add an element to an array with:

$r[] = $row;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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