-1

I have following sql query in PHP and output is as JSON:

<?php

$user_id = "1";

$sql = 'SELECT *,DATE_FORMAT(c.`date`, "%d.%m.%Y") AS date
          FROM
            conversation c,
            users u
          WHERE
            c.user_two = u.uid AND c.user_one = '$user_id'
            ORDER By  c.precious_time DESC';


$result = mysqli_query($con, $sql);

$rows = array();

while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
    $rows [] = $row; 
}

mysqli_close($con);

echo json_encode($rows);

?>

When I execute the the php file it does not echo anything, but if I set c.user_one = "1" instead of c.user_one = '$user_id' then it works and it gives me the results. Is there a formatting error ?

Sini
  • 406
  • 1
  • 6
  • 16
  • 2
    In deed it is. Try as `c.user_one = '.$user_id.'` – Abhik Chakraborty Mar 30 '15 at 16:40
  • **WARNING**: When using `mysqli` you should be using parameterized queries and [`bind_param`](http://php.net/manual/en/mysqli-stmt.bind-param.php) to add user data to your query. **DO NOT** use string interpolation to accomplish this because you will create severe [SQL injection bugs](http://bobby-tables.com/). **NEVER** put `$_POST` data directly into a query. – tadman Mar 30 '15 at 16:57

1 Answers1

0

If you use doublequotes it works:

$sql = "SELECT *,DATE_FORMAT(c.`date`, '%d.%m.%Y') AS date
        FROM conversation c, users u
        WHERE c.user_two = u.uid AND c.user_one = '$user_id'
        ORDER By c.precious_time DESC";

FYI: http://php.net/manual/en/language.types.string.php#language.types.string.parsing

fdglefevre
  • 672
  • 4
  • 15