I'm newbie here., I want to get the array value that I set in an array. I have this simple code here. Hope someone could help me..What is the correct way to set this one?
<?php
include('datacon.php');
//$id = $_GET['id'];
$list = mysql_query("SELECT PatientID,Fname,Mname,Lname
FROM tbl_PatientInfo WHERE PatientID = '1' ");
$result = array();
foreach( mysql_fetch_array($list) as $row){
$result[] = array(
'id' => $row['PatientID'],
'fname' => $row['Fname'],
'mname' => $row['Mname'],
'lname' => $row['Lname']
);
}
echo json_encode($result);
?>
When i try this code. It said an error: Warning: Illegal string offset 'PatientID' on line 15
This line is incorrect:
foreach( mysql_fetch_array($list) as $row){
This is retrieving just one row, and then iterating over the columns in that row. The columns are just strings, not arrays, which is why you get illegal string offset errors.
You want to retrieve each row, you do that with:
while ($row = mysql_fetch_array($list)) {
You are not getting an associative array that's why it is invalid to use:
mysql_fetch_assoc($list) as $row
rather than
mysql_fetch_array($list) as $row
Use mysql_fetch_assoc
as don't need numeric indexes in your output, so mysql_fetch_array
is a bit of an overhead.
$result = array();
while( ($row = mysql_fetch_assoc( $list ) ) !== false ) {
$result[] = array(
'id' => $row['PatientID'],
'fname' => $row['Fname'],
'mname' => $row['Mname'],
'lname' => $row['Lname']
);
}
fetch_array() : $row[0], $row[1], etc...
fetch_assoc() : $row['PatientID'], $row['Fname'], etc...
fetch_object() : $row->PatientID, $row->Fname, etc...
<?php
include('datacon.php');
//$id = $_GET['id'];
$list = mysql_query("SELECT PatientID,Fname,Mname,Lname
FROM tbl_PatientInfo WHERE PatientID = '1' ");
$result = array();
$i=0;
while( $row=mysql_fetch_array($list)){
$result[$i]['id'] = $row['PatientID'];
$result[$i]['fname'] = $row['Fname'];
$result[$i]['mname'] = $row['Mname'];
$result[$i]['lname'] = $row['Lname'];
$i++;
}
echo json_encode($result);
?>