如何用示例的{$ variable}编写更新查询
如何使用一些{$variable}
编写更新查询,例如:
$query="update subjects set values username='{$name}', hash_password='{$pass}' where id=1";
你不能在那里使用values
,它应该是:
$query="update subjects set username='{$name}', hash_password='{$pass}' where id=1";
但我会建议使用准备好的语句,而不是将变量直接放入查询中。
创建一个PDO连接:
// 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>");
}
}
像这样初始化:
$host = 'localhost';
$user = 'root';
$databaseName = 'databaseName';
$pass = '';
并像这样称呼它:
$db = connectToDatabase($host, $databaseName, $user, $pass);
并使用这样的功能:
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
}
现在最后,你可以做一些事情:
$username = "john";
$password = "aefasdfasdfasrfe";
$id = 1;
$success = update($db, $username, $password, $id);
你也可以通过这样做来避免sql注入(准备语句,并将变量执行到语句中)。
如果您不想阅读关于上下文/数据库转义的内容,则可以使用PDO
来避免此类问题,例如:
$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));
也可以看看:
上一篇: How to write update query using some {$variable} with example