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')";
我想知道我是否可以为此编写一份准备好的声明,我将如何处理它,我是堆栈。帮助
答案 0 :(得分:2)
在SQL中,使用问号占位符(?
)替换变量。通过将查询传递给mysqli_stmt
来创建mysqli::prepare
,然后通过调用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
答案 1 :(得分:1)
// 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。