SitePoint Sponsor

User Tag List

Results 1 to 6 of 6
  1. #1
    SitePoint Member
    Join Date
    May 2009
    Posts
    21
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Connecting to MySQL with PHP

    Hello,

    I'm new to php, and I'm having trouble applying this section of Kevin Yank's tutorial on connecting to my mysql database, newpolitics_com_jokes.

    I've created a test page test.php with the following info, but all I get is a blank page. Am I doing something wrong?

    Sean

    <HTML>
    <HEAD>
    <TITLE> Simple PHP Example </TITLE>
    </HEAD>
    <BODY>
    <P><?php mysql_connect(localhost, [my username], [my password])
    $dbcnx = mysql_connect('localhost', 'root', 'mypasswd');
    $dbcnx = @mysql_connect('localhost', 'root', 'mypasswd');
    if (!$dbcnx) {
    echo '<p>Unable to connect to the ' .
    'database server at this time.</p>';
    exit();
    }
    mysql_select_db('newpolitics_com_jokes', $dbcnx);
    if (!@mysql_select_db('newpolitics_com_jokes')) {
    exit('<p>Unable to locate the joke ' .
    'database at this time.</p>');
    }
    ?></P>
    </BODY>
    </HTML>

    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    Connecting to MySQL with PHP

    Before you can get content out of your MySQL database for inclusion in a Web page, you must know how to establish a connection to MySQL from inside a PHP script. Back in Chapter 2, Getting Started with MySQL, you used a program called mysql that allowed you to make such a connection from the command prompt. PHP has no need of any special program, however; support for connecting to MySQL is built right into the language. The built-in function mysql_connect establishes the connection:

    mysql_connect(address, username, password)


    Here, address is the IP address or host name of the computer on which the MySQL server software is running ('localhost' if it's running on the same computer as the Web server software), and username and password are the same MySQL user name and password you used to connect to the MySQL server in Chapter 2, Getting Started with MySQL.

    You may remember that functions in PHP usually return (output) a value when they're called. Don't worry if this doesn't ring any bells for you—it's a detail that I glossed over when I first discussed functions in Chapter 3, Getting Started with PHP. In addition to doing something useful when they are called, most functions output a value; that value may be stored in a variable for later use. The mysql_connect function shown above, for example, returns a number that identifies the connection that has been established. Since we intend to make use of the connection, we should hold onto this value. Here's an example of how we might connect to our MySQL server.

    $dbcnx = mysql_connect('localhost', 'root', 'mypasswd');

    As described above, the values of the three function parameters may differ for your MySQL server. What's important to see here is that the value returned by mysql_connect (which we'll call a connection identifier) is stored in a variable named $dbcnx.

    As the MySQL server is a completely separate piece of software, we must consider the possibility that the server may be unavailable or inaccessible due to a network outage, or because the user name/password combination you provided is not accepted by the server. In such cases, the mysql_connect function doesn't return a connection identifier, as no connection is established; instead, it returns false. This allows us to react to such failures using an if statement:

    $dbcnx = @mysql_connect('localhost', 'root', 'mypasswd');
    if (!$dbcnx) {
    echo '<p>Unable to connect to the ' .
    'database server at this time.</p>';
    exit();
    }

    There are three new tricks in the above code fragment. First, we have placed an @ symbol in front of the mysql_connect function. Many functions, including mysql_connect, automatically display ugly error messages when they fail. Placing the @ symbol (also known as the error suppression operator) in front of the function name tells the function to fail silently, and allows us to display our own, friendlier error message.

    Next, we put an exclamation mark (!) in front of the $dbcnx variable in the condition of the if statement. The exclamation mark is the PHP negation operator, which basically flips a false value to true, or a true value to false. Thus, if the connection fails and mysql_connect returns false, !$dbcnx will evaluate to true, and cause the statements in the body of our if statement to be executed. Alternatively, if a connection was made, the connection identifier stored in $dbcnx will evaluate to true (any number other than zero is considered "true" in PHP), so !$dbcnx will evaluate to false, and the statements in the if statement will not be executed.

    The last new trick is the exit function, which is the first example that we've encountered of a function that can be called with no parameters. When called this way, all this function does is cause PHP to stop reading the page at this point. This is a good response to a failed database connection because in most cases the page will be unable to display any useful information without that connection.

    As in Chapter 2, Getting Started with MySQL, once a connection is established, the next step is to select the database with which you want to work. Let's say we want to work with the joke database we created in Chapter 2, Getting Started with MySQL. The database we created was called ijdb. Selecting that database in PHP is just a matter of another function call:

    mysql_select_db('ijdb', $dbcnx);

    Notice we use the $dbcnx variable that contains the database connection identifier to tell the function which database connection to use. This parameter is actually optional. When it's omitted, the function will automatically use the link identifier for the last connection opened. This function returns true when it's successful and false if an error occurs. Once again, it's prudent to use an if statement to handle errors:

    if (!@mysql_select_db('ijdb')) {
    exit('<p>Unable to locate the joke ' .
    'database at this time.</p>');
    }

    Note that this time, instead of assigning the result of the function to a variable and then checking if the variable is true or false, I have simply used the function call itself as the condition. This may look a little strange, but it's a very commonly used shortcut. To check whether the condition is true or false, PHP executes the function and then checks its return value—exactly what we need to happen.

    Another short cut I've used here is to call exit with a string parameter. When called with a parameter, exit works just like an echo statement, except that the script exits after the string is output. So, calling exit this way is equivalent to an echo statement followed by a call to exit with no parameters, which is what we used for mysql_connect above.

    With a connection established and a database selected, we're ready to begin using the data stored in the database.

  2. #2
    Follow Me On Twitter: @djg gold trophysilver trophybronze trophy Dan Grossman's Avatar
    Join Date
    Aug 2000
    Location
    Philadephia, PA
    Posts
    20,580
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    <?php mysql_connect(localhost, [my username], [my password])
    $dbcnx = mysql_connect('localhost', 'root', 'mypasswd');
    $dbcnx = @mysql_connect('localhost', 'root', 'mypasswd');
    You try to connect to the database 3 times here. The first time is full of syntax errors, delete it. The second line is fine, keep it. The third line is redundant, you just connected with the same details on the second line, so delete it.

    Try that first

    PHP Code:
    <?php
    $dbcnx 
    mysql_connect('localhost''root''mypasswd');

  3. #3
    SitePoint Member
    Join Date
    May 2009
    Posts
    21
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks Dan. I amended test.php page as follows and uploaded it, but still got a blank screen. What am I supposed to see if it's done correctly? Am I supposed to put in something for 'root' and 'mypasswd' or leave as is. Tried changing 'mypasswd' to my actual password, but it didn't make any difference. Apologies for my ignorance.

    <HTML>
    <HEAD>
    <TITLE> Simple PHP Example </TITLE>
    </HEAD>
    <BODY>
    <P><?php $dbcnx = mysql_connect('localhost', 'root', 'mypasswd');
    mysql_select_db('newpolitics_com_jokes', $dbcnx);
    ?></P>
    </BODY>
    </HTML>

  4. #4
    Follow Me On Twitter: @djg gold trophysilver trophybronze trophy Dan Grossman's Avatar
    Join Date
    Aug 2000
    Location
    Philadephia, PA
    Posts
    20,580
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Well you have not written any code to display anything, so a blank page doesn't mean anything is wrong. If you right click the page and click "View Source" in your browser, you should see

    HTML Code:
    <HTML>
    <HEAD>
    <TITLE> Simple PHP Example </TITLE>
    </HEAD>
    <BODY>
    <P></P>
    </BODY>
    </HTML>
    If there were no errors

  5. #5
    SitePoint Wizard
    Join Date
    Nov 2005
    Posts
    1,191
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    .

  6. #6
    SitePoint Member
    Join Date
    May 2009
    Posts
    21
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks Dan. I've got it to work. Cheers


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •