如何从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查询中选择一条记录并使我的其余代码也能正常工作呢?
答案 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);
}