代码非常自我解释。我正在尝试使用sql来检索随机记录及其值。但是,当我上传这个时,我从源代码中得到的只是
<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>';
}
?>
谢谢!
答案 0 :(得分:1)
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>';
}
?>
答案 1 :(得分:1)
首先考虑
$count = 10; // for example: number of rows found
$count = floatval($count);
$rand = rand(1,$count);
$rand
的数字介于1到10之间 ...您需要 0..9 才能在MySQL限制中使用。因此,如果 $ rand点击10 ,您将无法获得任何结果,因为您的上一行是..LIMIT 9,1
,而不是LIMIT 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>';
}