简体   繁体   English

if语句检查mysql行是否存在,然后选择下一个查询

[英]if statement to check if mysql row exists, then selecting next query

I'm attempting to select a query to use based on the number of rows returned by a test result. 我正在尝试根据测试结果返回的行数选择要使用的查询。

    $id = mysql_real_escape_string(htmlspecialchars($_POST['id']));

    $result = "SELECT FROM Notifications WHERE UserID=$id";
    $r = e_mysql_query($result);
    $row = mysql_fetch_array($r);
    $num_results = mysql_num_rows($result); 
    $result = '';

    if ($num_results != 0) {
        $result =
            "SELECT U.UserID,U.FirstName,U.LastName, " .
            " DATE_FORMAT(U.BirthDate,'%m-%d-%Y') AS BirthDate, " .
            " N.Email, N.Phone,N.ProviderName, N.SubNotifications " .
            " FROM Users U, Notifications N " .
            " WHERE U.LocationID=0 " .
            " AND N.UserID='$id'";
    } else  {
        $result =
            "SELECT UserID, FirstName, LastName," .
            " DATE_FORMAT(BirthDate, '%m-%d-%Y') AS BirthDate " .
            " FROM Users " .
            " WHERE LocationID = 0 " .
            " AND UserID ='$id'";

    }
    echo $result;
    e_mysql_result($result); //Bastardized/homegrown PDO

    if ($row = mysql_fetch_assoc($result)) {
        $retValue['userInfo'] = $row;
    ...

I'm checking the Notifications table to see if the UserID exists there, if it doesn't it loads what does exist from the Users table, if it does, then it loads everything from the Notifications table. 我正在检查Notifications表以查看UserID是否存在,如果它不加载Users表中存在的内容,如果有,则它会加载Notifications表中的所有内容。

I'm echoing out the $result and the proper statement is loaded, but it doesn't execute. 我正在回显$result并加载了正确的语句,但它没有执行。 When I run the concatenated query I get from the PHP preview, it returns just fine. 当我运行从PHP预览获得的连接查询时,它返回正常。

Before I had to if/else this, I was running the first query, loading everything from the Notifications table, and it was loading just fine. 在我不得不使用if / else之前,我正在运行第一个查询,从Notifications表中加载所有内容,并且加载得很好。 What am I missing? 我错过了什么?

You can do the whole thing with one query with a LEFT JOIN. 您可以使用LEFT JOIN进行一次查询。

$query= "SELECT U.UserID, U.FirstName,U.LastName,  " .
    " DATE_FORMAT(U.BirthDate,'%m-%d-%Y') AS BirthDate,  " .
    " N.Email, N.Phone,N.ProviderName, N.SubNotifications  " .
    " FROM Users U  " .
    " LEFT JOIN Notifications N  " .
    " ON U.UserID = N.UserID  " .
    " WHERE U.UserID = '$id'"; 

You are missing execute a query with mysql_query() on all $result 您缺少在所有$result上使用mysql_query()执行查询

Also change (query variable should be quoted) so change your all variables $id quoted 同时更改(应引用查询变量),以便更改所有变量$id引用

$result = "SELECT FROM Notifications WHERE UserID=$id";

to

$result = "SELECT FROM Notifications WHERE UserID='$id'";
$r = mysql_query($result);

Note :- mysql_* has been deprecated use mysqli_* or PDO : - mysql_*已被弃用,使用mysqli_*PDO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM