home > web > mysql-db-connect-php

Connection to MySQL Database in PHP

posted on 2014-09-15 by Spencer Bravo

This post explains how I connect to MySQL Databases when writing in PHP. This post will mostly be used as a post I will refer to in later MySQL posts, so I won't need to include in those posts how to connect and I can get to the point. For those of you who will need this post at some place in those tutorials I will be sure to include a link to this post.

Now to the code! So when I set up my connection I acctually include it in a seperate file in a seperate directory. The directory is /inc in which I place all the files I will use by including them in other pages. In this directory I include files such as my header, footer, and my config file (in which I include the MySQL database connect setup). This file is named "config.inc.php". This is what the database connect part looks like:

<php
$db_host = ' '; // location of your database(localhost ussualy works)
$db_user = ' '; // your MySQL database username
$db_password = ' '; // your MySQL database password
$database = ' '; // name of your MySQL database

$db_connect = mysql_connect($db_host, $db_user, $db_password);
$db = mysql_select_db($database,$db_connect);
?>

You can view the most current version of this code at https://github.com/spravo13/mysql-db-connect-php-codeshrub

Then all you have to do is include this file anywhere you want to use the database and your variables will be there. Heres an example of using these variables. Note: I have already included the config file earlier on in this following code.

<php
$post_select = "SELECT * FROM post WHERE name = 'phil' LIMIT 1";
$post_query = mysql_query($post_select,$db_connect) or die($db_connect);
while ($post_row = mysql_fetch_assoc($post_query)){
}
?>

Here it is looking for a post named phil. As you see we use the variable "db_connect".

I hope this post is useful! If you have any questions or comments please don't hesitate to email us at CSTeam@CodeShrub.com

posted in web