创建了一个按用户ID获取帖子的表单。我的问题是: 如何将其转换为准备好的语句。可以看到为值分配var的位置,但如何准备一个已经等于请求值的SQL语句?声明是:
$sql = "SELECT * FROM posts, users WHERE posts.user_id = users.id AND
posts.user_id = ".$_GET['uid'];"
完整的PHP声明
此代码也运行“ PHP函数”但写入时不需要(我怀疑)
如果确实如此,请告诉我,我可以提供。
<?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'];
}
?>
答案 0 :(得分:0)
(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。