SQL查询失败

时间:2013-04-10 06:37:00

标签: php mysql sql

我希望查询最初返回c_id> 0的所有记录,然后根据通过文本框提供的后续条件进行过滤。但是,我第一次访问页面时没有打印任何记录。这是代码:

$ctitle = mysql_real_escape_string($_POST['ctitle']);
$csubject = mysql_real_escape_string($_POST['csubject']);
$creference = mysql_real_escape_string($_POST['creference']);
$cobjecttype = mysql_real_escape_string($_POST['cobjecttype']);
$cmaterial = mysql_real_escape_string($_POST['cmaterial']);
$ctechnic = mysql_real_escape_string($_POST['ctechnic']);
$cartist = mysql_real_escape_string($_POST['cartist']);
$csource = mysql_real_escape_string($_POST['csource']);

    $sql = "SELECT * FROM collections WHERE (
    c_id>0 AND
    `ctitle` LIKE '{$ctitle}' AND
    `csubject` LIKE '{$csubject}' AND
    `creference` LIKE '{$creference}' AND
    `cobjecttype` LIKE '{$cobjecttype}' AND
    `cmaterial` LIKE '{$cmaterial}' AND
    `ctechnic` LIKE '{$ctechnic}' AND
    `csource` LIKE '{$csource}' AND
    `cartist` LIKE '{$cartist}'
    )ORDER BY c_id DESC";

当我回显查询时,我得到以下打印:

request "Could not execute SQL query" SELECT * FROM collections WHERE ( c_id>0 AND `ctitle` LIKE '' AND `csubject` LIKE '' AND `creference` LIKE '' AND `cobjecttype` LIKE '' AND `cmaterial` LIKE '' AND `ctechnic` LIKE '' AND `csource` LIKE '' AND `cartist` LIKE '' )ORDER BY c_id DESC

我应该从哪里离开?

3 个答案:

答案 0 :(得分:0)

)ORDER BY

之间加一个空格

答案 1 :(得分:0)

你不需要围绕where子句元素的大括号。

答案 2 :(得分:0)

好的......我想我明白了......尝试用 LIKE'%'替换 LIKE''

LIKE''无效,因为它只显示空列。通过添加通配符(%),它将显示与所有内容匹配的所有行。但是,它可能是一个更好,更清晰的解决方案,可以完全动态地构建查询,省略空的WHERE条件。