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


Error when trying to query the DB on whether a user input is like 2 other fields in the DB

我有这个:

// 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'])."%' ";
}

我的表单上有一个名为plantname的用户输入字段。当用户在中输入内容时,我想检查它是像数据库中common_name字段中的值,还是像数据库中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'])."%' ";

您在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
}

这很糟糕,请将查询参数化。避免此问题和SQL注入。

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

strtolower($_POST['plant_name'])后面缺少空格和单引号。我在AND之前添加了一个空格,以便于度量。