Sample PHP/MySQL Connection & Query Code

May 16th, 2006 by Oliver - Tagged with - Posted in Other Stuff

(No Ratings Yet)
Loading ... Loading ...

Sample code to make connecting to a single database on multiple pages a little easier. This code is best used as an ‘include’ into the pages you wish to use DB queries. For more information on how to include go here.

  1. $hostname = “127.0.0.1″;
  2. $database = “users”;
  3. $username = “root”;
  4. $password = “mypassword”;
  5. $connect_string = mysql_pconnect($hostname, $username, $password) or trigger_error(mysql_error(),E_USER_ERROR);

Sample query using the ‘$connection_string’ information from above.
This will pull all records from the table ‘users’ from the database we defined above. 

  1. mysql_select_db($DATABASE, $CONNECT_STRING);
  2. $query_users = sprintf(“SELECT * FROM users”);
  3. $users = mysql_query($query_users, $CONNECT_STRING) or die(mysql_error());
  4. $row_users = mysql_fetch_assoc($users);
  5. $all_users = mysql_query($query_users);
  6. $totalRows_users = mysql_num_rows($all_users);

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>