简体   繁体   中英

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)

You can use order by RAND() like others suggested. But I think the way you trying does not work because the way you are adding elements into the array. Like the following line:

$something = array ($row['name'] . $row['name']);

does not push multiple elements (eg. country names) into the array. It replaces the previous value by a concatenated string of the same country name repeated twice. (so if the country name is Afghanistan your array will always have one element AfghanistanAfghanistan

Change your code like below:

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

Hope this will work.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM