Question:
Faced the following problem: the database query does not pass. I receive data from forms using AJAX (I pack it in JSON and send it to the server). Further, using PDO in PHP, I connect to MSSQL, where the database is located. The data comes to the server, but the query is not executed to the database.
<?php
try {
$db = new PDO("sqlsrv:Server=WIN-H0CPAVNR2UI\SQLEXPRESS;Database=UsersForProject");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
print("Couldn't connect to the database".$e->getMessage());
}
$user = json_decode($_REQUEST['user']);
$user->password = hash('md5', $user->password);
$query = $db->exec("SELECT * FROM dbo.Users WHERE Login = '".$user->login."' AND Password = '".$user->password."'") or die("Query error");
var_dump($query);
if ($query==1) {
$cookie_name = $user->login;
$cookie_value = $user->password;
setcookie($cookie_name, $cookie_value, time() + 3600);
}?>
Tell me, please, what to do. I tried to use single quotes for variables and the query() function, which returns a query string.
Answer:
I solved the problem using the prepare() function
$query = $db->prepare('SELECT * FROM dbo.Users WHERE Login = ? AND Password = ? ') or die("Query error");
$query->execute(array($user->login, $user->password));
$res = $query->fetchAll();
if ($user->login == $res[0][1] && $user->password == $res[0][3]) {
$cookie_name = $user->login;
$cookie_value = $user->password;
setcookie($cookie_name, $cookie_value, time() + 3600);
}
var_dump($res);