PHP MYSQL从列中选择查询条空间
我有一个这样的问题PHP MYSQL从列中选择查询条空间,php,mysql,Php,Mysql,我有一个这样的问题 mysql_query("select * from codes where code='222 '"); 我想在查询中去掉列中的空格,这样就可以 mysql_query("select * from codes where code=strippedstring('222 ')" 做这件事最好的方法是什么 $value=trim('222 '); mysql_query("select * from codes where code=$value" 注意:-停止使用m
mysql_query("select * from codes where code='222 '");
我想在查询中去掉列中的空格,这样就可以
mysql_query("select * from codes where code=strippedstring('222 ')"
做这件事最好的方法是什么
$value=trim('222 ');
mysql_query("select * from codes where code=$value"
注意:-停止使用mysql,因为它已被弃用
了解使用trim()
功能
mysql_query("select * from codes where code=trim('222 ')"
您可以在php和mysql中使用trim
您还可以使用
preg_replace('/[\s]/','$value)
要从字符串中提取任何空格,请使用以下PHP函数:
mysql_query("select * from codes where code=".strippedstring('222 ').");
首先,最好将查询的参数(查询的值和变量)与查询本身分开。为此,您需要使用mysqli或PDO。无论如何,这是一个很好的实践,因为旧的“mysql”函数已被弃用并将被删除。是mysqli的文档,这将是最简单的升级路径 首先,将查询的参数放入变量中
$input = '222 ';
然后使用trim()
最后,运行查询
$stmt = mysqli_stmt_init($database);
mysqli_stmt_prepare($stmt, 'select * from codes where code = ?');
mysqli_stmt_bind_param($stmt, 's', $input);
mysqli_stmt_execute($stmt);
//Note: Make sure to know how many columns you're getting.
$output = array();
mysqli_stmt_bind_result($stmt, $id, $name, $code);
while (mysqli_stmt_fetch($stmt)) {
$output[] = array($id, $name, $code);
}
这看起来比您拥有的代码多得多,但每一行都有一个重要的用途,有时您可能需要在它们之间做其他事情。我强烈建议您仔细阅读mysqli文档,虽然它们允许您执行一个简单的“mysqli\u query()
”调用,这与您正在使用的“mysql\u query()
”几乎相同,但不好的想法是它会让您面临SQL注入攻击之类的攻击
这篇文章很好地概述了为什么应该使用准备好的语句,并简要介绍了如何在各种语言(包括PHP)中使用它们
$input = trim($input);
$stmt = mysqli_stmt_init($database);
mysqli_stmt_prepare($stmt, 'select * from codes where code = ?');
mysqli_stmt_bind_param($stmt, 's', $input);
mysqli_stmt_execute($stmt);
//Note: Make sure to know how many columns you're getting.
$output = array();
mysqli_stmt_bind_result($stmt, $id, $name, $code);
while (mysqli_stmt_fetch($stmt)) {
$output[] = array($id, $name, $code);
}