Skip to main content

Panduan MySQLI

Connect to database using php mysqli

In order to connect to MySQL database using mysqli, mysqli_connect function is used, you need to provide host nameusernamepassword and database name.

Connect to database using php mysqli – procedural way

In procedural way mysqli_connect function is used. mysql_connect function opens a connection to database server and connection object is returned. If connection to database fails  mysqli_connect_errno() throws an error.
<?php

$host     = "localhost";

$user     = "root";

$password = "";

$database = "dbusers";

$mysqli   = mysqli_connect($host, $user, $password, $database);

if (mysqli_connect_errno($mysqli)) {
   
   echo "Failed to connect to MySQL: " . mysqli_connect_error();

}

?>

Connect to database using php mysqli – object oriented way

Object oriented way to connect to database, mysqli function is called and an object is returned. In case database connection is failed error is thrown.
<?php 

$host     = "localhost";

$user     = "root";

$password = "";

$database = "dbusers";

$mysqli = new mysqli($host, $user, $password, $database);

if ($mysqli->connect_errno) {

    echo "Failed to connect to MySQL: " . $mysqli->connect_error;

}

?>

Selecting records from database using php mysqli

Records from database can be selected using procedural way or object oriented way. mysqli_query function is used to perform query on database.
First connect to database, connection object and a query is passed to mysqli_query and it returns a result set. Result set is passed to mysqli_fetch_assoc function and it returns a data row as an associative array.

Select records using mysqli_fetch_assoc – procedural way

mysql_fetch_assoc returns a result set as an associative array and names of column in result set represents the keys of array. Null is returned if result set is empty.
<?php


$dblink = mysqli_connect("localhost", "root", "", "dbstudents");


/* If connection fails throw an error */

if (mysqli_connect_errno()) {

    echo "Could  not connect to database: Error: ".mysqli_connect_error();

    exit();
}

$sqlquery = "SELECT id, name, class, roll_no FROM students ORDER by id DESC LIMIT 50";


if ($result = mysqli_query($dblink, $sqlquery)) {


    /* fetch associative array */

    while ($row = mysqli_fetch_assoc($result)) {

        echo $row["name"]." ".$row["class"]." ".$row['roll_no']."<br />";
    }


    /* free result set */

    mysqli_free_result($result);
}

/* close connection */

mysqli_close($dblink);

Fetch records using  fetch_assoc – object oriented way

After database connection using new mysqli method,  database connection object is returned.  A query is passed to connection object‘s query method. This function returns a result set. Likewise procedural way a row from result set is fetched using fetch_assoc() method.
This method returns a single row of result, so we use a while loop to fetch all rows in result set.  Column names are used as array indexes to access result like $row[‘first_name’].
<?php

$mysqli = new mysqli("localhost", "root", "", "studentsdb");

/* check connection */
if ($mysqli->connect_errno) {
 
   echo "Connect failed ".$mysqli->connect_error;

   exit();
}

$query = "SELECT name, class, roll_no FROM students ORDER by id DESC LIMIT 50";

if ($result = $mysqli->query($query)) {

    /* fetch associative array */
    while ($row = $result->fetch_assoc()) {

        echo $row["name"]." ".$row["class"]." ".$row["roll_no"]."<br />";

    }

    /* free result set */
    $result->free();

}

/* close connection */
$mysqli->close();

?>

Fetch records using mysqli_fetch_array – procedural way

mysqli_fetch_array function is used to fetch records from database. It fetches a single row from result set as numeric array using mysql_num,  associative array using mysqli_assoc or both using mysqli-both. To display records from data row,  array index or column name is used.
<?php

$link = mysqli_connect("localhost", "root", "", "dbbookstore");

/* check connection */
if (mysqli_connect_errno()) {

    echo "Database connection failed ".mysqli_connect_error();

    exit();
}

$query = "SELECT name, author_name, price FROM books ORDER by id LIMIT 5";

$result = mysqli_query($link, $query);

/* numeric array */

$row = mysqli_fetch_array($result, MYSQLI_NUM);

echo $row[0]." ".$row[1]." ".$row[2];

/* associative array */
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);

echo $row["name"]." ".$row["author_name"]." ".$row['price'];

/* associative and numeric array */
$row = mysqli_fetch_array($result, MYSQLI_BOTH);

echo $row[0]." ".$row["author_name"]." ".$row[2];


/* free result set */
mysqli_free_result($result);

/* close connection */
mysqli_close($link);

?>

Fetch records using mysqli_result::fetch_array – object oriented way

fetch_array function can fetch result row as associative, numeric array or both. It is recommended way and works same as procedural way.
<?php

$mysqli = new mysqli("localhost", "root", "", "dbbookstore");

/* check connection */
if ($mysqli->connect_errno) {

    echo "Connectin to database failed: ".$mysqli->connect_error;
    
   exit();
}


$query = "SELECT name, author_name, price FROM books ORDER by id LIMIT 10";

$result = $mysqli->query($query);

/* Fetch result as numeric array */
$row = $result->fetch_array(MYSQLI_NUM);

echo $row[0]." ".$row[1]." ".$row[2]."<br />";

/* associative array */
$row = $result->fetch_array(MYSQLI_ASSOC);

echo $row["name"]." ".$row["author_name"]." ".$row['price']."<br />";

/* Both associative and numeric array */
$row = $result->fetch_array(MYSQLI_BOTH);

echo $row[0]." ".$row["author_name"]." ".$row[2];

/* free result set */
$result->free();

/* close connection */
$mysqli->close();

?>

Fetch all records using mysqli_fetch_all

If you need to fetch all records from database, mysqli_fetch_all function is used. First connection to database is created using mysqli_connect. Next we pass connection object and SQL query to mysqli_query function.
mysqli_query function returns result set. mysqli_fetch_all function returns all result rows as an associative, numeric or both.
<?php

$conn = mysqli_connect("localhost","root","","dbusers");

//Check connection
if (mysqli_connect_errno()){

  echo "Failed to connect to MySQL: " . mysqli_connect_error();

}

$result = mysqli_query($conn, "SELECT name, email FROM tbl_users ORDER BY id desc");

//Fetch all records
mysqli_fetch_all($result,MYSQLI_ASSOC);

//Free result set
mysqli_free_result($result);

mysqli_close($con);

?>

Prepared statements in php mysqli library

php mysqli library supports prepared or parameterized statements. A prepared statement works in two steps, step 1 is prepare a statement while step 2 involves execution of a prepared statement.
In prepare stage a statement template is sent to server, syntax is validated and internal resources are allocated while in execution step client binds the parameter values and sends it to server.
A statement is created by server and values are bind and using assigned internal resources statement is executed. It can execute repeated statement repeatedly with efficiency.

Insert records to database using php mysqli prepared statements

First we make a connection to database. Then prepare method is used to prepares SQL statement. Parameter markers ” ? ” are used in prepared statements. Then prepare function returns a statement handle that is used for further processing.
bind_param method binds variables to prepared statement. In this function we pass data types of variables. Data types of variable can be i as integerd as double, s as string and b as blob. Second parameters are the variables. The number of parameters and string type length should be same.Prepared statement are executed by execute method. When this function is called ? placeholders or parameters markers are replaced by variable values.
<?php

$conn = new mysqli("localhost", "root", "", "dbonlinestore");

if ($conn->connect_errno) {

    echo "Database connection failed. ".$conn->connect_error;

}

$product  = "EOS 7D Mark II Canon";

$price    = "$800";

$category = "Cameras";

$sql      = "INSERT INTO tbl_products (product_name, price, category) VALUES (?, ?, ?)";

/* Prepare statement */
$stmt     = $conn->prepare($sql);

if(!$stmt) {

   echo 'Error: '.$conn->error;
}
 
/* Bind parameters */
$stmt->bind_param('sss',$product,$price, $category);
 
/* Execute statement */
$stmt->execute();
 
echo $stmt->insert_id;

$stmt->close();

?>

Update records using php mysqli prepared statements

To update records first create a connection to database. Next SQL query is prepared using prepare function for execution. Finally records are updated by execute function.
<?php 

$conn = new mysqli("localhost", "root", "", "dbonlinestore");

if ($conn->connect_errno) {

    echo "Database connection failed (" . $conn->connect_errno . ") " . $conn->connect_error;

}

$product  = "Samsung Galaxy S7 Edge";

$price    = "$1000";

$category = "Mobile Phones";

$id       = 1;
 
/* Prepare statement */
$stmt = $conn->prepare("UPDATE tbl_products set product_name = ?, price = ?, category = ? where id = ?");

if(!$stmt) {
  trigger_error('Error: ' .$conn->error, E_USER_ERROR);
}
 
/* Bind parameters */
$stmt->bind_param('sssi',$product,$price, $category, $id);
 
/* Execute statement */
$stmt->execute();

$stmt->close();

Delete records using prepared statement php mysqli

To delete records from database using prepared statements first connect to database. Next SQL delete statement is prepared for execution. In where clause the ? parameter marker is used.
bind_param function binds value of $id parameter. Next prepared statement is executed by execute method and record is deleted.
<?php

$conn = new mysqli("localhost", "root", "", "dbonlinestore");

if ($conn->connect_errno) {   

  echo "Database connection failed. ".$conn->connect_errno;
  $conn->connect_error;
}

$sql = 'DELETE FROM tbl_products WHERE id = ?';

$id  = 2;
 
/*Prepare statement */
$stmt = $conn->prepare($sql);

if(!$stmt) {

  echo 'SQL error:'.$conn->error;

}
 
/* Bind parameters */
$stmt->bind_param('i',$id);
 
/* Execute statement */
$stmt->execute();
 
$stmt->close();


Comments

Popular posts from this blog

FPDF dengan CodeIgniter

Cetak Surat Keputusan Controller: <?php //File in controller named surat_keputusan.php defined('BASEPATH') OR exit('No direct script access allowed'); class Cetak_surat_keputusan extends CI_Controller { public function __construct()     {         parent::__construct();         $this->load->helper('url');         $this->load->database();                $this->db->select();         $this->db->from('surat.config_sk');                $query = $this->db->get();                 return $query->result();             } public function index() {      ...

Preview PDF di Modal Bootstrap dengan Ajax

//preview pdf in line function preview_surat_keputusan(no) { $('#form')[0].reset(); $('.form-group').removeClass('has-error'); $('.help-block').empty(); $.ajax({ url : "<?php echo site_url('surat_keputusan/ajax_preview/')?>/" + no, type: "GET", dataType: "JSON",     success: function(data)     {     //paramater yang akan ditampilkan di modal         $('[name="no"]').val(data.no);         $('[name="ns"]').val(data.ns);         $('[name="thts"]').val(data.thts);         $('[name="pdf"]').val("http://localhost/dosdm/document/sm/pdf/"+data.thts+"-SK-"+data.ns+".pdf");         var link_base =  "http://localhost/dosdm/document/sm/pdf/"+data.thts+"-SK-"+data.ns+".pdf" ;             $('#pdf_view').attr('src', link_base);      ...

Hack File .xlsb

For first you must create a backup copy of your Workbook!!! Then you have to rename the XLSB file with ZIP extension. Test.XLSB => Test.ZIP             Opening your ZIP file using a compression software (e.g. WinRar) I can see the content of the file, structured in folders Inside the folder xl you can find a binary file named vbaProject.bin. Extract it on your desktop and edit it using a text editor. In my case I used Notepad++. Using the Find function of your editor, you must search the text DPB And replace the DPB string with DPx Then save the vbaProject.bin and replace this file inside the .ZIP File, renaming then .ZIP file in XLSB. Reopening the XLSB file using Excel, you will get an error message: you have to answer Yes to this error message. Then  Save , Close and Reopen your XLSB file. Now, if you go to VBA Editor (ALT + F11), you ca...