Php 我的代码没有输出我的随机mysql查询。帮助
这段代码很容易解释。我正在尝试使用sql检索随机a记录及其值。然而,当我上传这个时,我从源代码中得到的只是Php 我的代码没有输出我的随机mysql查询。帮助,php,mysql,sql,Php,Mysql,Sql,这段代码很容易解释。我正在尝试使用sql检索随机a记录及其值。然而,当我上传这个时,我从源代码中得到的只是 <a href="/.php"> <div class="image"> <img src="https://s3.amazonaws.com/images/" alt="" /> </div>
<a href="/.php">
<div class="image">
<img src="https://s3.amazonaws.com/images/"
alt=""
/>
</div>
</a>
这是我的密码:
<?php
// Get the number of rows in the table
$count = mysql_fetch_assoc(mysql_query('SELECT COUNT(thumbnailID) FROM images'));
// Use those to generate a random number
$count = floatval($count);
$rand = rand(1,$count);
// Select the two columns we need, and use limit to set the boundaries
$query = 'SELECT link, pic, alt FROM images LIMIT '.$rand.',1';
// Run the query
if(($result = mysql_query($query)) !== FALSE) {
// Dump the result into two variables
list($link, $pic, $alt) = mysql_fetch_assoc($result);
// Echo out the result
echo '
<a href="/' . $link . '.php">
<div class="image">
<img src="https://s3.amazonaws.com/images/' . $pic . '"
alt="' . $alt . '"
/>
</div>
</a>';
}
?>
谢谢
SELECT link, pic, alt FROM images ORDER BY RAND() LIMIT 1;
简化代码:
<?php
$query = 'SELECT link, pic, alt FROM images ORDER BY RAND() LIMIT 1;';
// Run the query
if(($result = mysql_query($query)) !== FALSE) {
list($link, $pic, $alt) = mysql_fetch_assoc($result);
echo '
<a href="/' . $link . '.php">
<div class="image">
<img src="https://s3.amazonaws.com/images/' . $pic . '"
alt="' . $alt . '"
/>
</div>
</a>';
}
?>
首先考虑这一点
$count = 10; // for example: number of rows found
$count = floatval($count);
$rand = rand(1,$count);
$rand将是介于1和10之间的数字。。。您需要0..9才能在MySQL限制中使用。所以如果$rand达到10,你将一无所获,因为你的最后一行是..限制9,1,而不是限制10,1
试试这个
$sql = 'SELECT link, pic, alt FROM images ORDER BY RAND() LIMIT 1;';
$res = mysql_query($sql);
if ($row = mysql_fetch_array($res)) {
echo '<a href="/' . $row['link'] . '.php">
<div class="image">
<img src="https://s3.amazonaws.com/images/' . $row['pic'] . '" alt="' . $row['alt'] . '" />
</div>
</a>';
}
仍然得到相同的结果:[仍然得到相同的结果:[是的,这是一般性的通知…尝试下面的代码,让我知道那里发生了什么。您确定表中有任何记录吗?