查询正在搜索所有用户记录,而不仅仅是我的记录


Query is searching all user records instead of just mine

我正在做这个搜索引擎,应该只搜索我的内容,但在搜索结果中也搜索其他用户的内容,这是私人的。PHP新手,需要帮助!谢谢!

        $sql = "SELECT client_visit.why, client_names.client_name,
        client_names.client_id, client_visit.notes, 
        client_visit.date_time, client_visit.v_id FROM 
        client_visit LEFT JOIN client_names ON 
        client_visit.client_is = client_names.client_id 
        WHERE client_visit.user_id = '$pid' 
        AND client_visit.why_visit LIKE '%$q%'
        OR client_visit.field1 LIKE '%$q%' 
        OR client_visit. field2 LIKE '%$q%' 
        OR client_visit. field3 LIKE '%$q%' 
        AND client_visit. field4 LIKE '%$q%' 
        OR client_visit. field5 LIKE '%$q%' 
        OR client_visit.v_notes LIKE '%$q%' 
        OR client_visit.date_time LIKE '%$q%'
        OR client_names.client_name LIKE '%$q%' 
        ORDER BY client_visit.id DESC LIMIT $start, $limit";

将逻辑分组到括号中,因此查询确实在做您认为它是什么。

WHERE client_visit.user_id = '$pid' 
AND
(
    client_visit.why_visit LIKE '%$q%'
    OR client_visit.field1 LIKE '%$q%' 
    OR client_visit. field2 LIKE '%$q%' 
    OR client_visit. field3 LIKE '%$q%'
)
AND
(
    client_visit. field4 LIKE '%$q%' 
    OR client_visit. field5 LIKE '%$q%' 
    OR client_visit.v_notes LIKE '%$q%' 
    OR client_visit.date_time LIKE '%$q%'
    OR client_names.client_name LIKE '%$q%'
)

另一个注意事项,我希望您的数据正在被转义。如果没有,你想把它放在$sql = ...之前,给它一些保护。

$pid = (int) $pid;
$q = mysql_real_escape_string($q);
$start = (int) $start;
$limit = (int) $limit;

试试这个:

  $sql = "SELECT client_visit.why, client_names.client_name,
            client_names.client_id, client_visit.notes, 
            client_visit.date_time, client_visit.v_id 
            FROM client_visit 
            LEFT JOIN client_names ON client_visit.client_is = client_names.client_id 
            WHERE ( client_visit.user_id = '$pid' )
                   AND
           ( client_visit.why_visit LIKE '%$q%'
            OR client_visit.field1 LIKE '%$q%' 
            OR client_visit. field2 LIKE '%$q%' 
            OR client_visit. field3 LIKE '%$q%' 
            AND client_visit. field4 LIKE '%$q%' 
            OR client_visit. field5 LIKE '%$q%' 
            OR client_visit.v_notes LIKE '%$q%' 
            OR client_visit.date_time LIKE '%$q%'
            OR client_names.client_name LIKE '%$q%'
            ) 
            ORDER BY client_visit.id DESC LIMIT $start, $limit";

使用括号对条件进行分组。

相关文章: