简体   繁体   中英

Double quotes in single quotes from table

In my table i have query:

$sql="SELECT * FROM `jom_x1_organizatori` 
      WHERE Organizator='".$sta_dalje."' Order by `Struka`,`Zanimanje`";

$sta_dalje =$_POST["state_id"] from another table and value is:

  1. ЈУ Гимназија са техничким школама Дервента
  2. "ПРИМУС" Градишка

In case 1 working.

How to make query?

Firts of all: Never build the query by concatenating the query string with user input! If you do, then escape the input with the library's dedicated function ( mysqli_real_escape_string for example). Without escaping you will open a potential security hole (called SQL injection ).

"ПРИМУС" Градишка is not working because after concatenating, the query will be invalid. Now imagine, what happens, if I post the following input: '; DROP TABLE jom_x1_organizatori; -- '; DROP TABLE jom_x1_organizatori; --

Your query will be:

SELECT * FROM `jom_x1_organizatori` 
      WHERE Organizator=''; DROP TABLE jom_x1_organizatori; --' Order by `Struka`,`Zanimanje`

Whenever you can use prepared statements to bind parameters (and let the library to do the hard work), but always escape and validate your input (using prepared statements, escaping is done by the library)!

$sta_dalje = (sting)$_POST["state_id"]; // Do filtering, validating, force type convertation, etc!!

// Prepare the statement (note the question mark at the end: it represents the parameter)
$stmt = $mysqlLink->mysqli_prepare(
    "SELECT * FROM `jom_x1_organizatori` WHERE Organizator = ?"
);

// Bind a string parameter to the first position
$stmt->bind_param("s", $sta_dalje);

For more info about prepared statements:

Please note that the old mysql extension is deprecated, do not use it if not necessary!

Just a side note

Do not use SELECT * FROM , always list the columns. It prevents to query unnecessary data and your code will be more resistant to database changes, plus debugging will be a bit simplier task.

Use escape string

$sta_dalje = mysqli_real_escape_string($con, $_POST["state_id"]);

And your where condition can be simply

 Organizator='$sta_dalje'

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