从PHP获取mySQL的结果

时间:2015-04-27 13:52:26

标签: php mysql

我试图通过以下代码从mySQL中的表中获取结果。 这是行不通的。我是PHP的新手。

也许有人可以帮助我的代码出错?我认为我的SQL语句编写得不好。是吗?

<?php 

header("Content-type: text/html; charset=utf8");

// header('Content-Type:text/html;charset=utf-8');

//1. create connection

$connection=mysql_connect("localhost","user","pass");

if(!$connection){
    die("database connection failed:" . mysql_error());
}

//2. select database 

$db = mysql_select_db("database",$connection);

if(!db) {
    die("database connection failed:" . mysql_error());
}

//if i want to work with hebrew databases

mysql_query("SET NAMES 'utf8'",$connection); // reading heberer from phpadmin database - only for hebrew sites 

$MessageNo = $_POST['MsgNo']

//$MessageN0=(int)$MessageNo

$query = mysql_query("SELECT * FROM MessageContent WHERE MsgNo='$MessageNo'");;;

$messages = array();

while ($row = mysql_fetch_array($query)) {
    $messages[] = array('MsgContId' => $row['MsgContId'], 'MsgNo' => $row['MsgNo'],'MsgContent' => $row['MsgContent'], 'AddedBy' => $row['AddedBy'],'AddedAt'=>$row['AddedAt']);
}

// echo json_encode(array('users' => $users));

echo json_encode($messages);

mysql_close($connection);

?>

1 个答案:

答案 0 :(得分:1)

我在这行看到你有格式错误:

$query = mysql_query("SELECT * FROM MessageContent WHERE MsgNo='$MessageNo'");;;

删除额外的两个分号:

$query = mysql_query("SELECT * FROM MessageContent WHERE MsgNo='$MessageNo'");

还有:

$MessageNo = $_POST['MsgNo']

需要分号:

$MessageNo = $_POST['MsgNo'];

此外,您还在使用已弃用的功能。我建议你研究MySQLi函数或PDO。

咨询:mysqli with prepared statementsPDO with prepared statements

编辑:同样在第二个查询中,您还没有使用连接字符串:

$query = mysql_query("SELECT * FROM MessageContent WHERE MsgNo='$MessageNo'",$connection);

error reporting添加到文件的顶部,这有助于查找错误。

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);

// rest of your code

旁注:错误报告应仅在暂存时完成,而不是生产。

  • 同时将or die(mysql_error())添加到mysql_query()

<强>旁注: