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。