简体   繁体   中英

how to correctly use mysqli_real_escape_string() Function in a query

I am trying to use the mysqli_real_escape_string() Function in a query.

This is my current code:

 $Product_Id = substr($prod_name, 14, (strlen($prod_name)-14));
 $get_query = "SELECT P FROM Product WHERE Product_Id =' .mysql_real_escape_string((int)$Product_Id))";

This does not work, it creates the following error:

Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in

But if i remove the mysqli_real_escape_string function my code works.

So what is the best way to do this, as i am trying to stop sql injection.

I am trying to use the mysqli_real_escape_string() Function in a query.

But you're actually not. In your query you're using mysql_real_escape_string() .

Plus that query is malformed, so it wouldn't work anyway. Your quotes are in the wrong places. Try the following:

$get_query = "SELECT P FROM Product WHERE Product_Id = " . (int) mysqli_real_escape_string($Product_Id);

Since $Product_Id is being cast to an integer , you won't need to wrap it in quotes within the query (assuming Product_Id column is integer-based; since you're casting it to an integer, I'm assuming it is).

And moving the type cast (int) from the argument within mysqli_real_escape_string() to actually preceding the function is what you're looking for. Although it's not necessary to cast $Product_Id at this time as it is redundant and could actually pose more problems than it'd solve in some circumstances (Ie. assume $Product_Id was somehow set to a string [ $Product_Id = 'Marcus' ], and you then cast it to an integer: (int) $Product_Id it'd return 0 , but no error). A negative integer would also slip through which I'm assuming you don't have negative $Product_Id 's, right? There are much better ways to detect, and handle, variable types prior to sending them to a query. But we can get into that another time.

In your query you had an erroneous single-quote ( WHERE Product_Id =' ) which was causing a parsing error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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