我的代码中有一个SQL查询,我想将其转换为一个准备好的语句,以阻止SQL注入等漏洞。这就是我想要转换的:
<?php
$query = "SELECT * from `wp_posts` WHERE ID=$pid ";
$result = mysqli_query($link, $query);
//$id=$row['Gallery_Id'];
while($row = mysqli_fetch_array($result)){
?>
<h2 align="center"> <?php echo $row['post_title']; ?> </h2><br>
<div class="paracenter">
<p id="cont"><?php echo $row['post_content']; ?></p>
<hr color="black" width="10%">
</div>
<?php } ?>
这是我试过的,但没有用。
$query = "SELECT * from `wp_posts` WHERE ID=? ";
$stmt = mysqli_prepare($link, $query);
if($stmt){
mysqli_stmt_bind_param($stmt, "i", $pid);
mysqli_stmt_bind_result($stmt, $dbpid);
mysqli_stmt_execute($stmt);
mysqli_stmt_fetch($stmt);
}
$result = mysqli_query($link, $query);
//$id=$row['Gallery_Id'];
while($row = mysqli_stmt_fetch($result)){
?>
<h2 align="center"> <?php echo $row['post_title']; ?> </h2><br>
<div class="paracenter">
<p id="cont"><?php echo $row['post_content']; ?></p>
<hr color="black" width="10%">
</div>
<?php } ?>
网上几乎所有的例子都没有使用我使用的程序方法。我该如何纠正?
显式选择稍后要获取的列,而不是在select子句中使用*
。
参数bindingly是通过引用实现的,因此必须先声明$pid
,然后使用——而不是直接将整数2
写入绑定调用。
在绑定结果时,提供与SELECT子句中的列相关的变量。
代码:(PHPize.online Demo)
$pid = 2;
$sql = <<<SQL
SELECT post_title, post_content
FROM wp_posts
WHERE ID=?
SQL;
$stmt = mysqli_prepare($mysqli, $sql);
mysqli_stmt_bind_param($stmt, "i", $pid);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $title, $content);
if (mysqli_stmt_fetch($stmt)) {
?>
<h2 align="center"><?php echo $title; ?></h2><br>
<div class="paracenter">
<p id="cont"><?php echo $content; ?></p>
<hr color="black" width="10%">
</div>
<?php
}
也就是说,您在Wordpress应用程序内部进行编码,Wordpress有自己的辅助方法来提供准备好的语句功能(尽管它不是过程语法,但它非常整洁)。
$row = $wpdb->get_results($wpdb->prepare($sql, [$pid]));
if ($row) {
?>
<h2 align="center"><?php echo $title; ?></h2><br>
<div class="paracenter">
<p id="cont"><?php echo $content; ?></p>
<hr color="black" width="10%">
</div>
<?php
}
最后,使用Wordpress专用函数get_post()
可能是最可取的。
https://developer.wordpress.org/reference/functions/get_post/
$post = get_post($pid);
// $post->post_title;
// $post->post_content;