0

How can I select a row from mysql query and save it to variable. This is the full code I am currently using:

    <?php
    header('Content-Type: text/html; charset=utf-8');
    include 'config.php';

    // Connect to server and select databse.
    mysql_connect("$dbhost", "$dbuser", "$dbpass")or die("cannot connect");
    mysql_select_db("$dbname")or die("cannot select DB");


    $IND=$_POST['id'];


    $IND = stripslashes($IND);
    $IND = mysql_real_escape_string($IND);

    $sql = "select * from table where IND='$IND'";
    $result=mysql_query($sql);

       $row = mysql_fetch_array($result);
      $number = $row['number'];


    // Mysql_num_row is counting table row
    $count=mysql_num_rows($result);

    if ($count == 1) {
       $message = mysql_fetch_assoc($result);
        $message['status'] = 'ok';
        $message = array($message);


    } else {
         $message = mysql_fetch_assoc($result);
        $message['status'] = 'error';
        $message = array($message);
    }


    header('Content-Type: application/json');
        print '{"key":'. json_encode($message) .'}';
?>

But when I use $row = mysql_fetch_array($result); $number = $row['number']; the JSON encoded $message is shown undefined.

So how can I select a single record from mysql query and make all the rest of my code to work also?

user1256852
  • 53
  • 4
  • 13
  • Comment out the `header` line, and do a `var_dump($message)`, what does it say? – UltraInstinct Jul 03 '12 at 06:55
  • use print_R($row) to see how many rows are coming are they more then 1 – Muhammad Raheel Jul 03 '12 at 07:08
  • nope, they are not more then 1. $message shows just `{"key":[{"status":"ok"}]}`but not the rows from query – user1256852 Jul 03 '12 at 07:16
  • PHP's `mysql_*` functions are [deprecated](http://www.php.net/manual/en/faq.databases.php#faq.databases.mysql.deprecated). There are [alternatives](http://www.php.net/manual/en/mysqlinfo.api.choosing.php) that are both supported and [much safer](http://stackoverflow.com/a/60496/132382). – pilcrow Jul 03 '12 at 15:25

1 Answers1

0

declare the variable $message as array and then assign the values in the if condition . Try as follows :

$message=array();
$count=mysql_num_rows($result);

    if ($count == 1) {
       $message = mysql_fetch_assoc($result);
        $message['status'] = 'ok';
        $message = array($message);


    } else {
         $message = mysql_fetch_assoc($result);
        $message['status'] = 'error';
        $message = array($message);
    }
Prabhuram
  • 1,268
  • 9
  • 15