I am totally new to Php and i am trying to send json data from php to android.I have the following code in php to read value from data base:
<?php
$con=mysql_connect("localhost","root","");
if(! $con)
{
die('Connection Failed'.mysql_error());
}
mysql_select_db("registration",$con);
$name="Adam";//$_POST["name"];
$password="charles";//$_POST["password"];
$sql="SELECT * FROM users WHERE name='$name'and password='$password'";
$result=mysql_query($sql, $con);
while($row = mysqli_fetch_array($result))
{
$details= array(
'name' => $row['name'],
'password' => $row['password'],
);
array_push($json, $bus);
}
$jsonstring = json_encode($json);
echo $jsonstring;
mysql_close();
?>
I am expecting the output to be something like this:
[{"name":"Adam","age":"25","surname":"charles"}]
If i am not wrong the JSON data. But this gives me error :
mysqli_fetch_array() expects parameter 1 to be mysqli_result, resource given in...
and also
Undefined variable: json in...
can somebody pleease tell me what might be the possible error
To post JSON to a REST API endpoint using PHP, you must send an HTTP POST request to the REST API server and provide JSON data in the body of the PHP POST message. You also need to specify the data type in the body of the POST message using the Content-Type: application/json request header.
The file_get_contents() reads a file into a string. This function is the preferred way to read the contents of a file into a string. It will use memory mapping techniques, if this is supported by the server, to enhance performance.
Try as this
$result=mysql_query($sql, $con);
$json = array();
while($row = mysql_fetch_array($result))
{
$json[]= array(
'name' => $row['name'],
'password' => $row['password']
);
}
$jsonstring = json_encode($json);
echo $jsonstring;
And mysql is deprecated, when you can use mysqli or PDO
In addition to the changes suggested by sam and pitchinnate, also consider adding php header to set the content type to json
header('Content-type: application/json');
That is if you are using android to request the json information remotely
You are using mysql_query
with mysqli_fetch_array
. You need to use mysql_fetch_array
.
However mysql_* functions shouldn't be used anymore.
Also another error:
array_push($json, $bus); // i believe $bus should be replaced with $details
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With