Black Friday sale is now on! 50% off Laravel: The Modular Way. Learn more

Connecting to a database

David Carr

PHP & MySQL Tutorials

    This tutorial will explain how to connect to your database.

    First open a text editor such as Notepad or Dreamweaver..ect

    To start a php page you need to declare your using php. To do this you write the php open tag

    <?php

    Then start the variable that will connect to the database using the dollar sign '$' then give it a name such as 'dbh' which stands for Database Host. ($dbh)

    Then were going to use the error suppressor symbol '@' which will suppress the ugly error message that is produced in the event of something going wrong. Instead we will create our own error message that is more user friendly.

    Using the function mysql_connect we will define the host address, database username and database password.

    <?php
    $dbh=@mysql_connect ("localhost", "database username", "password");
    ?>

    We now check to see if we are connected to the database if not connected, Show an error message letting you know, using the not operator ! like !dbh if not dbh then show a message.

    <?php
    if (!$dbh) {
        echo '<p>Unable to connect to the database server at this time</p>';
    ?>

    Then exit the script using exit()
    Now we select the database from the database server we want to use.
    mysql_select_db select the database name then once again check to see if connected and if not connected show error message.

    <?php
    mysql_select_db ("table name");
    if (!@mysql_select_db('table name')) {
        exit('<p>Unable to select the table name at this time.</p>');
    ?>

    Save the file as connect.php or something similar and run the file in a browser and if you see an empty page you should be connected to your database. 

    Here is the full script:

    <pre lang="php" >
    <?php
     $dbh=@mysql_connect ("localhost", "database username", "password");
      if (!$dbh) {
        echo '<p>Unable to connect to the database server at this time</p>';
        exit();
    }
    
    mysql_select_db ("table name");
    
    if (!@mysql_select_db('table name')) {
        exit('<p>Unable to select the table name at this time.</p>');
    }
    ?>

     

    Laravel Modules Book by David Carr

    Help support the blog so that I can continue creating new content!

    Subscribe to my newsletter

    Subscribe and get my books and product announcements.

    © 2009 - 2022 DC Blog. All code MIT license. All rights reserved.