Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

send json data from php [closed]

Tags:

json

php

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

like image 452
Raj Avatar asked Mar 07 '13 21:03

Raj


People also ask

How to Send JSON data using HTTP POST request in PHP?

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.

What is File_get_contents PHP input?

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.


3 Answers

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

like image 166
Sam Avatar answered Oct 03 '22 05:10

Sam


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

like image 23
Sixthpoint Avatar answered Oct 03 '22 06:10

Sixthpoint


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
like image 35
Pitchinnate Avatar answered Oct 03 '22 06:10

Pitchinnate