Form data save to database and display

First need to create the table name from the PHPMyAdmin or we can create from functions.php file link

Form name field name can’t be same like database name.

<?php

if(isset($_POST['submitbtn'])){
  $custom_data = array (
    'fname' => $_POST['fname'],
    'lname' => $_POST['lname'],
  );
  $table_name = 'booking';
  $result = $wpdb->insert($table_name, $custom_data, $format=NULL);
}

if($result== 1){
  echo "<script>alert('Data saved.')</script>";
}else {
  echo "<script>alert('Data not saved.')</script>";
}

?>

<form action="" method="post">
  <label for="fname">First name:</label><br>
  <input type="text" id="fname" name="fname"><br>
  <label for="lname">Last name:</label><br>
  <input type="text" id="lname" name="lname"><br><br>
  <input type="submit" value="Submit" name="submitbtn">
</form>

<br><br>
<hr>
<?php
global $wpdb;

$result = $wpdb->get_results("Select * from booking"); 

foreach ($result as $book) { ?>
<h1><?php echo $book->fname ?></h1>
<h1><?php echo $book->lname ?></h1>
<?php } ?>

Leave a Reply

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