imcrazy
imcrazy

Reputation: 77

Retrieve specific row from database and display all the data in the specific row and send json using php

I would like to retrieve a specific row from database using php and mysqli.

For example:

I want to retrieve the row of data with userid =2

$userid =2;

Then I get it the user email, name, password from database using the $userid given:

include("includes/connect.php");
$user = "SELECT * FROM account WHERE user_id = $userid " ;
$query = mysqli_query ($conn,  $user);        

while($result = mysqli_fetch_array ($query)){
      $name = $result['username'];
      $password = $result['user_password']; 
      $email = $result['user_email'];           
  }

Then I would like to send the username, password and email of the userid=2 to mobile app in json.

How can I do that after that?

Upvotes: 2

Views: 3346

Answers (2)

Adrian Cid Almaguer
Adrian Cid Almaguer

Reputation: 7791

First you need add this line header('Content-Type: application/json'); to output your json file to the browser, and see the change in your while loop, and call the function json_encode()

header('Content-Type: application/json');

include("includes/connect.php");
$user = "SELECT * FROM account WHERE user_id = $userid " ;
$query = mysqli_query ($conn,  $user);        

$json = array();

while($result = mysqli_fetch_array ($query)){
      $json['name'] = $result['username'];
      $json['password'] = $result['user_password']; 
      $json['email'] = $result['user_email'];           
  }

echo json_encode($json);

Read mote at:

http://php.net/manual/en/function.json-encode.php

Upvotes: 1

hamed
hamed

Reputation: 8033

You need to pass data with json_encode:

$data = array();
while($result = mysqli_fetch_array ($query)){
  $data['username'] = $result['username'];
  $data['user_password'] = $result['user_password']; 
  $data['user_email'] = $result['user_email'];           
}

echo json_encode($data);

Also you can use mysqli_fetch_assoc for retrieving json data from database:

$row=mysqli_fetch_assoc($query)
echo json_encode($row);

More information about mysqli_fetch_assoc function.

Note, If you are sure that just one row will return(In this case I think just one row will return, because usually user_id is unique), no need to use while.

Upvotes: 2

Related Questions