Khwan Siricharoenporn
Khwan Siricharoenporn

Reputation: 99

SELECT mysql with php json encode

Here My code now :

$sql = "SELECT * FROM schedule_feednow WHERE IDMac = '".$_GET["IDMac"]."'";
$result = mysql_query($sql) or die(mysql_error());
$json_data = array();

while($rec = mysql_fetch_assoc($result)){
	$Subjson = array();
	$Subjson['IDMac'] = $rec['IDMac'];
	$Subjson['DATETIME'] = $rec['DATETIME'];
	$Subjson['Weight'] = $rec['Weight'];
	
	array_push($json_data,$Subjson);
	

}

echo json_encode ($json_data);

and Result :

[{"IDMac":"C-01","DATETIME":"12:05:19 AM on June 23, 2017","Weight":"50"},{"IDMac":"C-01","DATETIME":"12:05:55 AM on June 23, 2017","Weight":"50"},{"IDMac":"C-01","DATETIME":"02:02:20 PM on June 23, 2017","Weight":"50"}]

But I don't want this Result

I want this Result->

["Schedule":{"IDMac":"C-01","DATETIME":"12:05:19 AM on June 23, 2017","Weight":"50"},{"IDMac":"C-01","DATETIME":"12:05:55 AM on June 23, 2017","Weight":"50"},{"IDMac":"C-01","DATETIME":"02:02:20 PM on June 23, 2017","Weight":"50"}]

Please help me to generate code or train me. Thank you very much.

Upvotes: 0

Views: 73

Answers (4)

JNCM
JNCM

Reputation: 1

$sql = "SELECT * FROM schedule_feednow WHERE IDMac = '".$_GET["IDMac"]."'";
$result = mysql_query($sql) or die(mysql_error());
$json_data = array();

while($rec = mysql_fetch_array($result)){
	$json_data[] = $rec;
}

echo json_encode ('Schedule' => $json_data);

Upvotes: 0

Paladin
Paladin

Reputation: 1637

Replace

echo json_encode ($json_data);

with

$myResult = ['Schedule' => $json_data];
echo json_encode ($myResult);

Upvotes: 1

modsfabio
modsfabio

Reputation: 1147

Simply put your current result into an array with key "Schedule":

echo json_encode(array('Schedule' => $json_data));

Upvotes: 2

aynber
aynber

Reputation: 23010

Just create another array and put your json data in that:

$newJsonData = ['Schedule' => $json_data];
echo json_encode ($newJsonData);

Upvotes: 1

Related Questions