Basic insert, view, edit, delete and update using PHP and Mysql | 2my4edge

11 December 2014

Basic insert, view, edit, delete and update using PHP and Mysql

Hi readers, today i going to post one of old topic in php and  mysql, here i'm going to post Insert data through form, and fetch / view the data from database, and also Edit, Delete and Update with detailed explanation.  i know mysql is depreciated, even most of the people are using mysql so now i'm going to use mysql and i'll update with mysqli and pdo later, now i'm going to explain the basics of php mysql functions, how to insert, fetch, delete, update like all operations. New with Codeigniter insert edit view update delete


DOWNLOAD                     LIVE DEMO

FILES
  • db.php
  • index.php
  • insert.php
  • view.php
  • edit.php
These are the files needed to execute the basic insert fetch edit delete operation, let see what the file contains. i already posted how to create database and insert code and AJAX insert without refresh the page. 

DB.PHP
first we have to connect the db file.
<?php
ob_start();
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_DATABASE', '2my4edge');
$connection = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD) or die(mysql_error());
$database = mysql_select_db(DB_DATABASE) or die(mysql_error());
?>

i believe you can get clear idea from the color variation, RED all database fields, and the other all separated one with other same.

DATABASE NAME --> 2my4edge
TABLE NAME --> sample
TABLE FIELDS --> id(int, primary key, auto increment), username(varchar), emailid(varchar), mobileno(varchar), created(timestamp)

INDEX.PHP
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Insert form</title>
<link type="text/css" media="all" rel="stylesheet" href="style.css">
</head>

<body>
<div class="display">
<form action="insert.php" method="post" name="insertform">
<p>
  <label for="name" id="preinput"> USER NAME : </label>
  <input type="text" name="username" required placeholder="Enter your name" id="inputid"/>
</p>
<p>
  <label  for="email" id="preinput"> EMAIL ID : </label>
  <input type="email" name="usermail" required placeholder="Enter your Email" id="inputid" />
</p>
<p>
  <label for="mobile" id="preinput"> MOBILE NUMBER : </label>
  <input type="text" name="usermobile" required placeholder="Enter your mobile number" 
                                                           id="inputid" />
</p>
<p>
  <input type="submit" name="send" value="Submit" id="inputid1"  />
</p>
</form>
</div>
<?php include('view.php'); ?>
</body>
</html>
here i'm just viewing the view.php file below the form but you can make that separate page for that. the action will be on insert.php page. method is post.

INSERT.PHP
the index.php page form is run in the insert.php.
<?php
 ob_start();
  include("db.php");
  if(isset($_POST['send'])!="")
  {
  $username=mysql_real_escape_string($_POST['username']);
  $usermail=mysql_real_escape_string($_POST['usermail']);
  $usermobile=mysql_real_escape_string($_POST['usermobile']);
  $update=mysql_query("INSERT INTO sample(username,emailid,mobileno,created)VALUES
                                      ('$username','$usermail','$usermobile',now())");
  
  if($update)
  {
      $msg="Successfully Updated!!";
      echo "<script type='text/javascript'>alert('$msg');</script>";
      header('Location:index.php');
  }
  else
  {
     $errormsg="Something went wrong, Try again";
      echo "<script type='text/javascript'>alert('$errormsg');</script>";
  }
  }
 ob_end_flush();
?>
if the data is successfully registered, the header location will be to index.php

VIEW.PHP
<?php
 include('db.php');
  $select=mysql_query("SELECT * FROM sample order by id desc");
  $i=1;
  while($userrow=mysql_fetch_array($select))
  {
  $id=$userrow['id'];
  $username=$userrow['username'];
  $usermail=$userrow['emailid'];
  $usermobile=$userrow['mobileno'];
  $created=$userrow['created']
?>

<div class="display">
  <p> USER NAME : <span><?php echo $username; ?></span>
    <a href="delete.php?id=<?php echo $id; ?>" 
    onclick="return confirm('Are you sure you wish to delete this Record?');">
            <span class="delete" title="Delete"> X </span></a>
  </p>
  <br />
  <p> EMAIL ID : <span><?php echo $usermail; ?></span>
    <a href="edit.php?id=<?php echo $id; ?>"><span class="edit" title="Edit"> E </span></a>
  </p>
  <br />
  <p> MOBILE NO : <span><?php echo $usermobile; ?></span>
  </p>
  <br />
  <p> CREATED ON : <span><?php echo $created; ?></span>
  </p>
  <br />
</div>
<?php } ?>


View page contains edit and delete link in the while loop, here we are passing the values though id for edit and delete, like

<a href="delete.php?id=<?php echo $id; ?>" 
    onclick="return confirm('Are you sure you wish to delete this Record?');"> X </a>
<a href="edit.php?id=<?php echo $id; ?>"> E </a>
 we have to give this link before the while loop ends,

DELETE.PHP
<?php
  ob_start();
  include("db.php");
  if(isset($_GET['id'])!="")
  {
  $delete=$_GET['id'];
  $delete=mysql_query("DELETE FROM sample WHERE id='$delete'");
  if($delete)
  {
      header("Location:index.php");
  }
  else
  {
      echo mysql_error();
  }
  }
  ob_end_flush();
?>
the delete.php is deleting the data what are the data is there in the ID. if successfully deleted the page will goes to index.php page.



EDIT.PHP
this edit page contains both edit form and also update code.
<?php 
ob_start();
include('db.php');
if(isset($_GET['id']))
{
  $id=$_GET['id'];
  if(isset($_POST['update']))
  {
  $eusername=$_POST['eusername'];
  $eusermail=$_POST['eusermail'];
  $emobile=$_POST['eusermobile'];
  $updated=mysql_query("UPDATE sample SET 
        username='$eusername', emailid='$eusermail', mobileno='$emobile' WHERE id='$id'")
or die();
  if($updated)
  {
  $msg="Successfully Updated!!";
  header('Location:index.php');
  }
}
}  //update ends here
ob_end_flush();
?>
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Edit form</title>
<link type="text/css" media="all" rel="stylesheet" href="style.css">
</head>

<body>
<?php 
  if(isset($_GET['id']))
  {
  $id=$_GET['id'];
  $getselect=mysql_query("SELECT * FROM sample WHERE id='$id'");
  while($profile=mysql_fetch_array($getselect))
  {
    $username=$profile['username'];
    $usermail=$profile['emailid'];
    $usermobile=$profile['mobileno'];
?>
<div class="display">
  <form action="" method="post" name="insertform">
    <p>
      <label for="name"  id="preinput"> USER NAME : </label>
      <input type="text" name="eusername" required placeholder="Enter your name" 
      value="<?php echo $username; ?>" id="inputid" />
    </p>
    <p>
      <label  for="email"  id="preinput"> EMAIL ID : </label>
      <input type="email" name="eusermail" required placeholder="Enter your Email" 
      value="<?php echo $usermail; ?>" id="inputid" />
    </p>
    <p>
      <label for="mobile" id="preinput"> MOBILE NUMBER : </label>
      <input type="text" name="eusermobile" required placeholder="Enter your mobile number" 
      value="<?php echo $usermobile; ?>" id="inputid" />
    </p>
    <p>
      <input type="submit" name="update" value="Update" id="inputid1" />
    </p>
  </form>
</div>
<?php } } ?>
</body>
</html>



REALATED POSTS :










94 comments:

  1. I am beginner for php. tutorial was helped me lot. thank u .

    ReplyDelete
  2. thank for coding

    ReplyDelete
  3. Good script, this can be the beginning of something great

    ReplyDelete
  4. wow !!!!!

    really too much useful and helpful too

    thanx Arunkumar Maha for these work

    ReplyDelete
  5. your site is too much loading when it was open...................

    ReplyDelete
  6. thank you your site is very useful

    ReplyDelete
  7. when will you release the codes for pdo? mysql is already depreciated. thanks!

    ReplyDelete
  8. thanks for information and the artikel is not bad

    ReplyDelete
  9. Thanks for the nice documentation. Its really helpful for the beginner.......

    ReplyDelete
  10. Hi, i'm a newbie in PHP coding. May I ask which part does the form validation located?

    ReplyDelete
  11. Thanks for the nice documentation. Its really helpful for the beginner....... thanks very muchhhh

    ReplyDelete
  12. Thank Q so much. these examples are very useful.

    ReplyDelete
  13. wow thanks for this tutorial. this the best tutorial that i see in the web so far.

    ReplyDelete
  14. do you know what is panel manager in vb.net because i think that is the best way to create a tabulated form using panel and a button hide or unhide, that panel is too good to use than using tabcontrol in a 1 form in vb.net

    ReplyDelete
  15. I'm a first year computer science student and it's help me a lot.
    Thank you.

    ReplyDelete
    Replies
    1. Aww To Easy for me you Know That

      Delete
  16. THANKS FOR THE USEFUL CODES

    ReplyDelete
  17. Thanks for the post. Keep it up guys.

    ReplyDelete
  18. Thank You so much. I'm a beginner, it helped me a lot..

    ReplyDelete
  19. i am really appreciated with your academic help. PS

    ReplyDelete
  20. How to view the data from db and modify the data then update data?

    ReplyDelete
  21. this example is helped me a lot.......

    ReplyDelete
  22. Its Clear ...good job and Thanks

    ReplyDelete
  23. really this is help for beginners...
    thank you!!!!

    ReplyDelete
  24. I have a problem I cannot figure out. I used the above scripts, I can add but I cannot edit, I get a blank screen. I have found other examples on the net and have the same issue. I would think it is permissions but I can add and I get the response back after adding. Any idea's?

    ReplyDelete
  25. Thanks For sharing

    www.rationaltechnologies.com

    ReplyDelete
  26. i am not able to insert data. it display nothing.

    ReplyDelete
    Replies
    1. BHAI PLS CHECK THE TABLE NMBR IS WRONG ON EDIT PAGE, PLS CHECK IN THESE 2 Vriables
      1- $updated
      2-$getselect

      Delete
    2. Please give me solution of this Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\Final\edit.php on line 37

      Delete
    3. Please give me solution of this Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\Final\edit.php on line 37

      Delete
    4. I experience this warning.Please chech your select query,Data is get or not

      Delete
  27. Nice tutorials for beginner, thanks for sharing this tutorial.

    ReplyDelete
  28. Thanks so much..this tutorial.

    All the Best.





    juber khan

    ReplyDelete
  29. Thanks !
    All the Best


    Juber khan

    ReplyDelete
  30. its a very good code program i help fully ..

    ReplyDelete
  31. Thanks a lot. Your code is really helpful.

    All the best.

    ReplyDelete
  32. Thanks for your coding, very helpful, I do however have 1 question. Can these 4 files (view, add, edit, delete) be combined in 1 file?

    ReplyDelete
  33. Thanks for your coding, very helpful, I do however have 1 question. Can these 4 files (view, add, edit, delete) be combined in 1 file?

    ReplyDelete
  34. thank u so much...really helpful this tutorial

    ReplyDelete
  35. Wow Thank you so much. This is just what i was looking for. And it worked on my first try! Thanks again

    ReplyDelete
  36. simple example in insert delete in php

    ReplyDelete
  37. sir....i did like this
    but edit form is completely white....help me

    ReplyDelete
  38. Very help full INFORMATION,,,,SIR

    ReplyDelete
  39. style.css file is needed.

    ReplyDelete
  40. Your tutorials inspired me to start a blog.
    Insert Update Delete in PHP

    ReplyDelete
  41. Thanks for the tutorial.

    Ahmad
    Miri, Sarawak, Malaysia.

    ReplyDelete
  42. You are a gifted programmer and a good teacher. Thanks a lot.

    ReplyDelete
  43. action=""
    In edit.php what action we need to give

    ReplyDelete
  44. this is piece of shit

    ReplyDelete
  45. how to get single record of table in database by using login page(php)

    ReplyDelete
  46. what is the table called iedu

    ReplyDelete
  47. Fatal error: Call to undefined function mysql_connect() in C:\xampp\htdocs\database\db.php on line 7

    ReplyDelete
  48. Hi i am newbie this is my problem
    ( ! ) Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\wamp\www\gelo\EDIT.PHP on line 37
    Call Stack
    # Time Memory Function Location
    1 0.0010 145560 {main}( ) ..\EDIT.PHP:0
    2 0.0410 169096 mysql_fetch_array ( ) ..\EDIT.PHP:37
    can you help me please? thank you

    ReplyDelete
  49. thank u for sharing this

    ReplyDelete
  50. Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\edit\edit.php on line 37

    ReplyDelete
  51. how to view data in edit page for editing

    ReplyDelete
  52. A lot of many many thank to u sir because i have many problem in crud function .so i learned all crud function......

    ReplyDelete
  53. please in the edit.php i want to know what the iedu stands for

    ReplyDelete
    Replies
    1. Sorry @T-Rex xx, That is actually table name, i have changed now. that `sample`. table name.

      Delete
  54. What is the function ob_start(); for ?

    ReplyDelete
  55. Its really good documentation for both fresher and experience also
    Great work....!

    ReplyDelete
  56. Thank mr this cod is vre useful

    ReplyDelete
  57. Thank you This cod is very useful

    ReplyDelete
  58. thank you so much ... really it's very easy and simple code .....very very useful... thanks again

    ReplyDelete
  59. I believe there are many more pleasurable opportunities ahead for individuals that looked at your site.
    datascience training in chennai

    ReplyDelete




  60. It's interesting that many of the bloggers to helped clarify a few things for me as well as giving.Most of ideas can be nice content.The people to give them a good shake to get your point and across the command.

    Php course in chennai

    ReplyDelete
  61. this is a very helpful post. it's really code.

    ReplyDelete
  62. At first, you have to download the most recent rendition of Adobe Acrobat Reader to get to the shape, and further this product encourages you to see, download, finish and print the frame. https://w9.pdffiller.com

    ReplyDelete
  63. I accept there are numerous more pleasurable open doors ahead for people that took a gander at your site.we are providing ReactJs training in Chennai.
    For more details: ReactJs training in Velachery | ReactJs training in chennai

    ReplyDelete
  64. The programmers must mention the required columns specifically in the SQL query to keep data secure and reduce resource consumption.plakatų spausdinimas

    ReplyDelete
  65. Good job! Fruitful article. I like this very much. It is very useful for my research. It shows your interest in this topic very well. I hope you will post some more information about the software. Please keep sharing!!
    Blue Prism Training in Chennai
    Blue Prism Training Chennai
    Blue Prism Training in OMR
    Blue Prism Training in TNagar
    Blue Prism Training in Annanagar
    Blue Prism Training in Porur

    ReplyDelete
  66. Thank you This code is very useful but Here’s a basic tutorial on creating pagination on php https://bit.ly/2IPvdE1

    ReplyDelete
  67. thanks for great help.

    , here i found some tutorial on Code for Insert View Update Delete In Php MySQL for more detail Click Here

    ReplyDelete
  68. thanks for great help.

    , here i found some tutorial on Code for Insert View Update Delete In Php MySQL for more detail Click Here

    ReplyDelete


  69. Just seen your Article, it amazed me and surpised me with god thoughts that eveyone will benefit from it. It is really a very informative post for all those budding entreprenuers planning to take advantage of post for business expansions. You always share such a wonderful articlewhich helps us to gain knowledge .Thanks for sharing such a wonderful article, It will be deinitely helpful and fruitful article.
    Thanks
    DedicatedHosting4u.com

    ReplyDelete
  70. Whatever we gathered information from the blogs, we should implement that in practically then only we can understand that exact thing clearly, but it’s no need to do it, because you have explained the concepts very well. It was crystal clear, keep sharing..
    Java Training in Chennai
    Java Training in Coimbatore
    Java Training in Bangalore

    ReplyDelete

^