PHP connect to database, display random user

Hello,

What I am trying to accomplish is to connect to my database and randomly select 1 user and display them using the echo function. The code I have here looks good:

[php]<?php
// connect to your MySQL database here
require_once “connect_to_mysql.php”;
// Build the sql command string
$sqlCommand = “SELECT id, username FROM members ORDER BY RAND() LIMIT 2”;
// Execute the query here now
$query = mysql_query($sqlCommand) or die (mysql_error());
// Output the data here using a while loop, the loop will return all members
while ($row = mysql_fetch_array($query)) {
// Gather all $row values into local variables for easier usage in output
$uid = $row[“id”];
$username = $row[“username”];
// echo the output to browser or compound an output variables here
echo "User ID = $uid

User Name = $username


";
}
// close mysql connection
mysql_close();
?>[/php]

The issue is, I can’t seem to get the code right in the “connect_to_mysql.php” file for it to work properly. I have tried multiple different suggestions on how to connect to the database and I can get the code to connect to the database but it doesn’t seem to want to function with my code above to select and display a random user - it will just let me know if it successfully connected or not. So my question is: with the specific code I have above, how would I properly write the “connect_to_mysql.php” file to make this random selection work? Thank you for your time!

-David.

Mine is 4 lines,
[php]<?php
mysql_connect(‘localhost’, ‘login’, ‘password’) or die(mysql_error());
mysql_select_db(‘primary’) or die(mysql_error());
?>[/php]

What makes you think you’re not getting a connection? are you getting any error messages?

Sponsor our Newsletter | Privacy Policy | Terms of Service