简体   繁体   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;

this is what i am using now, which is bad, 这就是我现在使用的,这很糟糕,

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

i was wondering if i could write a prepared statement for this, how would i go about it, i am stack. 我想知道我是否可以为此编写一份准备好的声明,我将如何处理它,我是堆栈。 help. 救命。

In your SQL you replace the variables with question-mark placeholders ( ? ). 在SQL中,使用问号占位符( ? )替换变量。 Create a mysqli_stmt by passing your query to mysqli::prepare , then bind your variables to the placeholders with a call to mysqli_stmt::bind_param . 通过将查询传递给mysqli::prepare创建mysqli_stmt ,然后通过调用mysqli_stmt::bind_param将变量绑定到占位符。 Call mysqli_stmt::execute to perform the insert. 调用mysqli_stmt::execute来执行插入。 It looks like this: 它看起来像这样:

$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();
}

Using the if around the code ensures that it only runs if the prepare statement has no errors. 在代码周围使用if可确保仅在prepare语句没有错误时才运行。 If there is an error the prepare statement returns false. 如果有错误,则prepare语句返回false。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM