0

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

6 Answers 6

1

try

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

Note:- Stop using mysql_ as it is deprecated*

Learn about trim()

Sign up to request clarification or add additional context in comments.

Comments

1

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. This is good practice anyway, because the old 'mysql' functions are deprecated and will be removed. Here is the documentation for mysqli, which will be the easiest upgrade path for you.

First, put the parameters of your query into variables.

$input = '222 ';

Then use 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.

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).

Comments

0

Use the trim() function;

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

Comments

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

Comments

0

Use the following PHP function:

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

Comments

0

you can use trim in php and also mysql

see here

also you can use preg_replace('/[\s]/' , '' , $value); to get any whitespace out of string

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.