Reputation: 91
Ok, this is a lot like my last question (PHP convert a SQL request into JSON) but im unable to find a solution even when it looks like it is very easy.
I have a very simple SQL table:
$sql="CREATE TABLE
example (ID INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
status VARCHAR(50),
value VARCHAR(50));";
With the following values:
1 | name1 | open | value1
2 | name2 | open | value2
3 | name3 | close | value3
I call the desired data:
$sql= "SELECT * FROM example where status='open'";
$result= mysqli_query($link,$sql);
$arrayofdata = mysqli_fetch_array($result);
Since $arrayofdata could have 1 or many arrays inside it, i try this:
$JSONED = json_encode($arrayofdata);
But the output value is very odd, and, i do not understands why, it do not includes the [] brackes (As far as i understands JSON format, [] should be first and last element on a JSON string)
I want a JSON object like this:
[{1,"name1","open","value1"},{2,"name2","open","value2"}]
Can it be done directly? Or must the code interact with $arrayofdata to create a new array step by step?
Upvotes: 1
Views: 41
Reputation: 8670
you can get your desire results with something like the following code :
$sql= "SELECT * FROM example where status='open'";
$result= mysqli_query($link,$sql);
$data = array();
while ($row = mysql_fetch_assoc($result)) {
//... maybe some processing of $row here ...
$data[] = $row;
}
echo json_encode($data);
Upvotes: 1