Insert, View, Edit and Delete Record from Database Using PHP and MySQLi


Demo Download

In this tutorial, I will explain how to insert, view, edit and delete record from database using PHP and Mysqli, basically this tutorial is a second part of Simple User Registration & Login Script in PHP and MySQLi, in this first part I explained how to create simple user registration and login using PHP and MySQLi, if you do not know how to create user registration and user login form so kindly first check this tutorial Simple User Registration & Login Script in PHP and MySQLi, after that now come back to this tutorial.

I have tested this tutorial code from PHP 5.6 to PHP 8.2 versions, it is working smoothly on all PHP versions. However, I would recommend to use the latest PHP version.

I would suggest you to check PHP CRUD Operations Using PDO Prepared Statements, as this is compatible with PHP 7 and PHP 8 both versions.

Steps to Creating an Insert, View, Edit and Delete Record from Database Using PHP and MySQLi

Now I am assuming that you have already created user registration and login forms which I created in Simple User Registration & Login Script in PHP and MySQLi now I will create another table to keeping records in it, update dashboard.php file and add four more new pages which are insert.php, view.php, edit.php, and delete.php, follow the following steps:

  1. Create Another Table for Records
  2. Update Dashboard File
  3. Create Insert Page
  4. Create View Page
  5. Create Edit/Update Page
  6. Create Delete Page

1. Create Another Table for Records

Execute the below SQL query:

CREATE TABLE IF NOT EXISTS `new_record` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `trn_date` datetime NOT NULL,
 `name` varchar(50) NOT NULL,
 `age`int(11) NOT NULL,
 `submittedby` varchar(50) NOT NULL,
 PRIMARY KEY (`id`)
 );

2. Update Dashboard Page

Update dashboard.php file and paste the following code in it.

<?php
include("auth.php");
require('db.php');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Dashboard - Secured Page</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="form">
<p>Welcome to Dashboard.</p>
<p><a href="index.php">Home</a><p>
<p><a href="insert.php">Insert New Record</a></p>
<p><a href="view.php">View Records</a><p>
<p><a href="logout.php">Logout</a></p>
</div>
</body>
</html>

3. Create Insert Page

Create a page with name insert.php and paste the below code in it.

<?php
include("auth.php");
require('db.php');
$status = "";
if(isset($_POST['new']) && $_POST['new']==1){
    $trn_date = date("Y-m-d H:i:s");
    $name =$_REQUEST['name'];
    $age = $_REQUEST['age'];
    $submittedby = $_SESSION["username"];
    $ins_query="insert into new_record
    (`trn_date`,`name`,`age`,`submittedby`)values
    ('$trn_date','$name','$age','$submittedby')";
    mysqli_query($con,$ins_query)
    or die(mysqli_error($con));
    $status = "New Record Inserted Successfully.
    </br></br><a href='view.php'>View Inserted Record</a>";
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert New Record</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="form">
<p><a href="dashboard.php">Dashboard</a> 
| <a href="view.php">View Records</a> 
| <a href="logout.php">Logout</a></p>
<div>
<h1>Insert New Record</h1>
<form name="form" method="post" action=""> 
<input type="hidden" name="new" value="1" />
<p><input type="text" name="name" placeholder="Enter Name" required /></p>
<p><input type="text" name="age" placeholder="Enter Age" required /></p>
<p><input name="submit" type="submit" value="Submit" /></p>
</form>
<p style="color:#FF0000;"><?php echo $status; ?></p>
</div>
</div>
</body>
</html>

insert-new-record

Readers Also Read: Laravel 10 CRUD Application

4. Create View Page

Create a page with name view.php and paste the below code in it.

<?php
include("auth.php");
require('db.php');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>View Records</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="form">
<p><a href="index.php">Home</a> 
| <a href="insert.php">Insert New Record</a> 
| <a href="logout.php">Logout</a></p>
<h2>View Records</h2>
<table width="100%" border="1" style="border-collapse:collapse;">
<thead>
<tr>
<th><strong>S.No</strong></th>
<th><strong>Name</strong></th>
<th><strong>Age</strong></th>
<th><strong>Edit</strong></th>
<th><strong>Delete</strong></th>
</tr>
</thead>
<tbody>
<?php
$count=1;
$sel_query="Select * from new_record ORDER BY id desc;";
$result = mysqli_query($con,$sel_query);
while($row = mysqli_fetch_assoc($result)) { ?>
<tr><td align="center"><?php echo $count; ?></td>
<td align="center"><?php echo $row["name"]; ?></td>
<td align="center"><?php echo $row["age"]; ?></td>
<td align="center">
<a href="edit.php?id=<?php echo $row["id"]; ?>">Edit</a>
</td>
<td align="center">
<a href="delete.php?id=<?php echo $row["id"]; ?>">Delete</a>
</td>
</tr>
<?php $count++; } ?>
</tbody>
</table>
</div>
</body>
</html>

view-record

Readers Also Read: Laravel 10 User Roles and Permissions

5. Create Edit/Update Page

Create a page with name edit.php and paste the below code in it.

<?php
include("auth.php");
require('db.php');
$id=$_REQUEST['id'];
$query = "SELECT * from new_record where id='".$id."'"; 
$result = mysqli_query($con, $query) or die ( mysqli_error($con));
$row = mysqli_fetch_assoc($result);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Update Record</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="form">
<p><a href="dashboard.php">Dashboard</a> 
| <a href="insert.php">Insert New Record</a> 
| <a href="logout.php">Logout</a></p>
<h1>Update Record</h1>
<?php
$status = "";
if(isset($_POST['new']) && $_POST['new']==1)
{
$id=$_REQUEST['id'];
$trn_date = date("Y-m-d H:i:s");
$name =$_REQUEST['name'];
$age =$_REQUEST['age'];
$submittedby = $_SESSION["username"];
$update="update new_record set trn_date='".$trn_date."',
name='".$name."', age='".$age."',
submittedby='".$submittedby."' where id='".$id."'";
mysqli_query($con, $update) or die(mysqli_error($con));
$status = "Record Updated Successfully. </br></br>
<a href='view.php'>View Updated Record</a>";
echo '<p style="color:#FF0000;">'.$status.'</p>';
}else {
?>
<div>
<form name="form" method="post" action=""> 
<input type="hidden" name="new" value="1" />
<input name="id" type="hidden" value="<?php echo $row['id'];?>" />
<p><input type="text" name="name" placeholder="Enter Name" 
required value="<?php echo $row['name'];?>" /></p>
<p><input type="text" name="age" placeholder="Enter Age" 
required value="<?php echo $row['age'];?>" /></p>
<p><input name="submit" type="submit" value="Update" /></p>
</form>
<?php } ?>
</div>
</div>
</body>
</html>

update-record

6. Create Delete Page

Create a page with name delete.php and paste the below code in it.

<?php
require('db.php');
$id=$_REQUEST['id'];
$query = "DELETE FROM new_record WHERE id=$id"; 
$result = mysqli_query($con,$query) or die ( mysqli_error($con));
header("Location: view.php"); 
exit();
?>

Demo Download

Click here to learn how to implement forgot password recovery (reset) using PHP and MySQL.

This tutorial is only to explain the basic concept of PHP CRUD operations, you will need to implement more security when working with live or production environment.

If you found this tutorial helpful so share it with your friends, developer groups and leave your comment.

Facebook Official Page: All PHP Tricks

Twitter Official Page: All PHP Tricks

Article By
Javed Ur Rehman is a passionate blogger and web developer, he loves to share web development tutorials and blogging tips. He usually writes about HTML, CSS, JavaScript, Jquery, Ajax, PHP and MySQL.
    1. Dear Azeem,

      The purpose of this tutorial is to explain the simplest flow, indeed there is a lot of things to do to validate the data but this will create complexity for novice user.

  1. Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, bool given in D:\New folder\htdocs\Welcome\Admin_login.php on line 61

  2. actual error is on
    Notice: Undefined index: job_provider_id in C:\……edit_provider.php on line 3

  3. Dear Javed Sir,
    the error :Undefined index: job_provider_id show in my code please please help

    Update Record

    Update Record
    <?php
    $status = "";
    if(isset($_POST['new']) && $_POST['new']==1)
    {

    $name =$_REQUEST['job_provider_name'];
    $email =$_REQUEST['job_provider_email'];
    $pass = $_REQUEST['job_provider_pass'];
    $cmp_name = $_REQUEST['job_provider_cmp_name'];
    $address = $_REQUEST['job_provider_address'];
    $phone = $_REQUEST['job_provider_phone'];
    $update="update job_provider set
    job_provider_name='".$name."', job_provider_email='".$email."',
    job_provider_pass='".$pass."', job_provider_cmp_name='".$cmp_name."', job_provider_address='".$address."', job_provider_phone='".$phone."' where id='".$id."'";
    mysqli_query($con, $update) or die(mysqli_error());
    $status = "Record Updated Successfully.
    View Updated Record“;
    echo ”.$status.”;
    }else {
    ?>

    <input name="id" type="hidden" value="” />
    <input type="text" name="job_provider_name" placeholder="Enter Name"
    required value="” />

    <input type="text" name="job_provider_email" placeholder="Enter "
    required value="” />
    <input type="text" name="job_provider_pass" placeholder="Enter "
    required value="” />

    <input type="text" name="job_provider_cmp_name" placeholder="Enter "
    required value="” />

    <input type="text" name="job_provider_address" placeholder="Enter "
    required value="” />

    <input type="text" name="job_provider_phone" placeholder="Enter "
    required value="” />

    1. I think you should provide id value in this field.
      The error you are getting is may be because of your database table column name.
      In order to fix your error, I will need to see your code as your query is not about my tutorial, it is something else.

  4. Hi Javed sir, thanks for sharing the very best blog for me because I learn PHP web development and this blog is very useful and helpful for me.
    Thanks again.

  5. Hi Javed first of all thank you so much for this nice script !!

    I did created the database and installed all files on my directory. I did register myself and it actually created my account in the users table.

    BUT when I login, the page go blank (white) no error message but wont go further…

    If I try to go straith to index.php… same think page stay blank white
    Same with dashboard.

    If I enter wrong credentials then I get a proper Wrong Username/password message..

    Do you know what could be the problem ?

    1. Basically, this tutorial is focused on how to use the CRUD operation, well you can store value into column, for example for admin store 1 and for others store 2 in the user_type column.

  6. Very well written and done.
    I’ve juet started writing in the last few days and have seen loot of articles
    simply rework old ideas bbut add vrry little of worth. It’s great to see an informative post of some true value to your
    readers and me.
    It is on the list of creteria I need to replicate as a
    new blogger. Reeader engagement annd material value arre king.

    Many supeerb thoughts; you’ve certainly mahaged to get on my list of sites to
    follow!

    Continue the terrific work!
    Cheers,
    Stanislas

  7. Please post an article for:
    1. CRUD with live search, Pagination, Delete Confirmation dialogue.
    2. mpdf for Indic Complex Unicode Language
    3. Table with listing records in php using MySql Query: Group by & Order by

  8. @Javed what might be wrong here
    Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in C:\wamp64\www\hospital-management\edits.php on line 6
    Call Stack
    # Time Memory Function Location
    1 0.0015 245616 {main}( ) …\edits.php:0
    2 0.0864 255816 mysqli_fetch_assoc ( ) …\edits.php:6

    Update Record

    Update Record

    <?php
    $status = "";
    if (isset($_POST['new']) && $_POST['new'] == 1) {
    $id = $_REQUEST['id'];

    $name = $_REQUEST['nur_name'];
    $phone = $_REQUEST['nur_phone'];
    $quali = $_SESSION["nur_quali"];
    $update = "update nurse set nur_name='" . $name . "',
    nur_phone='" . $phone . "', quali='" . $quali . "',
    where id='" . $id . "'";
    mysqli_query($con, $update);
    $status = "Record Updated Successfully.
    View Updated Record“;
    echo ” . $status . ”;
    } else {
    ?>

    <input name="id" type="hidden" value="” />
    <input type="text" name="nur_name" placeholder="Enter Name" required value="” />
    <input type="text" name="nur_phone" placeholder="Enter Age" required value="” />
    <input type="text" name="nur_quali" placeholder="Enter Age" required value="” />

  9. Amazing tutorial but one things not worked for me. You added ‘submittedby’ method but when I logged in from another account data shows data inserted by previous user. Any solution for this please?

    1. When user logged in, it store the username in session $_SESSION[“username”], you can simply print this value on any PHP, it does not matter and check if its value is changing after login with different users. It should be change. Hope this will solve your issue.

  10. Warning: mysqli_prepare() expects parameter 1 to be mysqli, null given in C:\wamp\www\insert-view-edit-and-delete-record\registration.php on line 21

    Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in C:\wamp\www\insert-view-edit-and-delete-record\registration.php on line 23

    Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in C:\wamp\www\insert-view-edit-and-delete-record\registration.php on line 25

    Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:\wamp\www\insert-view-edit-and-delete-record\registration.php on line 29

  11. When I refresh the page, it keeps adding the same record I already did. The more i refresh, the more it inserts. How to stop that when people refresh?

    1. Add this script just before body closing tag.

      if ( window.history.replaceState ) {
      window.history.replaceState( null, null, window.location.href );
      }

  12. Thank you very much for your work.
    i`m gettint eror message on …
    Fatal error: Uncaught Error: Call to undefined function mysql_error() in C:\xampp\htdocs\subscription\insert.php:14 Stack trace: #0 {main} thrown in C:\xampp\htdocs\subscription\insert.php on line 1
    than
    i changed the msql to msqli but now the error change to…
    Warning: mysqli_error() expects exactly 1 parameter, 0 given in C:\xampp\htdocs\subscription\insert.php on line 14

    what do you recommend please?

      1. sir, i am natarajan, which php developer is best for developing the forms and report , i need master details report and tab function form ,it is possible to develop the php,

  13. Thanks for simple code sir .i have one issue that is in view data viewed in descending order . i also removed the desc in sql query . please reply me.

  14. Hi Javed thank, can you help me this errors for login
    Connected successfully
    Notice: Undefined variable: con in C:\xampp\htdocs\keys\login.php on line 17

    Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\keys\login.php on line 17

    Notice: Undefined variable: con in C:\xampp\htdocs\keys\login.php on line 19

    Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\keys\login.php on line 19

    Notice: Undefined variable: con in C:\xampp\htdocs\keys\login.php on line 23

    Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\keys\login.php on line 23

    Fatal error: Uncaught Error: Call to undefined function mysql_error() in C:\xampp\htdocs\keys\login.php:23 Stack trace: #0 {main} thrown in C:\xampp\htdocs\keys\login.php on line 23

      1. hi, javed i am not able to connect to the database
        i change mysqi into mysql and i get this errors

        Fatal error: Uncaught Error: Call to undefined function mysql_connect() in C:\xampp\htdocs\keys\db.php:7 Stack trace: #0 C:\xampp\htdocs\keys\login.php(10): require() #1 {main} thrown in C:\xampp\htdocs\keys\db.php on line 7

      2. hi javed, thank you trying to help me but i am still unable to connect to the dababase i mention before and i don’t know what i missing

        and i get this message from localhost

        Failed to connect to MySQL

        and i changed mysqli into mysql
        didnot show me any thing

        thank

  15. I downloaded the tutorial and ran it and it works as planned! However, when I switch to another table I can get data to display and can delete a record but when I try to edit a field it does not work. I have checked that the fields have same text-encoding, unsigned, type, length etc, but still cannot get it to work. I have also checked variable and field names for error and there are none. Any help would be appreciated.

      1. Please I have an issue updating a mysql database table from my webpage using php, I will appreciate any help rendered. The data were fetch and display in an HTML table.

        1. I would suggest you first check if your database connection is working or not. Kindly test my demo first, if you are still not able to update then you will need to debug the code manually, try to connect database and print values for testing, and check if it is connected or not, then insert value into database. If insertion is working then updating will work too.

  16. Thanks for the coding and tutorial, but when i applied it, it always getting an error… {“code”:”MethodNotAllowedError”,”message”:”POST is not allowed”}. Do you know why it appeared? thank you

  17. Hi, did u inserted the more inputs.i have tried but i am getting undefined index.please help me with this.

  18. Thank you so much for creating this website. I was able to create a my own system with PHP and MySQL because of your generosity to share your knowledge through your beautiful website. Can you please create a tutorial about “Comments & Reply System”, “Ratings (like giving likes, dislikes, or stars)”, and “basic Facebook-like app with messaging, posting, adding or removing friend features, and or follow or unfollow”?

  19. Thanks for these scripts, they help a lot.
    I am having an issue with trying to edit data from joined tables.
    I can get to the “view records” page fine but am having trouble trying to figure out how to edit data.
    I have two tables joined by an ID Number. I would like, when I click edit, to be able to see and edit data from both tables on the single edit screen. I can add fields from T1 fine, but when I try to add fields from T2 I get an undefined index error. I do not know how to get it to pull data from the second table and then update that data.

  20. As’Salam Alikum,

    very good tutorial thanks for sharing. I have tried it and i am wondering if its possible to create users with privileges to not view other users data so that one user can’t see another user’s data. if you have any idea than please share it.

    thanks

  21. Hello. I have been looking for edit and update page examples online that let you select which table in a database to work on. It seems all examples I find are limited to working on just one table in the database. Is it possible to select a table to edit? That would be a great tutorial.

  22. Warning: Cannot modify header information – headers already sent by (output started at C:\AppServ\www\insert-view-edit-and-delete-record\auth.php:8) in C:\AppServ\www\insert-view-edit-and-delete-record\auth.php on line 11

      1. if we want to amend or change a paritcular or some particular field instead of whole record or change/delete whole record

  23. I’d be interested to see a dynamic field add in the form, and how you handle the array submitted to the insert page. Can you show that?

  24. I am very interested with your tutorial may Allah help you and guide everywhere you are. Thanks a lot.

  25. Hi!
    I get this error message when I log in

    Warning: mysqli_error() expects exactly 1 parameter, 0 given in /home/public_html/insert/login.php on line 28

  26. This works great! However how would I automatically select the correct value in a dropdown when editing a record?

  27. Hello Javed,
    I’m trying to edit the table with ajax, and I’m using $wpdb wordpress hook, can you please tell me what would be the code to edit the table from backend, my table columns are : “links” and “hitstocount”
    So when I want to edit any particular link I’ll need to add a button in front of each of these rows?
    What would be the exact code to do so?

    Thank you!

    1. WordPress have its own structure, you need to follow it, learn how to use ajax in WordPress, you will need to either create a plugin or work on themes function.php file. Unfortunately, currently i didn’t share any tutorial about it, but you can find it easily.

  28. Hi,its a very great coding.
    but may i know why u use “$count=1;” and end with “$count++;” ?
    I need to know because i still new in programming.

    Thank you

      1. I need help.
        I have one page , where i put registration page with firstname, lastname,age,group.. and in same page below
        registration page there is show data all data coming from data base.. now i have to put edit button on each row of show data.. when i click edit button ,, the whole row get blank and two more button come cancel button and update button.. on same row..then when i put updated data on that blank row , then i click update.. please send these code.

        1. Hi Sanjeet,
          I have already shared how to insert, edit, view and delete in very simple way using PHP.
          I would suggest, first download my tutorial and try to execute the same file. If it is working then understand how the codes are working through my tutorial explanation then try to edit code as per your need. Hope this will help you to edit.

          1. Hi i have problem
            Undefined variable: status in C:\xmapp\htdocs\___\action.php on line 10
            and this bro please help me…
            Undefined index: id in C:\xmapp\htdocs\travels\action.php on line 4
            i already defined but system throw tis error.

  29. Good night, what if I want to insert, update (edit) and delete a specific row in the table without switching page? Per example, I click “edit” and a pop up appears where I can modify the data… Or I click “insert” and a pop up appears where i can insert a new row… and the same for deleting…

    Thank you!

  30. It is very helpful Thank you for your help
    But in my case insert.php is not working line 12 $stn_date(“Y-m-d H:i:s”) is not responde to me .
    It says pares error.

  31. Hi I encounter this error.
    Fatal error: Uncaught Error: Call to undefined function mysql_error() in C:\xampp\htdocs\impex insert.php:19 Stack trace: #0 {main} thrown in C:\xampp\htdocs\impex insert.php on line 19

    1. use mysqli_error() function instead mysql_error() because in lastest php version is not supported mysql_error() function

  32. Thanks for this clear and simple code, I was lookin for this, tons of videos or examples didn’t work, this one does! Everything works fine!

    Only a suggestion: On the view.php, when click on delete, would be great to before the entry is deleted, a popup/alert/warning to ask if really want to delete it.

  33. I want to add a button in the place of age in table when the user clicks the download button the file should download which is uploaded when admin is inserting data
    ex:-
    name:-something
    age:-22

    I want
    name:-something
    Download link (instead of showing age i want a button which user can download file ).

  34. Warning: session_start() [function.session-start]: Cannot send session cache limiter – headers already sent (output started at C:\xampp\htdocs\insert-view-edit-and-delete-record\login.php:15) in C:\xampp\htdocs\insert-view-edit-and-delete-record\login.php on line 16

    Warning: Cannot modify header information – headers already sent by (output started at C:\xampp\htdocs\insert-view-edit-and-delete-record\login.php:15) in C:\xampp\htdocs\insert-view-edit-and-delete-record\login.php on line 33

    sir i have errors like that at the beginnig plz tell me what to do?

  35. Hi bro, nice its works perfectly but in login page.
    Warning: session_start(): Cannot send session cache limiter – headers already sent
    can tel me whats problem?

    1. Hi Shashi, kindly check on your all pages that session_start() function must be at the beginning of the page, if does not, kindly move it on the top of every PHP pages, this will solve your issue.

  36. Hi, thanks for the tutorial.
    where should I make change to switch to another table? I’m trying to point to another table in the database, so I tried renaming new_record to the one I want (in insert.php), but the data is not saved to the new table.

    1. If you are facing issue during inserting into new table, first make sure that you have created table in database and check your column names clearly, and insert very simple record in it via PHPmyAdmin and then add records from PHP.

      1. I’ve created my new table, made all the columns the same as in new_record table, insert a simple record then add record from PHP as you stated. I still get the error

        Fatal error: Uncaught Error: Call to undefined function mysql_error() in C:\xampp\htdocs\record\insert.php:37 Stack trace: #0 {main} thrown in C:\xampp\htdocs\record\insert.php on line 37

        where line 37:
        mysqli_query($con,$ins_query) or die (mysql_error()) ;

        thanks for your help

  37. Sir, thanks for uploading the codes. They are really useful. I am using only the ‘users’ table and performing the update, delete and view actions on it.
    There are two problems that I am facing.
    Number One: when inserting new user in the table, it is working perfectly. But if I logout and go to the login page and enter that same username & password added recently, it says invalid username/password.
    Number two: While performing the update, it gives error like:

    Warning: mysqli_error() expects exactly 1 parameter, 0 given in C:\xampp\htdocs\NEW\edit.php on line 34….
    and this is the code snippet-
    if(isset($_POST[‘new’]) && $_POST[‘new’]==1)
    {
    $id=$_REQUEST[‘id’];
    $trn_date = date(“Y-m-d H:i:s”);
    $username =$_REQUEST[‘username’];
    $email =$_REQUEST[’email’];
    $password=$_REQUEST[‘password’];
    $submittedby = $_SESSION[‘username’];
    $update=”update new_record set trn_date='”.$trn_date.”‘, username='”.$username.”‘, email='”.$email.”‘, password='”.$password.”‘ , submittedby='”.$submittedby.”‘
    where id='”.$id.”‘ “;
    mysqli_query($con, $update) or die(mysqli_error()); <– giving the error here
    $status = "Record Updated Successfully.

    1. Hi Suman, To log in you must need to check either user is inserted in database or not, and then when you are trying to log in so try to echo value of user and password on the form submission so you can debug where there error is.
      And for 2nd error, simply replace your mysqli_error(); with mysqli_error($con);

      1. Hi Mr Javed Ur Rehman. I like your tutorial thank you.
        I had the same problem and did what you told Suman.It works but it gives me a syntax error: here is the errore below

        You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ‘s ‘, age=’23’, submittedby=’Benedictus’ where id=’19” at line 2

  38. it keep saying username or password incorrect but is in database, then i can’t view the index and other pages apart from login page

    1. Make sure your database connection is working, this tutorial have my credentials, so make sure you have updated these credentials in db.php with your credentials.

    1. You need to debug the error, first check if database connection working on that page by printing something from database. Then debug other things such as form visible or not? getting GET value from the URL or not.

  39. hi brother, I found your codes very useful to me as i’m learning php as a beginner.
    The way you had coded is very easy to understand.
    thankyou very much.

    and, what I want to know is, can we set download database function from php and MySQL?

  40. Mr Javed what is the uses of dashbord code ccould you tell me please!!!!!!

  41. I Would like to great thanks for you Mr Javed your tutorial is best

  42. hey man im having some problems with edit page here

    <input name="id" type="hidden" value="” />
    <input type="text" name="name" placeholder="Enter Name"
    required value="” />

    it was supposed to show the current row name and nothing happens its just in blank

  43. hey man im having some problems with edit page in line 24
    if(isset($_POST[‘new’]) && $_POST[‘new’]==1)
    what’s the ‘new’ camp?

      1. Sir can u guide me that i want to update the data of particular row clicking on edit button and a modal box open on that click containing the current value and from there only i want to update the fields

        1. I have created separate tutorials for popup and this tutorial is focus on CURD operations, you can simply check here how i updated record. And for popup you can check my other tutorial in demo section.

        1. What do you mean by cancel button? do you want to disable user?
          If you want to disable user, simply add new column in user table with field name active, and put 1 for active user and 0 for disabled user.

          1. Sir, very cute work you have here. please on the insert function is it possible to make users who uploaded the file to see only what they uploaded. and limit other users to insert and edit what another user uploaded?
            how can i get that done????

          2. Yes it is possible, everything is possible, you will need to insert data based on user ID and show only those results which are uploaded by same user ID, in this way, users will view only their uploaded data.

  44. Hello Friend Javed

    AOA

    I want a complete form with master and detail as per below format. kindly send as soon as possible.
    Thanks in advance.

    Best regards,

    Purchase No. : 0001 Date : 29/04/2019

    Supplier Name : abc company

    Ref No. : y-001

    sr. no Prod. Code Product Name qty rate amount discount net amount

    1 0001 Computer 10 20,000 200,000 5,000 195,000
    2 0002 Printer 2 9,000 18,000 500 17,500
    .more entries ======= ===== =======
    . 218,000 5,500 212,500

  45. Hi Javed, your code is excellent. It worked really smoothly, first time. For the Password Recovery code, there is a file index.php. There is also a similar one in the main program. Do I replace the first index.php file with the second one?
    Also, in a separate project I am working on, I have a list of football matches, and next to each match row I want to add fields for the predicted scores in two separate fields(example: homescore 2, awayscore 2 and insert these to the database. I would like to have an Insert button and an Edit button, all in the same row. How do you suggest I go about it please?

  46. Dear JAVED UR REHMAN,
    Always you help people I benefit by your codes
    wish you a brilliant future

  47. I can retrieve records, I can go to insert, but it will not insert records, errors out. I cannot edit records, errors out. I can delete records no problem. Can I email you my code to look at? My database is for internal network, no external access.

  48. Hello dear Javed Ur Rehman. Thank you for brilliant script. But how can changed that after inserting new record the script automatically show view.php instead view.php with “status” New record inserted? I do it with “header” sting but it’s not working. Thank you.

    P.S. This problem i have with update record

    <?php
    if(isset($_POST['new']) && $_POST['new']==1)
    {

    $trn_date = date("Y-m-d H:i:s");
    $name =$_REQUEST['name'];
    $age = $_REQUEST['age'];
    $submittedby = $_SESSION["username"];
    $ins_query="insert into new_record (`trn_date`,`name`,`age`,`submittedby`) values ('$trn_date','$name','$age','$submittedby')";
    mysqli_query($con,$ins_query) or die(mysql_error());

    $status = "New Record Inserted Successfully. View Inserted Record”;

    //– this line not work
    header(“HTTP/1.1 301 Moved Permanently”);
    header(“Location: view.php”);
    }
    ?>

    1. Kindly check my update query, you are using insert query.
      Also header will redirect you only if there is no HTML generated before it. First test header redirect on separate page check is it working on plane page or not.

      1. Thank you for fastest reply. It was my fault, sorry. I forgot to write “;” in my file… Your script work best. But your script have no pagination and this is a problem, because i have more than 200 records… And using your pagination script i have a problem. When i editing a record and click “submit button” the script reloading me to first page, but i’m editing for example a record on 15 page… Sorry for my bad english.

    2. whats is this not receiving any email not you give full script on the site.A lot of issues with code

    3. Can someone tell me why this is failing?

      $update=”UPDATE Camera SET Site='”.$Site.”‘,Driver Nb='”.$DriverNb.”‘,Driver Name='”.$DriverName.”‘,FM='”.$FM.”‘,DLM='”.$DLM.”‘,SafetyRep='”.$SafetyRep.”‘,Issued='”.$Issued.”‘,Returned='”.$Returned.”‘,Camera Serial='”.$CameraSerial.”‘,Camera Status='”.$CameraStatus.”‘,Monitor Serial='”.$MonitorSerial.”‘,Monitor Status='”.$MonitorStatus.”‘,Comments='”.$Comments.”‘ WHERE id='”.$id.”‘”;

      mysqli_query($conn,$update) or die(“failing at query: ” . mysqli_error());

  49. Hi, thanks for the code, however, when I enter data into the insert page, it returns a blank page and the view records table does not reflect the entered data, how can I fix this, thank you

    1. Hi Mike, make sure that your database connectivity is working fine, if your database is not connected then you will not be able to insert or fetch updated records.

    2. Kudos to your great work, I got your source code on “insert, view, edit and delete Record from database using php and mysqli” after learning with it I tried uploading it in a live server but after registration and login, it will show a white screen instead of proceeding index.php page, please help me out, exams is at the corner

  50. I am receiving the following error sometimes not all the time can you advise if i send you what i am doing please:

    Dashboard | Insert New Record | Logout

    Update Recipe Record

    Warning: mysqli_error() expects exactly 1 parameter, 0 given in C:\xampp\htdocs\download1\demo\edit.php on line 64

    you can see whats happening in the test website:

    regards Steve Jones

    1. I did check and i didn’t find anything wrong, i think you should check line no 64 and see what is missing over there, i think you should run my code separately first, if it is working separately fine then you should integrate it with your module.

  51. Hi Javed Ur Rehman,

    great tut. could you maybe do a simple username change page to work with this system?

    1. For this purpose you must need to make email as unique ID and allow users to change their username, add additional column with name username that they can change easily based on user email address.

  52. Unable to connect
    Firefox can’t establish a connection to the server at localhost.

    The site could be temporarily unavailable or too busy. Try again in a few moments.
    If you are unable to load any pages, check your computer’s network connection.
    If your computer or network is protected by a firewall or proxy, make sure that Firefox is permitted to access the Web.

    I am getting this error.can u help me to solve it??

    1. Richa browser does not have anything with the database connection, you need to enter your credentials in db.php file, if you do not know how to connect database using php, then you can search on Google for database connection examples.

  53. Hi sir i’m a 3rd yr student! How to solve these type of errors from the above coding?
    “”Warning: require(db.php): failed to open stream: No such file or directory in C:\xampp\htdocs\login\insert.php on line 2

    Fatal error: require(): Failed opening required ‘db.php’ (include_path=’C:\xampp\php\PEAR’) in C:\xampp\htdocs\login\insert.php on line 2″”

  54. Respected sir when i insert the name and age in insert.php it show the Warning: mysqli_error() expects exactly 1 parameter, 0 given in /opt/lampp/htdocs/php/insert.php on line 13.all code same as your.
    please sir give the solution of this warning. Thanks

  55. Javed I’m facing Error about the edit button.

    <input name="ID" type="hidden" value="” />
    <input type="text" name="Product" placeholder="Enter Product" required value="” />
    <input type="text" name="Price" placeholder="Enter Age" required value="” />
    <input type="text" name="Quantity" placeholder="Enter Age" required value="” />

    When I run the html It suddenly go to Auth.php

    1. It Seems like that you changed the names of input fields, first i will suggest to run the tutorial same as i shared with you, once you understanding working then you can modify it for your need.

  56. HI Javed
    help me
    how to display data based on username
    and how to maintain when the same username and email registration then can not register and there is a forgotten password menu

      1. please give examples of queries from the tutorial above, because I just learned php

  57. Hi Javed, love the tutorial.

    In the ‘insert.php’ code, does the following code cause or have an effect on an undefined index below such as ‘name’:

    if(isset($_POST[‘new’]) && $_POST[‘new’]==1){

    Also does this need to be edited if I add more inputs to the form>?

    Thanks in advance

    1. No it does not need to be edit, you can any number of fields but if you remove the above condition so you may have to face undefined index issue, because it checks either form is submitted or not, if form is submitted then we get the values and insert them. If you remove it then when you will open this form it will try to find variables which are not available so you have this error.

      1. That’s great thanks for the help!

        Does this include protection against SQL injection?

          1. Thanks for clarifying I wasn’t sure if that counted as security against SQL injection.

            Can you help me with a way of adding password hashing with password_hash and password_verify?

  58. Javed Ur Rehman I have register user every time. But I am not able to login on your demo profile. Are you sure your code is working fine. Because I am a developer. Please check again and let me know what is the issue.
    Thank you for share this code. But Please do correct…
    Then it will very help full for another guy. I don’t mind
    Thanks ..

  59. Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in /home/ubuntu/workspace/bearbeiten.php on line 17

    I dont know how to fix this :/ can you help me plz ???

  60. i got this error but i do not know how to solve this problem
    Notice: Undefined index: ic in C:\xampp\htdocs\OnlineRegister\delete.php on line 4

    1. There is no need to browser delete page, if you browse it will give error because we need id to get and use to delete data of that id, if you open this page directly it need id, and it is not able to find id therefore it will give you error, better you just use it in view page as i used.

  61. Warning: mysqli_error() expects parameter 1 to be mysqli, string given in C:\xampp\htdocs\cnd\edit.php on line 35

    Hi

    I am getting this error on edit page

  62. Thanks Buddy, It worked.
    I am a java developer but trying to learn php as well. 🙂
    This article is perfect for beginner.

  63. what does the $con stands for? what does it define ,it is found on the edit page and $result = mysqli_query($con,$sel_query);
    while($row = mysqli_fetch_assoc($result)) { ?>
    what does the above code fine?

    i also have problems with the insert.php with this code ,it gives error saying something about column 1 and denies to insert data into database

    1. You can display anything from database, i am also showing information from database on view page, kindly check view page above for implementation example.

  64. Dear Sir,

    please send reply for bellow points.

    how to i have md5 to string convert password in php and codignator.

    and one site complete in WordPress but i have first open my static html page then redirect main site how to do it.

  65. your way of explaining is wonderful and practical. Every thing working well. My doubt is that using login code, it is not directing to any page. screen becomes clear and no link appears.

    i am getting following error
    [09-May-2018 18:43:08 Asia/Calcutta] PHP Warning: session_start(): Cannot send session cache limiter – headers already sent (output started at /home/pctant/public_html/editing_data/login.php:10) in /home/pctant/public_html/editing/login.php on line 12

    1. Check your database connection, because if you got error in DB connection, it will print DB error message, which will appear before session_start(). SO if anything print before session_start() you will get these kind of error.

    2. Hi. I have Warning: session_start(): Cannot send session cache limiter – headers already sent (output started at /public_html/admin/login.php:1) in /public_html/admin/login.php on line 12

      DB connection is fine

      1. Well it seems like you are getting error in DB connection, therefore you are getting error of “headers already sent” which means db connection failed and it generated html code, therefore session_start() giving error.

  66. Good day,
    Please i am having this issue, i have a site with user account, when i log in as admin i cannot edit users profile.
    I tried to add edit button on the profile page, but when i edit it does not change the value.
    I added ModifyPhone.php, i edited process.php, also edited the profile index page, what else do i do so the change will be saved and reflect on the user details

    1. Gary kindly check update query, as update query help you to update data in your table, better you should try your query on sql direct, if that is not updating in direct sql then you should first fix your sql query to reflect the update.

      1. can u help me do inventory system for ict equipment in hospital just do insert,view, update and delete function…

        1. Dear Nurul, currently i do not having and such tutorial, however you can use my above code script for all insert, view, update and delete function, all you need is just to change fields name and data as per your need.
          Thanks

  67. I just came to learn only Insert data on MySQL Database, but because of your guide, I learn easily to update database too.

    Thank you Javed.

    Big Thumbs Up👍👍👍👍👍

  68. when i try to log in then is shows me this error plz help me

    mysqli_error() expects exactly 1 parameter, 0 given in C:\xampp\htdocs\php crud\login.php on line 28

  69. Thanks a lot for the time and effort you put in to make this tutorial easy to understand. I really benefited from it. Please I have one question. Everything is working fine but it still shows undefined parameter. Mysqli requires one parameter. It shows it on the edit page.. Could it be because I’m not yet logged in?

  70. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ” where id=’1” at line 3

    i got this arrow. can u explain it ?

  71. Good Job.
    But it seems you only fetch the last record in the databse to be display in the view.php using “ORDER BY id DESC.
    Thanks.

  72. 1.Notice: Undefined index: id in C:\xampp\htdocs\practice\delete.php on line 3

    Warning: mysqli_error() expects exactly 1 parameter, 0 given in C:\xampp\htdocs\practice\delete.php on line 5
    HOW TO FIX IT But the code is same as ur
    2.when i am running these modules it redirect me on the login page
    how to fix it….

    1. You can not directly open this page, as this page require an ID which record you want to delete, also you must be make sure that you are logged in to delete any record.

  73. This is great, thank you. How does this apply when working with radio buttons and dropdown menus?

  74. thanks for this great tutorial but after login , it shows me a blank page ,
    how to fix this issue

    thanks

    1. Check if your session is set or not, at the time of logged in $_SESSION[‘username’] is set.
      Also make sure you are redirected to the index page, check the address bar URL must contain /index.php
      if you do not see index.php after log in this mean you are not redirecting.
      I will advise you to check this code on both local machine and web server, sometimes this happen due to PHP version issue.

      1. Can you direct me to a page that will show me how to NOT duplicate email addresses when users try to sign up? In other words, if the email is already in database show error and reset their password if they like. Thank you for great tutorial.

  75. i want to let you know that i have tried several tutorials but this your tutorial is the BEST , I mean THE BEST , no error, no hidden code, , man You are good, May God bless you for me

  76. Very interesting tutorial, I’m wondering for instance if user1 can edit or delete the post of user2.

  77. When you are creating user…it creates
    when another creates the same username it blocks both id???
    solution please????

  78. 1. Create Another Table for Records

    Execute the below SQL query:
    CREATE TABLE IF NOT EXISTS `new_record` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `trn_date` datetime NOT NULL,
    `name` varchar(50) NOT NULL,
    `age`int(11) NOT NULL,
    `submittedby` varchar(50) NOT NULL,
    PRIMARY KEY (`id`)
    );
    1
    2
    3
    4
    5
    6
    7
    8

    CREATE TABLE IF NOT EXISTS `new_record` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `trn_date` datetime NOT NULL,
    `name` varchar(50) NOT NULL,
    `age`int(11) NOT NULL,
    `submittedby` varchar(50) NOT NULL,
    PRIMARY KEY (`id`)
    );
    Please how do i do this command in cmd or where??

  79. sir i want a code in mysqli in which login/logout time will be save in databse.please help sir.

  80. Are you sure the insert code is correct?? seems to have no relation to the database ‘registers’ that we create at start of tutorial .

  81. Hi i cant get your connect db to even work so i changed with one i use and it connected.,then every page is full of errors like:(view page)
    mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in C:\wamp64

    and in (insert page)
    Parse error: syntax error, unexpected ‘$trn_date’ (T_VARIABLE) in C:\wamp64 etc

    looks really good as well,,,pity i cant get it to run smoothly.

  82. Thanks for your great article. It cleared my many doubts. As did all as you mentioned but after creating a user when i click submit and login it stays on login.php page and shows whole page white. it doesnt go to index.php page. Could you please help me this as i am stuck at this stage.

    1. 10Q it is helpfull but in my case insert.php is not working .
      Pares error in line 12

  83. goooood one bro,, you are a genius keep it up.. how i wish i could meet with you bro…

  84. hi, first off, thank you for the clear code. One problem though, when I try to add a user and click the submit button, it goes to a blank page but does not add the user. I have tried to look for the problem for two days now with no success. kindly help.

  85. As Salam Alaikum, do you think it is possible for there to be a page where the user may only be able to modify their own details? e.g. change only their own password.

    1. simple create a member secure area and then users can edit anything you want to edit

  86. It is great effort without any confusion. Pls continue your contribution
    Thank u so much

  87. This blog is very helpful for php beginner’s, i really appreciate with you tutorial….

    Thanks

  88. thank you very much for helping me out start over again with latest mysqli command. if any inquiry may i know your email?

  89. I am very new to PHP and MySQL, just copied your code and run everything works perfectly fine. Please can you post code on how to insert more than two records into the Register database?

    I made attempt to add more columns as Gender, Phone Number, Address, etc to be displayed when view.php was executed but ended up getting error message. Please assist.

  90. Hello, I have noticed that it is possible to delete a record even though it is not logged in, because you do not call auth.php, so just enter the url and any ID and the record will be deleted by external people. It’s easy to fix but it’s important to warn. Sorry for spelling. Thanks, Alexandre Schmitz

  91. Strict Standards: date() [function.date]: It is not safe to rely on the system’s timezone settings. Please use the date.timezone setting, the TZ environment variable or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected ‘UTC’ for ‘8.0/no DST’ instead in C:\AppServ\www\file1\edit.php on line 27
    how to solve this one/

  92. Great and clear, please help me how to create referral system to plug on my website?

Comments are closed.