Since MySQL extension is deprecated and will be removed as of PHP 5.5 onwards, I'll be teaching you how to connect to a mysql database using the new method, MySQL Improved or MySQLi. I'll be writing 2 methods on how to connect and query on MySQLi.
1) Simple connection
//First I'll define variables
define("HOST","YOUR_MYSQL_HOST");
define("USER","YOUR_MYSQL_USERNAME");
define("PASS","YOUR_MYSQL_PASSWORD");
define("DBASE","YOUR_MYSQL_DATABASE");
// OR if you prefer using normal variables
$host = "YOUR_MYSQL_HOST";
$user = "YOUR_MYSQL_USER";
$pass = "YOUR_MYSQL_PASS";
$dbase = "YOUR_MYSQL_DATABASE";
// in my case I'll use define. It's up to you which variables you use
// now we'll connect and select our database
$mysqli = mysqli_connect(HOST, USER, PASS, DBASE) or die (mysqli_errno());
// as I mention before always use error or in MySQLi errno
// so it'll return the error message if it fails
$query = mysqli_query($mysqli, "SQL STATEMENT");
2) Object-oriented connection method
// We'll connect to the database and do a statement if it fails to connect
$mysqli = new mysqli(HOST, USER, PASS, DBASE);
if( $mysqli->connect_errno() ) {
echo "Connection failed: ". $mysqli->connect_error());
}
$query = $mysqli->query("SQL STATEMENT");
Have fun coding..
No comments:
Post a Comment