在 PHP 中使用 OR 的长 MySQL 语句


Long MySQL statements with OR in PHP?

我有一个菜鸟问题,但我在网上没有找到任何答案,因为我认为这是一些特殊问题。我正在编写一个具有自动刷新功能的消息系统。

这是为了获取数据库中的最新 ID:

$query = mysql_query("SELECT * FROM `messages` 
                          WHERE `requestor`='".$_POST['user_id']."' 
                          AND `target`='".$_POST['target_id']."' 
                          OR `requestor`='".$_POST['target_id']."' 
                          AND `target`='".$_POST['user_id']."' 
                          ORDER BY `id` ASC");
$rows = mysql_fetch_array($query);
$id = $rows['id'];      //latest message id at this moment
$lastSeenID = $_POST['msg_id'];     //This is the latest id which is shown on the client

现在,我需要 ID 大于客户端上最后一个已知 id 的列。($lastSeenID)。

但这不会以正确的方式工作。

mysql_query("SELECT * FROM `messages` 
             WHERE `id` > '".$lastSeenID."' 
             AND `requestor`='".$_POST['user_id']."' 
             AND `target`='".$_POST['target_id']."' 
             OR `requestor`='".$_POST['target_id']."' 
             AND `target`='".$_POST['user_id']."' 
             ORDER BY `id` ASC")

我希望你能帮助我。

请开始喜欢查询参数:

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s'n", mysqli_connect_error());
    exit();
}
$city = "Amersfoort";
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {
    /* bind parameters for markers */
    $stmt->bind_param("s", $city);
    /* execute query */
    $stmt->execute();
    /* bind result variables */
    $stmt->bind_result($district);
    /* fetch value */
    $stmt->fetch();
    printf("%s is in district %s'n", $city, $district);
    /* close statement */
    $stmt->close();
}
/* close connection */
$mysqli->close();
?>

代表OP发布。

我得到了工作代码(感谢您的括号建议)。

mysql_query("SELECT * FROM `messages` WHERE (`id` > '".$lastSeenID."' AND `requestor`='".$_POST['user_id']."' AND `target`='".$_POST['target_id']."') OR (`id` > '".$lastSeenID."' AND `requestor`='".$_POST['target_id']."' AND `target`='".$_POST['user_id']."') ORDER BY `id` ASC");

试试这个:

mysql_query("SELECT * FROM `messages` WHERE (`id` > '$lastSeenID' AND `requestor`='$_POST['user_id']' AND `target`='$_POST['target_id']' OR `requestor`='$_POST['target_id']' AND `target`='$_POST['user_id']') ORDER BY `id` ASC");

或 MySQLi

mysqli_query($con,"SELECT * FROM `messages` WHERE (`id` > '$lastSeenID' AND `requestor`='$_POST['user_id']' AND `target`='$_POST['target_id']' OR `requestor`='$_POST['target_id']' AND `target`='$_POST['user_id']') ORDER BY `id` ASC");