phpmysqldbo

How do I randomly get variables from a mysql database? (using php with dbo connection)


My question clearly states it in the heading, anyway a more elaborate question is how can I randomly show a variable (eg. name) from a mysql database using php with a dbo connection in xampp environment.

Here is what I've come up with from scratch:-

 <?php
                $db = new PDO 
                ('mysql:dbname=lab1;host=localhost;charset=utf8','root', 
                '');
                $stmt = $db->prepare('SELECT * FROM countries');
 ?>


                <head>
                <meta charset="UTF-8"/>
                <p>RANDOM!</p>
                </head>


                <body>
<?php
                $stmt -> execute();
                foreach($stmt as $row){
                $something = array ($row['name'] . $row['name']);
                }
                $rand_keys = array_rand($something, 1);
                echo $something[$rand_keys[0]] . "\n";
?>
                </body>

Seems to not work when I try opening it (from localhost)


Solution

  • Based off your comment of "sorry I was not able to make my question clear, so basically I have a table in mysql, with 4 columns and as of now it has 2 inputted rows, now I want to be able to echo lets say just 1 field (randomly) as I refresh the file when opened from localhost..." ... you will need to do a compound randomize :)

    Start with this sql change to randomly just grab one row (of all columns):

    SELECT * FROM countries ORDER BY RAND() LIMIT 1
    

    Then retrieve that one row, and then randomly pick from the available columns:

    $stmt->execute();
    $row = $stmt->fetch(PDO::FETCH_NUM);// PDO example, important to fetch by indexes, not associative names
    
    echo $row[ rand(0,count($row)) ];
    

    That should randomly pull one column from the randomly grabbed row.