0

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?

3
  • You should not use mysql_* functions anymore because they're deprecated and get removed with one of the next versions of PHP. Use PDO or mysqli instead. Then you should initialize your array $r with $r = array();. You can do ++$item; to increase a counting variable. And you should get all results in the $r variable afterwards. Commented Jul 25, 2014 at 10:44
  • use json_encode to return josnObject Commented Jul 25, 2014 at 10:45
  • Why are you starting $temp from 2? Commented Jul 25, 2014 at 10:46

2 Answers 2

2
  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);
Sign up to request clarification or add additional context in comments.

Comments

0

You don't need the $temp variable. You can add an element to an array with:

$r[] = $row;

2 Comments

If he likes to start with index 2 he has to.
Maybe the reason he's starting from 2 is because he already has 2 elements in the array, so my answer will work.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.