As you all knows that MySQLi is improved PHP extension of MySQL which is introduced in PHP 5. MySQL is deprecated in PHP 5.5 will be removed in future. We have millions of applications using PHP MySQL and needs to be updated on MySQLi or PDO (
PHP
Data
Objects is also a new extension you can use to use in your applications). So today i am going to give you a very simple integration guide of MySQLi how to connect to a database, how to run a query and insert records etc hope you love this
article.
Example of mysqli connection with the object method:
|
<?php
$db = new mysqli('localhost','root','password','dbname');
?>
|
Example of mysqli connection with the procedural method:
|
<?php
$con = mysqli_connect('localhost','root','password','dbname');
?>
|
Connection error checking with object method:
|
<?php
$db = new mysqli('localhost', 'root', 'password', 'dbname');
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
?>
|
Connection error checking with procedural method:
|
<?php
$con = mysqli_connect("HostName","UserName","password","DBName") or die("Some error occurred during connection " . mysqli_error($con));
?>
|
Escaping characters with mysqli real escape:
|
<?php
$db->real_escape_string('This is an un-escaped "string"');
//there is an alias function less typed
$db->escape_string('This is an un-escape "string"');
?>
|
Simple procedure with complete code with procedural method:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
<?php
//Create the connection
$con = mysqli_connect("HostName","UserName","password","DBName") or die("Some error occurred during connection " . mysqli_error($con));
// Write query
$strSQL = "SELECT username FROM MyTable";
// Execute the query.
$query = mysqli_query($con, $strSQL);
while($result = mysqli_fetch_array($query,RESULT_TYPE))
{
echo $result["username"]."
";
}
/*
result we have look like:
=======================
id ======= name ==== class
=======================
1 ======= venki ==== 19
....
if RESULT_TYPE
+MYSQLI_NUM: access result array =>> $result[0]=1 , $result[2]=19
+MYSQLI_ASSOC: access result array =>>> $result['id']=1, $result['name']=venki
+MYSQLI_BOTH: will create a single array with 2 attribute you can use $result[0]=1 or $result['id']=1
*/
// Close the connection
mysqli_close($con);
?>
|
0 comments:
Post a Comment