0

I am trying to output JSON format result of post_table in while loop, But I have to include an object value in the resulted array from fetching another table which is img_table, here is my code:

$result_main = mysql_query("SELECT * FROM post_table WHERE userid='$userid' ");
$rowsm = array();

while($rm = mysql_fetch_assoc($result_main)) {
    $row0 = mysql_fetch_array($result_main);
    $user_post_id =   $row0['user_post_id'];

    $result=mysql_query("SELECT * FROM img_table WHERE post_id='$user_post_id' "); 

    while($row = mysql_fetch_array($result)) {
        $user_img=$row['img_filename'];
        $rm['img_filename'] = $user_img;
    }

    $rowsm[] = $rm ;
}

echo"{\"result_main\":";
print json_encode($rowsm);
echo '}';

But the result is incorrect. Is this the right way to do so?

Eloims
  • 5,106
  • 4
  • 25
  • 41
user2985035
  • 569
  • 3
  • 8
  • 18
  • "But the result is incorrect" - how does it reveal? – RomanPerekhrest Mar 18 '16 at 20:36
  • [Your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – Jay Blanchard Mar 18 '16 at 20:38
  • 2
    Please [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). [These extensions](http://php.net/manual/en/migration70.removed-exts-sapis.php) have been removed in PHP 7. Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [PDO](http://php.net/manual/en/pdo.prepared-statements.php) and [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and consider using PDO, [it's really pretty easy](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard Mar 18 '16 at 20:39
  • what do you mean with "But the result is incorrect" explain better please – ScaisEdge Mar 18 '16 at 20:39
  • img_filename key value is correct in the first but null in the next result – user2985035 Mar 18 '16 at 20:41
  • Second, I must have 3 results under the result_main, instead I'm getting 2 only – user2985035 Mar 18 '16 at 20:42
  • 1
    Thats because `while($rm = mysql_fetch_assoc($result_main)) {` fetches a result row and so does `$row0 = mysql_fetch_array($result_main);` you dont need the `$row0 = mysql_fetch_array($result_main);` inside the while loop. You dont have an extra fetch inside the inner loop, do it like that# – RiggsFolly Mar 18 '16 at 20:45
  • OK great, so how to get the `$user_post_id = $row0['user_post_id']; ` value – user2985035 Mar 18 '16 at 20:48
  • I got it, simply `$user_post_id = $rm['user_post_id'];` got it right – user2985035 Mar 18 '16 at 20:52
  • @RiggsFolly Thanks a million, Please put your comment as an answer to mark it as the correct answer, Greetings :) – user2985035 Mar 18 '16 at 20:54

0 Answers0