I have a MySQL query like this written in PHP:
$merkki = $_GET["merkki"];
// Retrieve all the data from the table
//to show models based on selection of manufacturer
$result = mysql_query("SELECT * FROM Control_Mallit WHERE merkki_id = $merkki")
or die(mysql_error());
echo '{';
while($row = mysql_fetch_array($result)){
echo '"' . $row['id'] . '"' . ":" . '"' . $row['malli'] . '"';
}
echo '}';
Result is correct, but how I can get a comma after each record? If I echo (,) after each row my code doesn’t work. I need it formatted as described below.
{
"":"--",
"series-1":"1 series",
"series-3":"3 series",
"series-5":"5 series",
"series-6":"6 series",
"series-7":"7 series"
}
What’s the best way to do this?
Immediately stop using your code. It is vulnerable to SQL injection. Think of what would happen if the value of
merkkiwas1 OR 1=1. The statement would return all records:You need to bind parameters to your query using
mysqli_orPDOfunctions (mysql_functions are being deprecated. Also, use a column list and do notSELECT *.Here is a possible solution using
mysqli_(not tested):Edit
Following your original code, this solution should work: