treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Basic Database Connection, Random Query, Display Result

Last updated on:

<?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();
?>
View Comments

Comments

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

  2. Permalink to comment#

    You are most welcome!

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

Leave a Comment

Use markdown or basic HTML and be nice.