我有这个:
// 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'])."%' ";
答案 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
之前添加了一个空格以获得良好的衡量标准。