Help good people, I can not understand what is here and how in php, in my opinion everything seems to be fine, but alas ...

It does not issue errors, it connects, it works in general, as it should, but the result is empty ... I probably request it incorrectly?

<? $host = "localhost"; $dbuser = "***user***"; $dbpass = "***pass***"; $db = "***mydb***"; $id = $_POST['id']; $link = mysql_connect($host, $dbuser, $dbpass) or die("Error connect!"); mysql_select_db($db, $link); if (!empty($id)) { $sql="SELECT * FROM myTable WHERE id LIKE " + $id; $data = mysql_query($sql); $res = mysql_result($data); echo $res; echo $data; } else { echo "Empty id"; } ?> 
  • var_dump($sql); to start. then here - Ipatiev
  • Do you have a string id and are you looking for a piece of this string? at least like is intended precisely for this. And for sampling by number fields and just for equality, the operator is equal. where id=xx - Mike
  • one
    Well, of course, the supposed statements about the fact that by this code all SQL injections are crying and that the mysql_query function has actually been banned from using. - Ipatiev

1 answer 1

Indeed, there is a lot that is wrong. Three major problems

  1. Incorrect PHP syntax. + does not combine strings. for this is the point.
  2. In any case, using concatenation, requests cannot be collected. To avoid a lot of problems, including SQL injections, you need to use substitutions in the query.
  3. The use of non-existent language functions.

It will be correct to make a request using PDO

 <? $host = "localhost"; $dbuser = "***user***"; $dbpass = "***pass***"; $db = "***mydb***"; $charset = 'utf8'; $dsn = "mysql:host=$host;dbname=$db;charset=$charset"; $opt = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false, ]; $pdo = new PDO($dsn, $dbuser, $dbpass, $opt); // все что выше этой строки надо вынести в отдельный файл // и подключать через include if (!empty($_POST['id'])) { $stmt = $pdo->prepare("SELECT * FROM myTable WHERE id = ?"); $stmt->execute([$_POST['id']]); $row = $stmt->fetch(); var_dump($row); } else { echo "Empty id"; } 
  • Thanks for the code, and especially for the link ... I have to make it a rule before reading and studying something, look at the year of the article) - Vladimir Alexandrov
  • one
    Yes, this is a very good rule, by the way - Ipatiev