Basic Database Connection, Random Query, Display Result

Last updated on:

$hostname = 'localhost';
$user = 'username';
$pass = 'password';
$database = 'database_name';

$db_connection = new PDO( "mysql:host=" . $hostname . ";dbname=" . $database, $user, $pass );

$results = $db_connection->query( 'SELECT testimonial, author FROM recommendations WHERE 1 ORDER by rand() LIMIT 1' );

foreach ( $results as $row ) {
	echo '<p id="quote">' . $row['testimonial'] . '</p>';
	echo '<p id="author">&ndash;' . $row['author'] . '</p>';

// Close the connection
$db_connection = null;


  1. Guilherme Barbosa
    Permalink to comment#

    Not the basic only. I liked it.

  2. Eddie
    Permalink to comment#

    You are most welcome!

  3. rajan
    Permalink to comment#

    Hi, this script can only be implemented for a single table. Do you have any other script that works for more than one table.
    Thank you.

  4. KedarLasane
    Permalink to comment#

    You can store Login Details Like Username & Password in different file and then include it into above page instead of directly specified.Something like following

    include "secure.php"; // include file for i.e username & password
    $db = mysql_connect(HOSTNAME, USERNAME, PASSWORD) or die ('I cannot connect to MySQL.');
    $query = "SELECT testimonial,author FROM recommendations WHERE 1 ORDER by rand() LIMIT 1";
    $result = mysql_query($query);
    while ($row = mysql_fetch_array($result)) 
    echo "" , ($row['testimonial']) , " \n –" , nl2br($row['author']) , "";

    and secure.php contains following data.

    define ('HOSTNAME', 'localhost');
    define ('USERNAME', 'username');
    define ('PASSWORD', 'password');
    define ('DATABASE_NAME', 'recommendations');

    It is very secure method than above one.

  5. Casey
    Permalink to comment#

    Just an FYI for newcomers. I suggest using the new php syntax. This is deprecated. You should be using prepared statements and mysqli connection, otherwise you’re vulnerable to sql injection.

  6. Brent
    Permalink to comment#

    USE PDO! mysql_connect is an anti-pattern and not as secure as it should be.

  7. Milton
    Permalink to comment#

    PDO style. After reading, trial and error!! First post of a newbee!

    Try {
             $link = new \PDO('mysql:host='.HOSTNAME.';dbname='.DATABASE.';charset=utf8mb4', USERNAME, PASSWORD, array(\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION, \PDO::ATTR_PERSISTENT => false));
              $handle2 = $link->prepare('SELECT * FROM tabla1');
              $result = $handle2->fetchAll(\PDO::FETCH_OBJ);
    catch(\PDOException $ex)
          echo $ex->getMessage();
    • Wage
      Permalink to comment#
          'password' => 'passwordhere'
      // Establish a connection to the database using PDO.
      try {
          $connect = new PDO('mysql:host=localhost;dbname=test_db', $config['username'], $config['password']);
      } catch (PDOException $e){
          echo 'ERROR: '.$e->getMessage();
  8. Jaylord Ferrer
    Permalink to comment#

    This should be updated. MySQLi or PDO.

  9. Keyx

    Indeed, when will you update this?

Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in in triple backtick fences like this:

  function example() {
    element.innerHTML = "<div>code</div>";

There's a whole bunch of content on CSS-Tricks.

Search for Stuff   •   Browse the Archives

Get the Newsletter ... or get the RSS feed