从mysql查询中选择单行并将其保存到变量

时间:2012-07-03 06:51:21

标签: php mysql select

如何从mysql查询中选择一行并将其保存到变量中。这是我目前正在使用的完整代码:

    <?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) .'}';
?>

但是当我使用$row = mysql_fetch_array($result); $number = $row['number'];时,JSON编码的$ message显示为undefined。

那么如何从mysql查询中选择一条记录并使我的其余代码也能正常工作呢?

1 个答案:

答案 0 :(得分:0)

将变量$message声明为array,然后assign if条件中的值。请尝试如下:

$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);
    }