简体   繁体   中英

PHP query string with variables in it not working

When I build a query string using variables in PHP, it does not seem to be working. My current query is:

$u = "admin";
$hash = password_hash("password", PASSWORD_DEFAULT);
$set_login = "INSERT INTO users (username, password) VALUES ({$u}, {$hash})";

*I am executing the query further down in the script

If I replace {$u} with the string literal it represents, and replace {$hash} with just a string literal for a password, such as password , the query works fine. However, when I introduce variables that is when it breaks. I've tried breaking up the query string and using the concatenation operator:

$set_login = "INSERT INTO users (username, password) VALUES ( " . $u . ", " . $hash . ")";

This did not work either. I then thought it might be something with the hash, so I modified the code to (for testing):

$u = "admin";
$p = "password";
$set_login = "INSERT INTO users (username, password) VALUES ({$u}, {$p})";

This did not work either.

The best solution is to use prepared statements , it's very simple.

here's how you will do it with prepared statements

mysqli

<?php
$u = "admin";
$hash = password_hash("password", PASSWORD_DEFAULT);
$set_login = "INSERT INTO users (username, password) VALUES (?,?)";
$query = $ConnectionString->prepare($set_login);
$query->bind_param("ss",$u,$hash);

if($query){
    echo "success";
}else{

    error_log("error".$ConnectionString->error);
}

?>

PDO

<?php
$u    = "admin";
$hash = password_hash("password", PASSWORD_DEFAULT);

$query = $ConnectionString->prepare("INSERT INTO users (username, password) VALUES (?,?)")->execute(array($u,$hash));

if ($query) {
    echo "success";
} else {

    error_log("error" . $ConnectionString->errorInfo());
}

?>

Some useful resources.

PDO Connection PDO Tutorials Mysqli Prepared

NB: AS Jay have indicated in his comment make sure your password field size in the database is at least 60 Characters

In your query the problem is that you did not wrapper the strings around quotes

Your query should be:

$set_login = "INSERT INTO admin (uname, upass) VALUES ('{$u}', '{$hash}')";

But this is not the best recommended way of doing quires, you should use one of the methods above using prepared statements.

Here's why you should : Bobby Tables

INSERT INTO users (username, password) VALUES ('{$u}', '{$hash}')

Don't forget to wrap string with a quotation mark

But as mentioned in comments, it's bad idea to put data directly, use prepared statements

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM