PHP MySQLi Functions: mysqli_query | mysqli_connect | mysqli_fetch_array

A wide range of PHP MySQL database manipulation functions is already included in PHP. We’ll talk about PHP MySQLi Functions today. Prior to these, we also covered PHP Exception And Error Handling Tutorial , Forms in PHPPHP SessionPHP Operators, and Mail Function In PHP. If you don’t know about these, then act quickly!

Access MySQL database servers using the MySQLi functions.

The final optional parameter link_identifier is accepted by the majority of MySQL functions. If it is omitted, the most recent connection established is used. If it is absent, connection attempts are made using the php.ini default parameters. Functions return FALSE if the operation is unsuccessful.

Installation / Runtime Configuration

It is necessary to compile PHP with support for the MySQLi extension if you want the MySQLi functions to be available.

With PHP 5.0.0, the MySQLi extension was introduced. In PHP 5.3.0, the MySQL Native Driver was added.

For installation, go to:

For runtime configuration, go to:

PHP MySQLi Functions

PHP mysqli_connect function

To establish a connection with a MySQL database server, use the PHP MySQL connect function.


$db_handle = mysqli_connect($db_server_name, $db_user_name, $db_password);
PHP mysqli_select_db function

The function mysqli_select_db is used to choose a database.


PHP mysqli_query function

To run SQL queries, use the mysqli_query function. The following query types can be run using the function.

  • Insert
  • Select
  • Update
  • delete


mysqli_query($db_handle,$query) ;
PHP mysqli_num_rows function

The number of rows returned from a select query can be determined using the mysqli_num_rows function.


PHP mysqli_fetch_array function

Row arrays are fetched from a query result set using the mysqli_fetch_array function.


PHP mysqli_close function

An open database connection can be closed using the mysqli_close function.



Let’s examine some real-world examples of how these features are used.

The MySQL database creation This tutorial assumes that the reader has some familiarity with MySQL and SQL; if not, please consult the tutorials on those topics.

The steps to create the database and table are listed below. Here we have created a form that has connected to the database and you can insert the data and you can delete the data.

Filename: fileinsert.php

$con = mysqli_connect($server,$username, $password, $database); 
    die("Connection Failed".mysqli_connect_error());
//   echo "Successfully connected";  
$name= $_POST['name'];
$image= $_FILES['image']["name"];
$gender= $_POST['gender'];
$age= $_POST['age'];
$date= $_POST['date'];
$email= $_POST['email'];
$phone= $_POST['phone'];
$country= $_POST['country'];
$message= $_POST['message'];

if (isset($_POST['cbox'])) {
elseif (!isset($_POST['cbox'])) {
else {
    echo "Some error occurred";
$query2="select * from `formmpc` where name='$name'";
$result1=mysqli_query($con, $query2);
    echo '<script>
        alert("Already exits");

$sql="INSERT INTO `mpc_trip`.`formmpc` (`id`, `name`, `image`,`gender`, `age`, `date`, `email`, `phone`, `country`, `message`, `emailverify`) VALUES ('', '$name', '$image','$gender', '$age', '$date', '$email', '$phone', '$country', '$message','$sms');";
$result = mysqli_query($con,$sql);
    // echo "Msg= $sms";
    move_uploaded_file($_FILES["image"]["tmp_name"], "image/".$_FILES['image']["name"]);

    echo '<script>alert("Inserted Successfully")</script>';
    // if($sql){
    //     echo "Data Inserted Successfully";
    // }
    // else{
    //     echo "Data not Inserted Successfully";
    // }


<!DOCTYPE html>
<html lang="en">

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Starting Form </title>
    <link href=",wght@0,100;0,200;0,300;1,100;1,200&display=swap"
    <link href="" rel="stylesheet">
    <link rel="Stylesheet" href="style.css">
    <!-- Bootstrap CSS -->
    <link href="" rel="stylesheet"
        integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

    <!-- <img class="bg" src="" alt="" style="height: 57em;"> -->
    <div class="Container bg-success p-2 text-white bg-opacity-40" >
        <h1>Registration Form</h1>
        <p>Enter Your Details and submit this form to Confirm your participation in the Trip</p>
        <!-- <p class="submitmsg">Thanks for submitting your form. We are happy to see you joining with us</p> -->

        <form action="" method="post" enctype="multipart/form-data">
            <input type="text" name="name" id="Name" placeholder="Enter Your Name" style="margin:11px;">

            <div class=" images mb-2" style=" margin-right: 26em;margin-top: 1em;position: relative;">
            <label for="exampleFormControlInput2" class="form-label">Profile Photo</label>
            <input type="file" name="image" id="image" placeholder="" style="">
            <div class="form-check" style="margin-right: 45em;margin-top: 1.5em;">
                Select your Genders <br>
                <input type="radio" name="gender" value="male" style="position: relative;top: 25px;left: 1em;">
                <input type="radio" name="gender" value="female" style="position: relative;top: 25px;left: 1em;">
            <input type="text" name="age" id="age" placeholder="Enter Your Age" style="margin:11px;margin-top: 1em;">
            <div class="mb-3" style=" margin-right: 45em;margin-top: 1em;position: relative;left: 13px;">
                <label for="exampleFormControlInput1" class="form-label">Date of Birth</label>
                <input type="date" class="form-control" name="date" id="exampleFormControlInput1" placeholder="date">

            <input type="email" name="email" id="Email" placeholder="Enter Your Email" style="margin:11px;">
            <input type="tel" name="phone" id="phone" placeholder="Enter Your Mobile Number" style="margin:11px;">

            <div style="margin-right:37em;margin-left: 1em;">
                <label for="country">Country: </label>
                <select name="country" id="country" required
                    style="margin: 22px 6px; border: 1px solid #030303c2; border-radius: 6px;height: 39px;">
                    <option value="please select a country">please select a country</option>
                    <option value="India">India</option>
            <textarea name="message" id="Description" cols="30" rows="10"
                placeholder="About Your Information" style="  height: 138px; position: relative;left: 8px;"></textarea>
            <div class="form-check" style="margin-right: 45em;margin-top: 1em;">
                <input class="form-check-input" name="cbox" type="checkbox" value="" style="    margin-left: 1em;">
                <label class="form-check-label" style="margin-left:10px;">
                    send sms in Email
            <div class="button" style="border: 1px solid rebeccapurple;background: antiquewhite;border: 1px solid rebeccapurple;background: antiquewhite;width: 95px;">
                <button class="btn" name="submit">Submit</button>
            <div class="anchor" style="border: 1px solid black; margin-left: 18em;position: relative;bottom:40px;padding: 7px 6px;background: antiquewhite;width: 8em;">
                <a href="viewdetails.php" style="color: black; text-decoration: none;">View Details</a>
        <!-- <button class="btn">Reset</button> -->


Starting Form

Registration Form

Enter Your Details and submit this form to Confirm your participation in the Trip

Select your Genders
Male Female

For Image, You will create a image folder in the that parent Folder

Filename: style.css

For customized the form.

    margin: 0px;
    padding: 0px;
    /* box-sizing: border-box; */
font-family: 'Roboto', sans-serif;

    max-width: 50%; 
    padding: 34px; 
    margin: auto;

h1 {
    text-align: center;
    font-family: 'Sriracha', cursive;
    font-size: 40px;

    font-size: 17px;
    text-align: center;
    font-family: 'Sriracha', cursive;

input, textarea{
    border: 2px solid black;
    border-radius: 6px;
    outline: none;
    font-size: 16px;
    width: 80%;
    margin: 11px 0px;
    padding: 7px;

    color: white;
    background: purple;
    padding: 8px 12px;
    font-size: 20px;
    border: 2px solid white;
    border-radius: 14px;
    cursor: pointer;

    width: 100%;
    position: absolute;
    z-index: -1;
    opacity: 0.6;
    color: green;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    position: relative;
    left: 12em;
    left: 12em;
    margin: -5px -108px;
    padding: 10px 0px;
    margin: -5px -108px;
    padding: 10px 0px;
    box-shadow: 0px -1px 7px 4px #fce541c4;
    height: 60em;
    width: 67em;

Filename: delete.php

In this file, It contains the queries which are written for the deletion of data.

$con = mysqli_connect($server,$username, $password, $database); 
    die("Connection Failed".mysqli_connect_error());
    $query = "DELETE FROM `formmpc` WHERE  `id`='$id'";
    $result = mysqli_query($con,$query);
        echo '<script>
        alert=("Deleted Successfully");
        echo "not deleted";

Filename: Viewdetails.php

In this file, we have created a table and  we can able to see all the data which you have saved.

// session_start();
$con = mysqli_connect($server,$username,$password,$database);
    echo "Not Connected";
<table width="109%" border="1" cellspacing="5" style="border-collapse: collapse;text-align: center;height: 8em;background: aliceblue;
    <thead colspan="2" align="center">
            <th>Profile Photo </td>
            <th>Email Verify</th>
                $sql="SELECT * FROM `formmpc` ORDER BY id";
                $result= mysqli_query($con,$sql);
                while($row = mysqli_fetch_array($result)){

                    $date=date("d M Y",strtotime($row['date']));

                    // $_SESSION['id'] = $id;

                    <td><img src="image/'.$image.'" width="60px";height="50px"; alt="Empty"</td> 
                    <button style="height: 2em;position: relative; right: 13px;width: 66px;border: none;background: darkgrey;" ><a href="update.php?updateid='.$id.'" style="text-decoration: none;color: azure;">Update</a></button>
                    <button style="height: 2em;position: relative; right: -2px;width: 66px;border: none;background: darkgrey;"><a href="delete.php?deleteid='.$id.'"  style="text-decoration: none;color: azure;">Delete</a></button>




‘; ?>
SL.No Name Profile Photo Gender Age DOB Email ContactNo Country Message Email Verify Operation
‘.$id.’ ‘.$name.’ Empty ‘.$gender.’ ‘.$age.’ ‘.$date.’ ‘.$email.’ ‘.$phone.’ ‘.$country.’ ‘.$message.’ ‘.$sms.’
MySQLi FunctionsDescription
mysql_affected_rowsFind the number of rows from the last MySQL operation that were affected.
mysql_client_encodingreturns the character set’s name.
mysql_closeCut off your MySQL connection.
mysql_connectTo connect to a MySQL server, do so.
mysql_create_dbEstablish a MySQL database.
mysql_data_seekThe internal result pointer moved.
mysql_db_nameobtains the database name from the MySQL list DBS call.
mysql_db_querychooses a database and runs a query against it.
mysql_drop_dbDrop a MySQL database to delete it.
mysql_errnoreturns the error message’s numerical value from a previous MySQL operation.
mysql_errorreturns the text of the previous MySQL operation’s error message.
mysql_escape_stringTo utilise a string in a mysql query, it must be escaped.
mysql_fetch_arrayRetrieve a row of results as either an associative array, a numeric array, or both.
mysql_fetch_assocRetrieve a row of the result as an associative array.
mysql_fetch_fieldObtain column data from a result and provide it back as an object.
mysql_fetch_lengthsFind the length of each result’s output.
mysql_fetch_rowObtained an enumerated array of the result row.
mysql_field_flagsObtain the result’s flags for the field that was specified.
mysql_field_lenreturns the length of the field that was supplied.
mysql_field_nameObtain the result’s name for the given field.
mysql_field_seekSet the field offset for the result pointer.
mysql_field_tableObtain the table name where the requested field is located.
mysql_field_typeGet the field’s type as a result for the provided field.
mysql_free_resultClear the result memory.
mysql_get_client_infodiscover the MySQL client.
mysql_get_host_infoObtain MySQL host information.
mysql_get_proto_infolearn about the MySQL protocol.
mysql_get_server_infolearn about the MySQL server.
mysql_infoLearn more about the most recent search.
mysql_insert_idObtain the ID created by the most recent query.
mysql_list_dbsList the MySQL server’s accessible databases.
mysql_list_fieldsList the fields of a MySQL table.
mysql_list_processesList each instance of MySQL.
mysql_list_tablesthe MySQL database’s tables.
mysql_num_fieldsCount the number of fields in the result.
mysql_num_rowsCount the number of rows in the result.
mysql_pconnectEstablish an ongoing connection with a MySQL server.
mysql_pingIf a server connection is available, ping it or try again if none are.
mysql_querySend a query to MySQL.
mysql_real_escape_stringenables the usage of special characters in strings in SQL statements.
mysql_resultFind out the results.
mysql_select_dbchoosing a MySQL database.
mysql_set_charsetthe client character set is set.
mysql_statdiscover the present system status.
mysql_tablenameGet the field’s table name.
mysql_thread_idthe thread ID that is active right now.
mysql_unbuffered_queryDon’t fetch and buffer the rows of the response before sending a SQL query to MySQL.
mysql_fetch_objectGet a row of the results as an object.

ODBC The name “ODBC” stands for Open Database Connectivity. Its basic syntax is as follows.

<?php $conn = odbc_connect($dsn, $user_name, $password); ?>

The example makes you a given.

  • using Windows OS.
  • You have established an ODBC connection to the northwind Microsoft Access database.

The implementation code for ODBC data access is provided below.

	$dbh = odbc_connect('northwind', '', ''); 
	if (!$dbh) {     
	exit("Connection Failed: " . $dbh); 
	$sql_stmt = "SELECT * FROM form_mpc"; 
	$result = odbc_exec($dbh, $sql_stmt); 
	if (!$result) {     
	exit("Error access records"); 
	while (odbc_fetch_row($result)) {     
	$company_name = odbc_result($result, "Name");    
	$contact_name = odbc_result($result, "Number");     
	echo "<b> Name (Contact Name):</b> $Number ($number) <br>";

You Might Like

Leave a Reply

Your email address will not be published. Required fields are marked *