Reputation: 455
Simple question. How do i make the query work? I know you can't directly use $_POST
in a query. But i do not know how to get this to work.
$sql = 'SELECT * FROM users WHERE `password` = $_POST[password] AND `username` = $_POST[username]';
$result = mysqli_query($link, $sql);
if (!$result) {
echo "DB Error, could not query the database\n";
echo 'MySQL Error: ' . mysqli_error($link);
exit;
I have also tried using the mysqli_real_escape_string like this :
$username_sql = mysqli_real_escape_string($link, $_POST['username']);
$password_sql = mysqli_real_escape_string($link, $_POST['password']);
This did not work as planned. As it did still not work.
Thanks,
Mike
Upvotes: 0
Views: 2524
Reputation: 24071
I think it is necessary to add at least one example of prepared statements, just to show that it is not more difficult and it makes your application safer (SQL-injection).
$stmt = $mysqli->prepare('SELECT * FROM users WHERE `password` = ? AND `username` = ?');
$stmt->bind_param("ss", $_POST[password], $_POST[username]);
$stmt->execute();
$stmt->bind_result($result);
$stmt->fetch();
// read the result...
$stmt->close();
Be aware that passwords should not be stored plain text, instead one should use the functions password_hash() and password_verify().
Upvotes: 4
Reputation: 2556
Use prepared statements to avoid sql injection and syntax errors with commas .
$sql = 'SELECT * FROM users WHERE `password` = ? AND `username` = ?';
$stmt = mysqli_stmt_init($link);
mysqli_stmt_prepare($stmt, $sql);
mysqli_stmt_bind_param($stmt, "ss", $_POST['password'], $_POST['username']);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while($row = mysqli_fetch_assoc($result){
echo $row['username'] .'<br>';
}
Upvotes: 4
Reputation: 1982
You answered your question yourself. mysqli_real_escape_string() is the way to go.
$sql = 'SELECT * FROM users WHERE `password` = "' . mysqli_real_escape_string($_POST[password]) . '" AND `username` = "' . mysqli_real_escape_string($_POST[username]') . '"';
Upvotes: 0
Reputation: 6661
use ''
with string comparison of MySQL
$username_sql = mysqli_real_escape_string($link, $_POST['username']);
$password_sql = mysqli_real_escape_string($link, $_POST['password']);
$sql = "SELECT * FROM users
WHERE `password` = '$username_sql' AND `username` = '$password_sql'";
Upvotes: 5