我正在尝试切换到 PDO。尽管我很快遇到了一些问题,但我无法解决的一个问题是我的随机图像脚本。我之前有一篇文章提到此功能不起作用,它与 SELECT MAX(id) 需要为 SELECT MAX(id-6)
有关。之前的问题是我得到的是随机数量的随机图像,而不是 6。
现在的问题是,有时我得到六张随机图像,有时我什么也得不到。我希望有人可以查看我的脚本,看看他们是否能发现其中的任何问题。
谢谢,有时只需第二双眼睛即可:
<?php
$passed_cat = mysql_real_escape_string($_GET['cat']);
$passed_sub_cat = mysql_real_escape_string($_GET['sub_cat']);
include ('../../connection.php');
$related_images = "SELECT *,r1.id as main_id
FROM images AS r1
JOIN
(
SELECT ROUND(RAND() * (SELECT MAX(id-6)
FROM images)) AS id
) AS r2
WHERE r1.id >= r2.id
AND public_approved='Approved'
AND category = :category
AND sub_category = :sub_category
ORDER BY r1.id ASC
LIMIT 6
OFFSET 20";
$q = $conn->prepare($related_images);
$q->execute(array(
':category' => $passed_cat,
':sub_category' => $passed_sub_cat));
if(!$q)
{
die("Query failed due to: ". $conn->errorInfo());
}
$q->setFetchMode(PDO::FETCH_BOTH);
while($row = $q->fetch())
{
echo "<div style='float:left; margin:2px;' >";
echo '<a href="sub_page.php?cat='. $passed_cat .'&sub_cat='. $passed_sub_cat .'&id='. $row['main_id'] .'"><img src="../../files/small/thumb0_'. $row['item_name'] . '.' . $row['file_extension'] . '" style="width:96px;" border="0"></a>';
echo "</div>";
}
?>
编辑:Connection.php
<?php
$host = "localhost";
$dbname = "all_sites";
$db_username = "root";
$db_password = "password";
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname",$db_username,$db_password);
}
catch (PDOException $pe)
{
die('Connection error, due to: ' .$pe->GetMessage());
}
?>
最佳答案
mysql_real_escape_string() 不是必需的,如果不使用 mysql_connect() 可能会导致问题
From the manual: mysql_real_escape_string('',*link_identifier)
- The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.
只需将 $_GET 变量传递给执行数组即可:
$q->execute(array(':category'=>$_GET['cat'], ':sub_category'=>$_GET['sub_cat']));
关于php - 尝试切换到 PDO,随机图像脚本并不总是触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13459475/