Treehouse: Grow your CSS skills. Land your dream job.

Last updated on:

Basic Database Connection, Random Query, Display Result

<?php

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

$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 "<p id="quote">" , ($row['testimonial']) , "</p> \n <p id="author">&ndash;" , nl2br($row['author']) , "</p>";
}

mysql_free_result($result);
mysql_close();
?>

Comments

  1. Guilherme Barbosa
    Permalink to comment#

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

  2. Eddie
    Permalink to comment#

    You are most welcome!

  3. ambu
    Permalink to comment#

    Hey friend
    we guys are creating social networking site in aspx can u please give me some important tricks how i can make it more attractive

    we want to create in semi flash mode can u help me

    Thanks
    Ambu

  4. 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.

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

  6. 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

  7. Brent
    Permalink to comment#

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

  8. 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();
         }
    ?>
     
    • 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();
      }
      
      ?>
      
  9. Jaylord Ferrer
    Permalink to comment#

    This should be updated. MySQLi or PDO.

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:

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