Learn MySQLi or PDO_MySQL
1. Why learn?
- MySql_* extension is deprecated as of PHP 5.5.0, and will be removed in the future.
- MySQLi or PDO_MySQL are better than MySql. You will agree with me, when you learn anyone of these.
- If you like OO (object-oriented), then you will like these more.
- Full form of MySqLi is MySqLi (improved) .MySql Improved Extension
MySqLi has dual interface. Procedural and object-oriented interface. You can choose whatever you like. Exactly same functionality is provided in both interfaces but in different ways.
Procedural way example-
<?php//New way $mysqli = mysqli_connect($host, $user, $pass, $database); $res = mysqli_query($mysqli, "SELECT 'something' FROM table"); $row = mysqli_fetch_assoc($res);
echo $row['something'];//Old way $mysql = mysql_connect($host, $user, $pass); mysql_select_db($database);$res = mysql_query("SELECT 'something' FROM table", $mysql); $row = mysql_fetch_assoc($res);
echo $row['something']; ?>
mysqli_connect in which we have to write database name also. So, we don't need mysql_select_db($database); statement line.Object oriented way,$mysqli = new mysqli($host,$user,$pass,$database);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli->connect_error;
} $res = $mysqli->query("SELECT 'something' FROM table"); $row = $res->fetch_assoc();
echo $row['something'];We can even mix both but it's bad way so I am not going to tell that way.Full list of MySqli function/class can be found at,http://www.php.net/manual/en/mysqli.summary.phpPrepared Statements
A prepared statement
or a parameterized statement is used to execute the same statement
repeatedly with high efficiency.
This is two step process,
First step,
<?php
$mysqli = new mysqli(......);
/* Prepared statement, stage 1: prepare */ if (!($stmt = $mysqli->prepare("INSERT INTO table(column) VALUES (?)"))) {
//Prepare failed
}//use ?,? for multiple ?>Second Step, binding and execution, (? is replaced with real values)
Example #2 Second stage: bind and execute
<?php /* Prepared statement, stage 2: bind and execute */
if (!$stmt->bind_param("column", 'value')) {
//error happens
}
if (!$stmt->execute()) {
//execution error.
}?>Official docs for prepare can be found at, More coming soon.
No comments:
Post a Comment