简体   繁体   English

PHP MYSQL从列中选择查询条带空间

[英]PHP MYSQL select query strip spaces from column

I have a query like this 我有这样的查询

mysql_query("select * from codes where code='222 '");

I want to strip spaces in the column in the query so it should be like 我想在查询中的列中删除空格,所以它应该是这样的

mysql_query("select * from codes where code=strippedstring('222 ')"

What would be the best way to do this 什么是最好的方法来做到这一点

try 尝试

$value=trim('222 ');
mysql_query("select * from codes where code=$value"

Note:- Stop using mysql_* as it is deprecated 注意: - 不推荐使用mysql_ *,因为它已被弃用

Learn about trim() 了解trim()

First of all, it is best if you separate the parameters of the query (the values and variables queried) and the query itself. 首先,最好将查询的参数(查询的值和变量)与查询本身分开。 To do this, you'll need to use mysqli or PDO. 为此,您需要使用mysqli或PDO。 This is good practice anyway, because the old 'mysql' functions are deprecated and will be removed. 无论如何,这是一种很好的做法,因为旧的'mysql'函数已被弃用并将被删除。 Here is the documentation for mysqli, which will be the easiest upgrade path for you. 是mysqli的文档,它将是最简单的升级途径。

First, put the parameters of your query into variables. 首先,将查询的参数放入变量中。

$input = '222 ';

Then use trim() . 然后使用trim()

$input = trim($input);

And last, run your query. 最后,运行您的查询。

$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);
}

This looks like a LOT more code than you have, but each line serves an important purpose, and sometimes you might want to do other things between them. 这看起来比你拥有的代码多得多,但是每一行都有一个重要的目的,有时候你可能想要在它们之间做其他事情。 I would highly recommend looking through the mysqli documentation, and while yes they allow you to do a simple ' mysqli_query() ' call that's nearly identical to the ' mysql_query() ' you're using, it's a bad idea is it leaves you open for things like SQL injection attacks. 我强烈建议查看mysqli文档,虽然是的,但是它们允许你做一个简单的' mysqli_query() '调用,它与你正在使用的' mysql_query() '几乎完全相同,这是一个坏主意,它会让你打开对于像SQL注入攻击这样的东西。

Here is a good overview about why you should use prepared statements, and a quick look at how to use them in various languages (including PHP). 这里有一个很好的概述,为什么你应该使用预准备语句,并快速了解如何在各种语言(包括PHP)中使用它们。

使用trim()函数;

mysql_query("select * from codes where code=trim('222 ')"

you can use trim in php and also mysql 你可以在php和mysql中使用trim

see here 看这里

also you can use preg_replace('/[\\s]/' , '' , $value); 你也可以使用preg_replace('/[\\s]/' , '' , $value); to get any whitespace out of string 从字符串中获取任何空格

使用以下PHP函数:

mysql_query("select * from codes where code=".strippedstring('222 ').");
$sql="select * from codes where code='".trim('222 ')."'";
mysql_query($sql);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM