2

I have this piece of PHP code which should accept a number sent from an Android app and search the equivalent to that number in the database (in the other field) and send the result to the Android app.

But I get this error:

Object of class stdClass could not be converted to string in D:\xampp\htdocs\ \b.php

in this line:

mysql_query(" select  stock_account from  Stock where  phone_id=   (string)$data ") 

This is the complete code:

if( isset($_POST["json"]) )
{
    $data = json_decode($_POST["json"]);

    mysql_connect("localhost", "root", "password") or die(mysql_error());
    mysql_select_db("dbname") or die(mysql_error());

    $datatwo = mysql_query(" select  stock_account from  Stock where   id=   (string)$data ") or die(mysql_error()) ;  

    echo $datatwo;
}
insertusernamehere
  • 23,204
  • 9
  • 87
  • 126
JEREEF
  • 51
  • 8

1 Answers1

1

The first thing is that json_decode generates an object. The second thing you want to is a value from the $data variable so we use $data->id to get the id from the JSON. I'm casting it to an integer like this $id = (int)$data->id; and storing it in a new variable. Now in the query you can pass the $id variable to fetch your row.

If you want a different value off your $data variable you will need to change $data->id to something else.

<?php

if (isset($_POST["json"])) {
    $data = json_decode($_POST["json"]);

    mysql_connect("localhost", "root", "password") or die(mysql_error());
    mysql_select_db("dbname") or die(mysql_error());

    $id = (int)$data->id;
    $datatwo = mysql_query("SELECT stock_account FROM Stock WHERE phone_id =$id") or die(mysql_error()) ;  

    $row = mysql_fetch_assoc($datatwo);
    echo $row['stock_account'];
}

Read more here: http://php.net/json_decode

json_decode — Decodes a JSON string

Usage: mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )

Community
  • 1
  • 1
Clay
  • 4,700
  • 3
  • 33
  • 49