-2

Hi I am new in php and i dont know how can i do this?

I have four rows in my data base and i want to encode a Json array of these rows using php how can i do this.

below is my code please look into this and give me a suggestion--

<html>
<head>
<title>First</title>
<body>
<?php
$con = mysql_connect("localhost","root");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("ContactDB", $con);

$result = mysql_query("SELECT * FROM mycontacts");

echo "<table border='1'>
<tr>
<th>PhoneNumber</th>
<th>Name</th>
<th>Lastname</th>
</tr>";

 while($row = mysql_fetch_array($result))
  {
  $data=array("PhoneNumber"=>$row['PhoneNumber'],"Name"=>$row['Name']); 
print_r (json_encode(array_chunk($data, 1, true)));  
}


mysql_close($con);
?>

</body>
</head>
</html>

I am getting response like this

[{"PhoneNumber":"1234567"},{"Name":"Ujjwal"}][{"PhoneNumber":"765423"},{"Name":"ABC"}][{"PhoneNumber":"098765123"},{"Name":"A"}]

but i want it in this format

[{"PhoneNumber":"1234567", "Name":"X"},{"PhoneNumber":"765423", "Name":"ABC"},{"PhoneNumber":"098765123", "Name":"A"}]

1

5 Answers 5

1

Replace

while($row = mysql_fetch_array($result))
{
  $data=array("PhoneNumber"=>$row['PhoneNumber'],"Name"=>$row['Name']); 
  print_r (json_encode(array_chunk($data, 1, true)));  
}

with

$data = array();
while($row = mysql_fetch_array($result))
{
  $data[] = array("PhoneNumber"=>$row['PhoneNumber'],"Name"=>$row['Name']); 
}
print_r (json_encode($data));  
Sign up to request clarification or add additional context in comments.

Comments

0

Dont use array_chunk

json_encode($data) should do it.

You may also want to declare data as as array before the loop and then user $data[] = json_encode(.....)

Comments

0

Try this:

$json = json_encode($data)

Comments

0

Try replacing

$data= array("PhoneNumber"=>$row['PhoneNumber'],"Name"=>$row['Name']);

with

$data= (object) array("PhoneNumber"=>$row['PhoneNumber'],"Name"=>$row['Name']);

Comments

0

Example of how to do it below. Can I also suggest the use of AS in the MySQL query (and avoid the *; just get the data you need).

$q = mysql_query("SELECT ... AS ... ...");
$rows = array();
while($r = mysql_fetch_assoc($q)) {
    $rows[] = $r;
}
print json_encode($rows);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.