簡體   English   中英

我將如何編寫准備好的sql語句而不是使用real_escape PHP,MySQL

[英]how would i write prepared sql statements rather than using real_escape PHP, MySQL

public $id;
public $filename;
public $type;
public $size;
public $description;
public $title;

這就是我現在使用的,這很糟糕,

$sql = "INSERT INTO photographgallery 
              (filename,type,size,description,title)
    VALUES ('$sanitized_filename', '$sanitized_type', '$sanitized_size', '$sanitized_description', '$sanitized_title')"; 

我想知道我是否可以為此編寫一份准備好的聲明,我將如何處理它,我是堆棧。 救命。

在SQL中,使用問號占位符( ? )替換變量。 通過將查詢傳遞給mysqli::prepare創建mysqli_stmt ,然后通過調用mysqli_stmt::bind_param將變量綁定到占位符。 調用mysqli_stmt::execute來執行插入。 它看起來像這樣:

$sql = "INSERT INTO photographgallery 
            (filename, type, size, description, title)
          VALUES
            (?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
// The string 'ssiss' in the following means 'string, string, int, string, string'
//  and describes the types of the parameters.
$stmt->bind_param('ssiss', $filename, $type, $size, $description, $title);
$stmt->execute();
$stmt->close();  // always clean up after yourself
// Your variables, however you get them.    
$filename = "name1";
$type = "type1";
$size = 100;
$desc = "test desc";
$title = "title"

if($stmt = $mysqli->prepare("INSERT INTO photographgallery (filename, type, size, description, title) VALUES (?, ?, ?, ?, ?)") {
    $stmt->bind_param('ssiss', $filename, $type, $size, $desc, $title); //Assuming the variables are string, string, int, string, string respectively
    $stmt->execute();
    $stmt->close();
}

在代碼周圍使用if可確保僅在prepare語句沒有錯誤時才運行。 如果有錯誤,則prepare語句返回false。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM