Php 试图查询数据库中的用户输入是否与数据库中的其他两个字段类似时出错
我有这个:Php 试图查询数据库中的用户输入是否与数据库中的其他两个字段类似时出错,php,sql,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'])."%' "; } 我
// 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字段中的值,或者类似于数据库中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\u real\u escape\u string
对用户输入进行转义,或者使用准备好的语句(更好的选择):
准备好的语句示例:
$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
}
strtolower($\u POST['plant\u name'])
后面缺少空格和单引号。
我在
和前面添加了一个空格,以便更好地测量。这很糟糕,请将查询参数化。避免这个问题和SQL注入。在ORI理解准备好的语句之前,您缺少了”
和一个空格,我的代码中的其他地方都有它们-但是我不确定如何在这种类型的代码中为准备好的语句执行语法,因为如果您知道我的意思,它与普通查询略有不同mean@user1227124我补充说这是一个动态构建此类查询的示例。
$where .= " AND LOWER(common_name) LIKE '".strtolower($_POST['plant_name']) . "' OR LOWER(latin_name) LIKE '".strtolower($_POST['plant_name'])."%' ";