举例说明如何使用{$variable}编写更新查询


How to write update query using some {$variable} with example

如何以{$variable}为例编写更新查询如:

$query="update subjects set values 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注入(准备语句,并在语句中执行变量)。

不能在这里使用values,它应该是:

$query="update subjects set username='{$name}', hash_password='{$pass}' where id=1";

但是我建议使用一个准备好的语句,而不是直接将变量转储到您的查询中。

如果你不想阅读上下文/数据库转义,以下是使用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)); 

参见:

    如何在PHP中防止SQL注入?
  • http://bobby-tables.com/