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

时间:2014-07-10 06:06:59

标签: php mysql sql

我尝试根据测试结果返回的行数选择要使用的查询。

    $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;
    ...

我正在检查Notifications表以查看UserID是否存在,如果它没有加载Users表中存在的内容,如果有,则它会加载Notifications表中的所有内容。

我回复$result并加载了正确的语句,但它没有执行。当我运行从PHP预览获得的连接查询时,它返回正常。

在我必须使用if / else之前,我正在运行第一个查询,从Notifications表中加载所有内容,并且加载得很好。我错过了什么?

2 个答案:

答案 0 :(得分:2)

您可以使用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'"; 

答案 1 :(得分:1)

您遗失了在所有$result上使用 mysql_query()执行查询

同时更改(应引用查询变量),因此请更改所有变量$id引用

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

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

注意: - mysql_*已被弃用,使用mysqli_*PDO