Basic Database Connection, Random Query, Display Result

<?php

$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;

Comments

  1. User Avatar
    Guilherme Barbosa
    Permalink to comment#

    Sweet!
    Not the basic only. I liked it.
    Thanks.

  2. User Avatar
    Eddie
    Permalink to comment#

    You are most welcome!

  3. User Avatar
    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. User Avatar
    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

    
    <?php
    include "secure.php"; // include file for i.e username & password
    $db = mysql_connect(HOSTNAME, USERNAME, PASSWORD) or die ('I cannot connect to MySQL.');
    
    mysql_select_db(DATABASE_NAME);
    
    $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']) , "";
    }
    
    mysql_free_result($result);
    mysql_close();
    ?>

    ——–
    and secure.php contains following data.

    
    <?php
    define ('HOSTNAME', 'localhost');
    define ('USERNAME', 'username');
    define ('PASSWORD', 'password');
    define ('DATABASE_NAME', 'recommendations');
    ?>


    It is very secure method than above one.

  5. User Avatar
    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.

    http://php.net/manual/en/book.mysqli.php

  6. User Avatar
    Brent
    Permalink to comment#

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

  7. User Avatar
    Milton
    Permalink to comment#

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

    
    <?php
    Try {
            require_once('db.php');
            
             $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');
              $handle2->execute();
              $result = $handle2->fetchAll(\PDO::FETCH_OBJ);
           }
    catch(\PDOException $ex)
    {
          echo $ex->getMessage();
         }
    ?>
     
    • User Avatar
      Wage
      Permalink to comment#
       'usernamehere',
          '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. User Avatar
    Jaylord Ferrer
    Permalink to comment#

    This should be updated. MySQLi or PDO.

  9. User Avatar
    Keyx

    Indeed, when will you update this?

  10. User Avatar
    THOMPSON
    Permalink to comment#

    PLEASE FRIENDS AND FAM I NEED YOUR HELP I WANT TO BUILD A DYNAMIC WEBSITE USING PHP I NEED ALL THE HELP I CAN GET AS I AM KIND OF NEW TO PHP

Submit a Comment

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

icon-closeicon-emailicon-linkicon-logo-staricon-menuicon-nav-guideicon-searchicon-staricon-tag