创建Prepared SQL语句,其中SQL语句中的值已经相等(SQL注入)


Create Prepared SQL Statement where in the SQL Statement already equal values (SQL Injection)

创建了一个按用户id获取帖子的表单。我的问题是:如何将其转换为准备好的语句看到了为值分配var的地方,但是如何准备一个已经等于请求中某个值的SQL语句声明是:

 $sql = "SELECT * FROM posts, users WHERE posts.user_id = users.id AND
 posts.user_id = ".$_GET['uid'];"

完整的PHP语句
 nbsp nbsp nbsp 这段代码还运行"PHP函数",但写操作不需要它(我怀疑)
nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp;如果是,请告诉我,我可以提供

<?php
if(isset($_GET['uid'])) {
    $sql="SELECT * FROM posts, users WHERE posts.user_id = users.id
                    AND posts.user_id = ".$_GET['uid'];
} else {
    $sql="SELECT * FROM posts, users WHERE posts.user_id = users.id
                    ORDER BY post_id DESC";
}
include_once('dbconnect.php');
$result=mysql_query($sql);
if(!$result) {
    error_reporting(1);
    echo mysql_error();
}
$postID=$_GET['pid'];
while($row=mysql_fetch_array($result)) {
    echo $row['post_id'].$row['post_title'].$row['username'];
    if(isset($_SESSION['id'])) {
        if(getSessionUserId() == $row['user_id']) {
            echo $row['post_id'].$row['post_id'];
        }
    }
    echo substr($row['post_content'], 0, 200).$row['post_id'];
}
?>

(1)发现我需要创建一个将名称设置为UTF8的数组;完成后,我就可以连接到服务器了

(2)然后需要将呼叫发送到服务器

(3)然后从服务器[fetchAll()]获取结果

<?php
    $dsn = 'mysql:host=HOST;dbname=DATABASE';
    $username = 'USERNAME';
    $password = 'PASSWORD';
    $options = array(
        PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8', PDO::ATTR_PERSISTENT => false
    );
    try
    {
        $dbh = new PDO($dsn, $username, $password, $options);
        echo '<h4 class="text-success">PDO connection created Successfully</h4>';
        print '<h4 class="text-info">Connection Info: </h4><p class="text-warning">'.$dsn.'</p>';
        print '<p class="text-warning"><b>Username: </b>'.$username.'</p><br />';
    }
    catch(PDOException $e)
    {
        echo '<p class="text-danger">'.$e->getMessage().'</p>';
        die();
    }
    $dbh = new PDO($dsn, $username, $password);
    $stmt = $dbh->prepare('SELECT * FROM posts, users WHERE posts.user_id = users.id ORDER BY post_id DESC');
    $stmt->execute();
    $result = $stmt->fetchAll();
    foreach($result as $row)
    {
        echo '<h3><a href="viewpost.php?pid='.$row['post_id'].'">'.$row['post_title'].'</a></h3>';  #Post Title
        echo '<p class="text-success col-md-12" name="marketing-section" id="marketing-section"> Author: <a href="#" data-toggle="modal" data-target="#form-content">'.$row['username'].'</a></p>';
        echo '<p class="lead col-md-12">'.substr($row['post_content'], 0, 200).'<a href="viewpost.php?pid='.$row['post_id'].'"> ...More</a></p><br /><hr>';
    }
?>

现在效果很好!请参阅Create Prepared SQL Statement:Demo