There is such a request:

$sql_ticket = "SELECT * FROM tickets WHERE `id`=".$id." AND `status`=\"close\" ORDER BY id DESC"; 

If instead of ".$id." insert the desired number, then the query is executed. If I pass the required number through a variable, it gives an error:

You have an error in your SQL syntax; If you’re on the right line, I’m checking your order.

What is wrong doing? Please help me figure it out. I have already tried everything I know, I don’t understand what’s wrong ...

Closed due to the fact that off-topic participants Alexey Shimansky , Visman , user194374, cheops , aleksandr barakin Aug 8 '16 at 6:39 .

It seems that this question does not correspond to the subject of the site. Those who voted to close it indicated the following reason:

  • "The question is caused by a problem that is no longer reproduced or typed . Although similar questions may be relevant on this site, solving this question is unlikely to help future visitors. You can usually avoid similar questions by writing and researching a minimum program to reproduce the problem before publishing the question. " - Alexey Shimansky, Visman, Community Spirit, cheops, aleksandr barakin
If the question can be reformulated according to the rules set out in the certificate , edit it .

  • maybe you do not have a number in the ITD? Can you write the full code before the request? - Alexey Shimansky
  • Show which string you get in the $ sql_tikket variable during the execution of the codes. Surely something is simply not so substituted, but in order to understand what it is, you need to look at what line it turned out after the substitution. - Xander
  • And ps. $ Id. "?? and sql injections ... - Denis Kotlyarov
  • @DenisKotlyarov, aha, 10 pieces! Where does $id come from is not yet known to write about the injection. - Visman
  • What are 10 pieces? And so yes, in fact, the author has a mess with php. - Denis Kotlyarov

1 answer 1

In order for such errors to never occur, as well as for a variety of other reasons, in order to correctly compile a SQL query with the insertion of a value from a variable, this insertion must be done through the placeholder .

It is quite simple. For example using PDO :

 # 1. В запросе вместо переменной пишем знак вопроса $sql = "SELECT * FROM tickets WHERE id=? AND status='close'"; # 2. Затем запрос подготавливаем $stmt = $pdo->prepare($sql); # 3. Исполняем запрос, передавая в него переменную. $stmt->execute([$id]); # 4. Получаем запрошенные данные. $ticket = $stmt->fetch() 

It is very simple, absolutely safe (as opposed to passing a variable directly to a query!) And 100% guaranteed against the appearance of syntax errors caused by data.

Any other options obviously false