2013-03-22 19 views
-1

如何使用寫更新查詢寫更新查詢一些{$variable}與例如 例如:

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

這是正確的,假設您設置了這些變量。 – 2013-03-22 20:58:06

+0

但我有這樣的錯誤「查詢錯誤.. !!你的SQL語法有錯誤;查看與你的MySQL服務器版本相對應的手冊,在正確的語法附近使用value values ='Veerendra Kakumanu',hash_password ='veeru'其中id = 1'在第1行「 示例代碼 $ name = $ _ POST [」name「]; $ pass = $ _ POST [「pass」]; $ query =「更新主題設置值username ='{$ name}',password ='{$ pass}'where id = 1」; $ result = mysql_query($ query,$ connection); – Veerendra 2013-03-22 21:03:52

+0

而不是谷歌PDO和準備報表tuturial;從長遠來看,這比將變量插入到SQL查詢中更麻煩。 – mario 2013-03-22 21:04:09

回答

1

不能使用values那裏,它應該是:

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

但我會建議使用準備的語句,而不是將變量直接轉換爲查詢。

+0

謝謝您先生。您可以告訴我如何編寫準備好的聲明plzz – Veerendra 2013-03-22 21:12:41

+0

好處在於準備好的聲明和值(+1),因爲它們是用於插入的。我舉了一個關於如何在我的答案中使用它們的例子。 – Jonast92 2013-03-22 21:13:31

+0

@VeǝruWeerǝndra不客氣。 – jeroen 2013-03-22 21:17:45

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)); 

參見:

+0

非常感謝你 – Veerendra 2014-12-15 05:37:23

2

創建一個PDO連接ction:

// 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注入。

+0

非常感謝你.... :-) – Veerendra 2013-03-22 21:17:14

相關問題