Total Pageviews

Tuesday, 11 December 2012

MySQL and PDO Tutorial

PHP Code:
<?php
$dbhost
="";$dbuser="";$dbpass="";$dbname="";$connection=mysql_connect($dbhost,$dbuser,$dbpass)or die("Could not login to the database server. Please check the username, password, and hostname and try again.");
mysql_select_db($dbname,$dbconnection);
mysql_query("");?>

So, to explain:
Anything above that starts with "$db"... is my connection variable. You can name these anything as long as you change the name in the mysql_connect function.

The $connection variable is used to declare the connection. You don't need the variable, you can just use:
PHP Code:
mysql_connect('localhost','root','password'); 
to connect. You don't really need any variables in this, but they do make the code easier to modify later on.

mysql_select_db($dbname,$dbconnection); tells PHP what database to connect to.
Finally mysql_query(""); is the query. Put the query between the quotes, and it will execute.


PDO
PDO really is my favorite. Here is a sample connection used locally on my computer.


PHP Code:
<?php
$hostname 
"localhost";$username "root";$password "";$dbname "pdotest";
try {
    
$db = new PDO("mysql:host=$hostname;dbname=$dbname"$username$password);

    
$sql "[mysql query here]";
    
$result $db->query($sql);
    }
catch(
PDOException $error)
    {
    echo 
$error->getMessage();
    }
?>

Seems a bit longer huh? But no lie, it is much faster. PDO also has what they call prepared statements, which virtually eliminate the threat of a hacking type, called SQL Injection. Really not much to explain from the PDO side of things, basically you connect using the line: "$db = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);"

Query is put in the $sql variable.