Friday 17 May 2013

PHP MySQLI Tutorial

What is MySQLI :

The MySQLi Extension (MySQL Improved) is a relational database driver used in the PHP programming language to provide an interface with MySQL databases.
MySQLi is an improved version of the older PHP MySQL driver, offering various benefits.
The developers of the PHP programming language recommend using MySQLi when dealing with MySQL server versions 4.1.3 and newer (takes advantage of new functionality).

Why Mysqli :

The MySQLi extension provides various benefits with respect to its predecessor, the most prominent of which are:
  • An object-oriented interface
  • Support for prepared statements
  • Support for multiple statements
  • Support for transactions
  • Enhanced debugging support
  • Embedded server support

MySQLi Vs MySQL

MySQLi MySQL
PHP version introduced 5.0 Prior to 3.0
Included with PHP 5.x yes Yes
MySQL development status Active development Maintenance only
Recommended by MySQL for new projects Yes - preferred option No
API supports Charsets Yes No
API supports server-side Prepared Statements Yes No
API supports Stored Procedures Yes No
API supports Multiple Statements Yes No
Supports all MySQL 4.1+ functionality Yes No


Here is a simple code that implements mysqli

<?php


 //CONNECT TO THE DATABASE
 $DB_HOST = 'HOST';
 $DB_USER = 'USERNAME';
 $DB_PASS = 'PASSWORD';
 $DB_NAME = "mysqlitest";

 $mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
 
 
 if (mysqli_connect_errno()) {
  printf("Connect failed: %s\n", mysqli_connect_error());
  exit();
 }

 //CREATE TABLE
 $q = "CREATE TABLE user (id int AUTO_INCREMENT PRIMARY KEY, 
     name varchar(30))";
 $mysqli->query($q);
 
 //INSERT FEW VALUES
 $q = "INSERT INTO user VALUES (NULL, 'abc')";
 $mysqli->query($q);
 $q = "INSERT INTO user VALUES (NULL, 'bcd')";
 $mysqli->query($q);
 $q = "INSERT INTO user VALUES (NULL, 'xyz')";
 $mysqli->query($q);
 
 
 //SELECT A USER
 $q = "SELECT * FROM user WHERE id=3";
 $result = $mysqli->query($q) or die($mysqli->error.__LINE__);

 // GOING THROUGH THE DATA
 if($result->num_rows > 0) {
  while($row = $result->fetch_assoc()) {
   echo $row['name']; 
  }
 }
 else {
  echo 'NO RESULTS'; 
 }
 // CLOSE CONNECTION
 mysqli_close($mysqli);
?>

Ads :
Buy iPad Tablet eBook Reader on www.ebay.com
Electronics, Cars, Fashion, Collectibles, Coupons and More Online Shopping | eBay
www.ebay.co.uk | www.ebay.com.my

3 comments:

  1. Its quite interesting..Is there any possible to fine out data collection through PHP..
    best dissertation topics

    ReplyDelete
  2. PHP is best and world popular programming language. Today all user want PHP web application development because it is easy to manage and so cheap also. It is fast to develop and user friendly also.

    ReplyDelete
  3. Good information for me. please keep updating us with new posts. thank you so much .

    ReplyDelete