PHP MYSQL Connect

PHP MYSQL Connect

The connection to the mySQL database is the basics to php / mySQL. If this fails, all fails. Once you can connect to a database, you can select and alter data. It is like learning to walk.

Whether you plant to create a simple or elaborate PHP / mySQL application, you must connect to a mySQL database. There are many ways to write the code for which to do so, but,two functions will be present for you to do so. The two functions are mysqli_connect() and mysqli_select_db. The function mysqli_connect will appear first for obvious reasons. Doesn't it make sense to first connect to a database then select it?

Normally, there are two methods for which the connection takes place. One technique is to use a function and the other is to just add the code into a page. Using a function is more secure and it saves on code repetition. This might not look like much now, but, an 8,000 word php/mysql application with separate database connection files used on a new server could be a hassle to fix up more than once.

Accessing Database With Function

The code below $db = public_db_connect(); calls the function and returns the $db variable. That variable can be passed into select, update, delete, and insert into queries.

function public_db_connect() {

$host = "localhost";
$user = "user";
$pw = "password";
$database = "database_name";

$db = mysqli_connect($host, $user, $pw, $database) or die("Cannot connect to mySQL.");

return $db;
}

$db = public_db_connect();
$command = "SELECT * FROM table_sort where id >0";
$result = mysqli_query($db, $command);
if($result){
echo "There are entries";
}

Accessing Database Without a Function

The code below will connect to a database. The $db variable is used in the mysqli_query() function. The output is the same as the example above.

    $host = "localhost";
$user = "root";
$pw = "";
$database = "ABOOK";

$db = mysqli_connect($host, $user, $pw, $database)
or die("Cannot connect to mySQL.");

mysqli_select_db($db, $database)
or die("Cannot connect to database.");

$command = "SELECT * FROM table_sort where id >0";
$result = mysqli_query($db, $command);
if($result){
echo "There are entries";
}