尝试查询数据库时,用户输入是否与数据库中的其他2个字段相同时出错

时间:2012-03-16 17:29:52

标签: php sql

我有这个:

// if there is a plant name
if (isset($_POST['plant_name']) && $_POST['plant_name']) {
$where .= "AND LOWER(common_name) LIKE '".strtolower($_POST['plant_name']) "OR LOWER(latin_name) LIKE '".strtolower($_POST['plant_name'])."%' ";
}

我的表单上有一个名为plant name的用户输入字段。当用户输入内容时,我想检查它是否是数据库中common_name字段中的值,或者是LIKE数据库中latin_name字段中的值。

我的错误是:

 Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING 

指向第53行,即这一行:

$where .= "AND LOWER(common_name) LIKE '".strtolower($_POST['plant_name']) "OR LOWER(latin_name) LIKE '".strtolower($_POST['plant_name'])."%' ";

3 个答案:

答案 0 :(得分:1)

您错过了PHP中的.和查询中的'

$where .= "AND LOWER(common_name) LIKE '".strtolower($_POST['plant_name']) . "' OR LOWER(latin_name) LIKE '".strtolower($_POST['plant_name'])."%' ";
                                                                           ^  ^

此外,如果您使用的是MySQL,LIKE不区分大小写,因此您无需使用LOWER

你应该至少使用mysql_real_escape_string来逃避用户输入,或者使用预备语句(更好的选择):http://php.net/manual/en/pdo.prepared-statements.php

准备好的陈述示例:

$query = 'SELECT * FROM `table` ';
$bindParams = array( );
$where = array( );

// if the post variable is set...
if( isset( $_POST['plant_name'] ) && !empty( $_POST['plant_name'] ) {
    // add the value to $bindParams
    $bindParams['plant_name'] = $_POST['plant_name'];
    // add the where clause to the array
    $where[] = 'common_name LIKE :plant_name OR latin_name LIKE :plant_name';
}

// do similar if blocks for other post variables

// build the where array into a string
if( count( $where ) > 0 )
    $query .= 'WHERE (' . implode( ') AND (', $where ) . ')';

// prepare and execute
$stmt = $db->prepare( $query );
if( $stmt->execute( $bindParams ) ) {
    // do stuff here
}

答案 1 :(得分:1)

这很讨厌,参数化您的查询。避免这个问题和SQL注入。

答案 2 :(得分:0)

$where .= " AND LOWER(common_name) LIKE '".strtolower($_POST['plant_name']) . "' OR LOWER(latin_name) LIKE '".strtolower($_POST['plant_name'])."%' ";

您在strtolower($_POST['plant_name'])之后错过了一个空格和单引号。 我在AND之前添加了一个空格以获得良好的衡量标准。