Friday, 31 August 2018

Getting a random array of a while loop in PHP

I have a page set up for testimonials for a company website. Just the standard message first name, last name, message, blah blah..anyways I can pull the message up and have a single entry show up however, I would like it to randomly generate a 'testimonial' I know there is random_array functions already included in PHP but how would I go about it in a while loop? Thats the only way really I have learned to pull information from a MySQL database. So if there is a simpler way I am all ears.

<?php
    mysql_select_db("test", $link);
    $sql= "SELECT * FROM testimonials LIMIT 1";

    $result = mysql_query($sql);
    while($row = mysql_fetch_assoc($result)){
        // var_dump($row['message']); die;
?>
    <p>
<?php
    echo $row['message']; ?>"<br/>
    <div id="quote"><?php echo $row['first_name']. " " .$row['last_name'];?></div><div id="location"><?php echo $row['city']. " , " .$row['state'];?></div><br/>

    <div class="readmore">
        <a href="greenInformation.php">Click Here to view more</a>
    </div></p>

<?php } ?>


Like this?
$sql="SELECT * FROM `testimonials` ORDER BY RAND() LIMIT 1";

Another, and better method, is if you have a ID column, then you could generate a random number and get a row based on that.
$sql="SELECT * FROM `testimonials` WHERE `id`=".mt_rand(1,500);

0 comments:

Post a Comment