What should be: 1. Js sends the information from the $login variable to the php server 2. Php connects the database and gets the password for this login from the accounts table 3. If the value is not found - the php server sends true , if it is found - false 4. It triggers a specific code in js, depending on the server response. Help me find the error.

Js:

  $.post('check.php', {'login':login}, function(data) { if(data == "true"){ var div = document.querySelector("#login"); div.className = "true"; div.innerHTML = "Логин свободен!"; alogin = null; alogin = true; }else if(data == "false"){ var div = document.querySelector("#login"); div.className = "false"; div.innerHTML = "Логин занят!"; alogin = null; alogin = false; } }); 

Check.php

 <?php $login = $_POST['login']; include ("db.php"); $result = mysql_query("SELECT password FROM accounts WHERE login='$login'",$db); if(empty($result)){ echo("true"); }else{ echo("false"); } ?> 
  • Is there a mistake there? - Suvitruf
  • Of course, because I indicated the data in the database correctly, rechecked everything, but nothing works, oddly enough, although nothing is going to the console either, so I ask - Ivan Repin
  • one
    You did not write in the question what exactly does not work. The server does not receive the request? The client does not receive a response from the server? Does the customer get the wrong answer you expected? - Suvitruf
  • one
    @IvanRepin have you debugged your code? Checked what $login , $result and data are equal to? - Regent
  • And you should avoid entries like login='$login'" - a potential place for a hack. - Stepan Kasyanenko

1 answer 1

First, you need to screen variables in "", that is, login='{$login}' , secondly, this code is potential mysql injection, thirdly, mysql_query is deprecated since PHP 5.5, so use mysqli_query ( http: // php. net / manual / en / mysqli.query.php ), in the fourth, use an explicit result comparison:

 $mysqli = new mysqli("localhost", "my_user", "my_password", "world"); $result = $mysqli->query("SELECT * FROM FROM accounts WHERE login='{$login}'"); if($result !== FALSE) { echo 1; die; } echo 2; 

But of course it would be more correct to use PDO:

 /* Connect to a MySQL database using driver invocation */ $dsn = 'mysql:dbname=testdb;host=127.0.0.1'; $user = 'dbuser'; $password = 'dbpass'; try { $dbh = new PDO($dsn, $user, $password); } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); } $sth = $dbh->prepare('SELECT * FROM accounts WHERE login = ?'); $sth->execute(array($login)); $accounts = $sth->fetchAll(); if(!empty($accounts)) { echo 1; die; } echo 0;