How to write update query using some {$variable} with example
如何使用一些{$variable}
编写更新查询,例如:
$query="update subjects set values username='{$name}', hash_password='{$pass}' where id=1";
You cannot use values
there, it should be:
$query="update subjects set username='{$name}', hash_password='{$pass}' where id=1";
But I would recommend using a prepared statement instead of dumping variables straight into your query.
Create a PDO connection:
// Usage: $db = connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword);
// Pre: $dbHost is the database hostname,
// $dbName is the name of the database itself,
// $dbUsername is the username to access the database,
// $dbPassword is the password for the user of the database.
// Post: $db is an PDO connection to the database, based on the input parameters.
function connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword)
{
try
{
return new PDO("mysql:host=$dbHost;dbname=$dbName;charset=UTF-8", $dbUsername, $dbPassword);
}
catch(PDOException $PDOexception)
{
exit("<p>An error ocurred: Can't connect to database. </p><p>More preciesly: ". $PDOexception->getMessage(). "</p>");
}
}
Init it like this:
$host = 'localhost';
$user = 'root';
$databaseName = 'databaseName';
$pass = '';
And call it like this:
$db = connectToDatabase($host, $databaseName, $user, $pass);
And use a function like this:
function update($db, $username, $password, $id)
{
$query = "UPDATE subjects SET username = :username, hash_password = :password WHERE id = :id;";
$statement = $db->prepare($query); // Prepare the query.
$result = $statement->execute(array(
':username' => $username,
':password' => $password,
':id' => $id
));
if($result)
{
return true;
}
return false
}
Now finally, you can do something like:
$username = "john";
$password = "aefasdfasdfasrfe";
$id = 1;
$success = update($db, $username, $password, $id);
You also avoid sql injection by doing it like this (preparing the statements, and executing the variables into the statement).
If you don't wanna read up on context/database escaping, this is how you avoid such problems using PDO
for example:
$pdo = new PDO('mysql:host=localhost;dbname=db', 'user', 'pw');
$pdo->prepare("update subjects set values username=?, hash_password=? where id=?")
->execute(array($user, $pass, 1));
See also:
上一篇: 这是从SQL注入安全吗?