-1

如何使用一些{$variable}示例编写更新查询,例如:

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

3 回答 3

2

创建 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 注入。

于 2013-03-22T21:10:17.680 回答
1

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

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

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

于 2013-03-22T21:08:31.580 回答
0

如果您不想阅读上下文/数据库转义,这就是您避免此类问题的方法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)); 

也可以看看:

于 2013-03-22T21:10:04.507 回答