Showing submitted values into database into next php page - php

I'm trying to make a verify page for my reservation website but I can't show only specific data from picking the specific id.
For example, I submitted a new customer and it generated an ID = 1. Then the form will take me to another PHP page and I want it to show the name of the customer I just submitted by choosing it's specific ID (which is 1 or whatever id was generated from before).
Here's my first submit form:
<form action="menuactions/temporestoaction.php" method="post" enctype="multipart/form-data">
<label class="control-label">First Name:</label>
<input class="form-control" placeholder="John" type="text" name="first_name" required autofocus/>
<br />
<label>Last Name:</label>
<input class="form-control" placeholder="Doe" type="text" name="last_name" required/>
<button type="submit" name="submit" class="btn btn-success btn-md">Submit</button>
</form>
and this is the temporestoaction.php which will submit all the values into mysql database:
<?php
if(isset($_POST['submit'])) {
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "records";
//Form Inputs to Db
$foodid = $_POST['foodid'];
$firstname = $_POST['first_name'];
$lastname = $_POST['last_name'];
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO `temporesto` ( first_name, last_name)
VALUES ( '$firstname', '$lastname')";
if (mysqli_query($conn, $sql)) {
header('Location: ../temporesto.php?id='.$row['food_id'].'');
exit();
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
?>
Which will then redirect to a new PHP page, the temporesto.php:
<?php
include 'menuactions/temporestopick.php';
while($row = mysqli_fetch_array($data, MYSQLI_ASSOC)){
?>
<input type='hidden' value=" <?php echo $_GET['food_id'];?>" name="iduse">
<label class="control-label">First Name: <h2><?php echo $row['first_name'];?></h2></label>
<input class="form-control" type="text" name="first_name" />
<br />
<label class="control-label">Last Name: <h2><?php echo $row['last_name'];?></h2></label>
<?php
}
?>
The problem I have with this is that it shows all of the values submitted instead of a specific one, see this image for reference.
P.S
temporestopick.php is using "SELECT * FROM temporesto";

If you are trying to display a verify page before you process form, then I don't see the need to save first into the database. You can simply post all form values from your form and they would be contained in your $_POST which is an array. You then sanitize all inputs, loop through to get all their values then display them for verification. If all is okay, you sanitize again then insert into your database.
In case you are a little lost, you can do the following.
Submit your form with the values filled to your action page.
In your action page, sanitize all received values from the form.
You can use extract($_POST); to get the values of your form fields into strings.
Display for viewing and confirmation then submit values to database after sanitizing.
Sample:
process.php
<?php
if(isset($_POST['submit']))
{
//sanitize your $_POST values
foreach($_POST as $key => $value)
{
$_POST[$key] = sanitize($value);
//You can out errors from empty fields here if you want
}
//extract $_POST values into strings
extract($_POST);
/*
If your form has something like input name="fname" when you extract you will get the value for name as $name
You can then echo Name: $fname
*/
$values = <<<EOD
Name: {$name}
Email: {$email}
EOD;
}
I hope you are able to get on with this. After this stage of verification then you can save to database to avoid you saving unwanted data into your database.

I removed the whole code inside temporestoaction.php and added this:
<html>
<body>
<?php
if(isset($_POST['submit']))
{
//Form Inputs to Db
$firstname = $_POST['first_name'];
$lastname = $_POST['last_name'];
$contact = $_POST['contact'];
$eventdate = $_POST['eventdate'];
$eventtime = $_POST['eventtime1'];
$eventhours = $_POST['eventhours1'];
$packages = $_POST['packages'];
$food = $_POST['food'];
$prices = $_POST['price-total'];
$treats = $_POST['treats'];
$chkfood = "";
$chktreats = "";
foreach($food as $chkfood1)
{
$chkfood.= $chkfood1.",";
}
foreach($treats as $chktreats1)
{
$chktreats.= $chktreats1.", ";
}
?>
<label><h2>NAME: <?php echo $firstname . " " . $lastname; ?></h2> </label>
<br/>
<label><h2>Contact: <?php echo $contact; ?></h2></label>
<br/>
<label><h2>Food: <?php echo $chkfood; ?></h2></label>
<br/>
<label><h2>Event Date: <?php echo $eventdate; ?></h2></label>
<br/>
<label><h2>Event Time: <?php echo $eventtime; ?></h2></label>
<br/>
<label><h2>Event Hours: <?php echo $eventhours; ?></h2></label>
<br/>
<label><h2>Packages: <?php echo $packages; ?></h2></label>
<br/>
<label><h2>Food: <?php echo $chkfood; ?></h2></label>
<br/>
<label><h2>Prices: <?php echo $prices; ?></h2></label>
<br/>
<label><h2>Treats: <?php echo $chktreats; ?></h2></label>
</body>
<?php
}
?>
</html>
With this code, it takes all the inputs from my submit form and transfers it into the next page for verifying.

Related

How do you trigger the next record in the PHP array via the HTML submit button?

Goal: I want to create an HTML form that displays pre-populated information from the 22 arrays from array_file.php.
First, I will go on index.php. On index.php, I will see a form with pre-populated data. I will not be able to edit the first and last name fields, but I will be able to edit the email field (if necessary).
Second, once everything looks okay, I will click the "Submit" button.
Third, if nothing is wrong (i.e., email field is populated), the "Submit" button should take me to the second record in the array.
Finally, once it has looped through all the arrays, it will provide a message, such as, "You're done!"
Current problem: My current index.php page shows all 22 pre-populated forms on one page. While I can edit and submit to the database using the individual "Submit" button, I'd rather be able to look at each pre-populated form one at a time.
Here is the code:
<?php
ob_start();
include 'array_file.php';
ob_end_clean();
?>
<?php
$i=1;
while ($i<=22){
?>
<form action="index.php" method="post">
<h2>Form</h2>
<label>First Name:</label>
<input class="input" name="first_name" type="text" value="<?php echo htmlentities($array[$i][1]) ?>" disabled><br>
<label>Last Name:</label>
<input class="input" name="last_name" type="text" value="<?php echo htmlentities($array[$i][2]) ?>" disabled><br>
<label>Email:</label>
<input class="input" name="email" type="text" value="<?php echo htmlentities($array[$i][3]) ?>"><br><br>
<input class="submit" name="submit" type="submit" value="Submit">
</form>
<?php
$i=$i+1;
}
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['submit'])){
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = mysqli_real_escape_string($conn,$_POST['email']);
if($email !=''){
//Insert Query of SQL
mysqli_query(#conn,"INSERT into form(form_first_name, form_last_name, form_email) values ('$first_name', '$last_name', '$email')");
echo "<br/><br/><span>Data inserted successfully!</span>";
}
else{
echo "<p>Insertion Failed <br/> Some required fields are blank!</p>";
}
}
$mysqli->close(); // Closing Connection with Server
?>
Let me know if you need me to provide any more information. Thank you in advance!
I hope this code is what you need.
<?php
ob_start();
include 'array_file.php';
ob_end_clean();
if(isset($_POST['submit']) and isset($_POST[email])){
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = mysqli_real_escape_string($conn,$_POST['email']);
if($email !=''){
//Insert Query of SQL
mysqli_query(#conn,"INSERT into form(form_first_name, form_last_name, form_email) values ('$first_name', '$last_name', '$email')");
echo "<br/><br/><span>Data inserted successfully!</span>";
}
}
/// find which form will be published
if( isset($_SESSION["form"]) and $_SESSION["form"]<22){
$form=$_SESSION["form"]+1;
$_SESSION["form"]=$form;
}else{
$form=1;
$_SESSION["form"]=$form;
}
// determine which is the next form number
if($form<22){ $nextForm=$form+1; }else{ $nextForm="??"; }
<!-- form area !-->
<form action="index.php?form=<?php echo $nextForm; ?>" method="post">
<h2>Form</h2>
<label>First Name:</label>
<input class="input" name="first_name" type="text" value="<?php echo htmlentities($array[$form][1]) ?>" disabled><br>
<label>Last Name:</label>
<input class="input" name="last_name" type="text" value="<?php echo htmlentities($array[$form][2]) ?>" disabled><br>
<label>Email:</label>
<input class="input" name="email" type="text" value="<?php echo htmlentities($array[$form][3]) ?>"><br><br>
<input class="submit" name="submit" type="submit" value="Submit">
</form>

Have a Insert and a Edit button in the same form using PHP and SQL

I've been going at this for a couple of hours now (searching here and google) but nothing I find helped me to get this to work.
I'm trying to make one form and have a Insert INTO and UPDATE $table SET function in the same form, using buttons.
But whatever I try the Update doesn't copy the data from the form. INSERT INTO works. But when I try to edit the form, no data is copied.
HTML:
<form id="contact-form" method="post" action="cms_data.php" role="form">
<div class="col-sm-12">
<h2>id</h2>
<input name="id" type="text" placeholder="<?php echo $id;?>" value="1">
</div>
<div class="col-sm-12">
<h2>Omschrijving</h2>
<textarea name="omschrijving" type="text" style="height:220px;width:100%;resize:none;"><?php echo $omschrijving;?></textarea>
</div>
<div class="col-sm-12">
<h2>Datum</h2>
<input name="datum" type="text" value="<?php echo $datum;?>">
</div>
<div class="col-sm-12">
<h2>Tijd</h2>
<input name="tijd" type="text" value="<?php echo $tijd;?>">
</div>
<div class="col-sm-12">
<h2>Locatie</h2>
<input name="locatie" type="text" value="<?php echo $locatie;?>">
</div>
<div class="col-sm-12">
<h2>Dresscode</h2>
<input name="dresscode" type="text" value="<?php echo $dresscode;?>">
</div>
<div class="col-sm-12 text-right">
<input type="submit" class="btn btn-success btn-send" value="Versturen" id="sent" <?php // echo $_SESSION['disabled']; ?>>
Update
</div>
</form>
CMS_DATA.php
<?php session_start();?>
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
//echo '<div style="width:100%;background:green;color:#FFF;font-size:2rem;text-align:center;">Connected to '. $dbname. '</div>';
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$id = $_POST['id'];
$omschrijving = $_POST["omschrijving"];
$datum = $_POST["datum"];
$item = $_POST["tijd"];
$locatie = $_POST["locatie"];
$dresscode = $_POST["dresscode"];
$quote = iconv("UTF-8", "WINDOWS-1252//TRANSLIT");
$date = date('Y-m-d');
date_default_timezone_set("Europe/Amsterdam");
$time = date("h:i:sa");
$sql = "INSERT INTO $table (ID, Omschrijving, Datum, Tijd, Locatie, Dresscode )
VALUES ('" .$id."','" .$omschrijving."','".$datum."',' ".$item."','".$locatie."','".$dresscode."')";
if ($conn->query($sql) === TRUE) {
echo "";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
UPDATE-CMS.php
<?php session_start();?>
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
//echo '<div style="width:100%;background:green;color:#FFF;font-size:2rem;text-align:center;">Connected to '. $dbname. '</div>';
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$id = $_POST['id'];
$omschrijving = $_POST["omschrijving"];
$datum = $_POST["datum"];
$item = $_POST["tijd"];
$locatie = $_POST["locatie"];
$dresscode = $_POST["dresscode"];
$quote = iconv("UTF-8", "WINDOWS-1252//TRANSLIT");
$date = date('Y-m-d');
date_default_timezone_set("Europe/Amsterdam");
$time = date("h:i:sa");
$sql = "UPDATE $table SET
Omschrijving = '$omschrijving', Datum = '$datum', Tijd = '$item', Locatie = '$locatie', Dresscode = '$dresscode' WHERE ID = '1'";
if ($conn->query($sql) === TRUE) {
echo "Done";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Like I said, the INSERT INTO works fine. But no data (values) are copied when using the update. I just overrides ID 1 with empty rows... I hope someone can help me... thanks in advance.
You have defined action on your form action="cms_data.php", so your button that is responsible for submitting that form works correctly, but on the other hand you've defined another button (anchor tag), that only has href (hence points to another page), so if you click on it, you won't pass any arguments with it.
My suggestion here is, as I mentioned in comment below your question, to use two buttons, both with submit property, but then handle clicking on them via JavaScript.
When you capture submitment, you can dinamically change action on your form, so your data will be passed to desired script.
Handling multiple buttons in a form:
Process a Form Submit with Multiple Submit Buttons in Javascript
Manipulating form's action property:
How to use JavaScript to change the form action
Another suggestion would be that you use prepared statements in your query, so you wouldn't be vulnerable to SQL injections (from the comments section, I see you'll only be using this locally, but this is a good practice).
Using Mysqli prepared statements:
https://stackoverflow.com/a/24989090/5018750
Echo only prints value on the screen in your respective textbox and does not assign that value to your actual field.
Instead what you can do is start the session in the start of your contact form and store those fields in session variable.
When user selects UPDATE option he will get redirected to UPDATE-CMS.php page. In UPDATE-CMS.php you can retrieve your stored session variables and assign them to your actual variables. In this way you can carry forward your old as well as new values.
anchor just links the page it will not pass data
you are trying to have submit and update button in one form
solution:
in html5 button has formaction attribute .formaction specifies page data to be transferred .so that different button can have different action page
<form id="contact-form" method="post" action="cms_data.php" role="form">
<div class="col-sm-12">
<h2>id</h2>
<input name="id" type="text" placeholder="<?php echo $id;?>" value="1">
</div>
<div class="col-sm-12">
<h2>Omschrijving</h2>
<textarea name="omschrijving" type="text" style="height:220px;width:100%;resize:none;"><?php echo $omschrijving;?></textarea>
</div>
<div class="col-sm-12">
<h2>Datum</h2>
<input name="datum" type="text" value="<?php echo $datum;?>">
</div>
<div class="col-sm-12">
<h2>Tijd</h2>
<input name="tijd" type="text" value="<?php echo $tijd;?>">
</div>
<div class="col-sm-12">
<h2>Locatie</h2>
<input name="locatie" type="text" value="<?php echo $locatie;?>">
</div>
<div class="col-sm-12">
<h2>Dresscode</h2>
<input name="dresscode" type="text" value="<?php echo $dresscode;?>">
</div>
<div class="col-sm-12 text-right">
<buttin formaction="CMS-DATA.php" type="submit" class="btn btn-success btn-send" value="Versturen" id="sent" <?php // echo $_SESSION['disabled']; ?>>
<button formaction="UPDATE-CMS.php" >Update </button>
</div>
</form>

How to update user input of a form when i am using header that links to other file?

I am writing a form using php and mysql. The main goal is to make the form
(1) detect missing field.
(2) update user input after successful submit and
(3) most importantly to avoid re-submission on reload/refresh.
I am able to manage the first and the third one but doesn't have any idea on the second one.
Here's my code (able to achieve first and third)
form1.php
<!DOCTYPE html>
<html>
<head></head>
<body>
<?php
$name = "";
$class = "";
$school = "";
if(isset($_POST["submit"])){
$name = $_POST["name"];
$class = $_POST["class"];
$school = $_POST["school"];
$output = false;
if(empty($_POST["name"]) || empty($_POST["class"]) || empty($_POST["school"])){
echo 'field cannot be empty';
$output_form = true;
}
if(!empty($_POST["name"]) && !empty($_POST["class"]) && !empty($_POST["school"])){
$hostname = "localhost";
$admin = "root";
$password = "";
$database = "testdatabase";
$dbc = mysqli_connect($hostname, $admin, $password, $database) or die("database connection error");
$insert_query = "INSERT INTO `sorty` (`name`, `class`, `school`) VALUES ('$name', '$class', '$school')";
$insert_result = mysqli_query($dbc, $insert_query) or die("error");
if($insert_result == 1)
echo "data inserted";
else
echo "insert query failed";
mysqli_close($dbc);
header('Location: form2.php');
}
}
else
$output = true;
if($output){
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
Name: <input type="text" name="name" value="<?php echo $name?>"/><br/>
Class: <input type="text" name="class" value="<?php echo $class?>"/><br/>
School: <input type="text" name="school" value="<?php echo $school?>"/><br/>
<input type="submit" value="submit" name="submit"/>
</form>
<?php
}
?>
</body>
</html>
My second file form2.php(succesful page after form submission)
<body>
Name: /*user input here*/<br/>
Class: /*user input here*/<br/>
School: /*user input here*/<br/>
As I can't access the variable $name, $class, $school of form.php I am having problem updating the user input data. So is there anyway to access the variable across file or is it not possible to do in this way.
user_name you may check this out. and read the code. i hope you will get the answer. You may add session for showing the message that the specified operation is done. thank you :)

Inserting HTML Form data into MySQL with PHP

I'm trying to make a simple message board MySQL database where you can write a review and submit it via an HTML form on one page and view all of the reviews on a separate page once you've submitted your review.
My problem is two of the fields from the HTML form are not being inserted into my MySQL database which results in my view all reviews page to be missing the Name and Title.
Link to what the "Read all Reviews" page looks like.
The code works without any issue when I tested it doing MySQL queries with just PHP but I need my HTML form to work.
HTML form:
<form action ="process.php" method = "post">
<fieldset>
<legend>Review Field</legend>
Reviewer Name: <br />
<input type="text" name "name" id = "name"><br />
Title of Review:<br />
<input type="text" name "title" id = "title"><br />
Enter your review below:
<!--Textbox start-->
<textarea name="body" id = "body" rows="10" cols="100">
</textarea>
<!--Textbox end-->
<br />
<input type="submit" name = "submit" id="submit">
<br />
</fieldset>
</form>
Code for process.php:
<?php // Create a database connection.
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "password";
$dbname = "ya_reviews";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
//Test if connection occurred.
if (mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
//Perform database query
$name = $_POST['name'];
$title = $_POST['title'];
$body = $_POST['body'];
//This function will clean the data and add slashes.
// Since I'm using the newer MySQL v. 5.7.14 I have to addslashes
$name = mysqli_real_escape_string($connection, $name);
$title = mysqli_real_escape_string($connection, $title);
$body = mysqli_real_escape_string($connection, $body);
//This should retrive HTML form data and insert into database
$query = "INSERT INTO reviews (name, title, body)
VALUES ('".$_POST["name"]."','".$_POST["title"]."','".$_POST["body"]."')";
$result = mysqli_query($connection, $query);
//Test if there was a query error
if ($result) {
//SUCCESS
header('Location: activity.php');
} else {
//FAILURE
die("Database query failed. " . mysqli_error($connection));
//last bit is for me, delete when done
}
mysqli_close($connection);
?>
View all Reviews:
<?php
//This will fetch the data from the database
$query = "SELECT * FROM reviews";
$result = mysqli_query($connection, $query);
//Test if there was a query error
if (!$result) {
die("Database query failed.");
}
// This will let me display the data.
// The loop will be spilt so I can format with HTML
while ($row = mysqli_fetch_assoc($result)) {
//output data from each row
?>
Name: <?php echo $row["name"] . "<br />"; ?>
Title: <?php echo $row["title"] . "<br />"; ?>
Review: <?php echo $row["body"] . "<br />";
echo "<hr>"; ?>
<?php
} ?>
Note: I connected to the database with the same code seen in process.php before the above code, I excluded it to save space.
Your HTML attribute syntax is incorrect. Its missing = sign between attribute and value.
Change name "name" to name="name" and name "title" to name="title"
<input type="text" name="name" id = "name"><br />
Title of Review:<br />
<input type="text" name="title" id = "title"><br />
Also during insert you aren't using escaped values.
Use $name instead of $_POST["name"] in insert query. Same goes for title and body values.
The problem is that the name attribute is not correct in HTML.
<input type="text" name="name" id = "name"><br />
<input type="text" name="title" id = "title"><br />
I think you messed up with syntax of HTML
<form action ="process.php" method = "post">
<fieldset>
<legend>Review Field</legend>
Reviewer Name: <br />
<input type="text" name="name" id = "name"><br />
Title of Review:<br />
<input type="text" name="title" id = "title"><br />
Enter your review below:
<!--Textbox start-->
<textarea name="body" id = "body" rows="10" cols="100">
</textarea>
<!--Textbox end-->
<br />
<input type="submit" name = "submit" id="submit">
<br />
</fieldset>
</form>
It will work surely!
Yo, you're just missing some syntax, therefore creating errors when it comes to gathering the data from those elements,
<input type="text" name "title" id = "title">
You're missing the "=" sign from the name parameter

Insert data mysqli and php in form 1 and return to new form 2

Hi all I am new to mysqli and php (currently studying and trying to work on a test database- I have not used security measures at this wont be available public) and trying to get the information I have just submitted in the form to display in a new form which will then receive further user input then submitted to database. Here is an example of what I have done so far:
Form 1 (customer table - cust id =primary key)
Customer Details ie name address telephone etc
dynamic drop down box - consists of 4 options.( would like whatever option is selected here to return a particular form)
The form is currently submitting correctly in the database, but I would like once it has submitted to the database to return the customer info (including the customer id as that is the relationship in the new table) and on the form2(service table - service id is primary key) so the user can input further data to the form and submit.
Hope this makes sense, any help would be appreciated.
Thanks
Response 1
Thank you for my response I probably havent made myself very clear.
Form 1 where dynamic dropdown list is - when user submits forms I would like it to return form 2 with the customer info we inserted in form 1
Form 1
<!doctype html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>test</title>
</head>
<body>
<form action="newbookingcode.php" method="post">
<p>First Name: <input type="text" name="firstname"/>
Last Name: <input type="text" name="lastname"/></p>
<p>Business Name: <input type="text" name="businessname"/></p>
<p>Contact Number: <input type="text" name="number"/>
Alt Number: <input type="text" name="altno"></p>
<p>Email Address:<input type="text" name="email"></p>
<p>Street No:<input tyep="text" name="streetno">
Street Name:<input type="text" name="street"></p>
<p>Suburb:<input type="text" name="suburb">
Postal Code:<input type="text" name="postalcode">
State: <input type="text" name="state"></p>
**<p>Type of Service Required: <select id="category" name="category" >
<option value="nill">---Select Service---</option**
<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM serviceType";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<option value= "'.$row['jobType'].'" >' . $row['jobType'] . '</option>';
}
} else {
echo "0 results";
}
$conn->close();
?>
</p>
</select>
<p>
<input type="submit"/>
</p>
</form>
</body>
</html>
Query in separate file
$fname=$_POST['firstname'];
$lname=$_POST['lastname'];
$bname=$_POST['businessname'];
$phone=$_POST['number'];
$altphone=$_POST['altno'];
$email=$_POST['email'];
$streetno=$_POST['streetno'];
$street=$_POST['street'];
$suburb=$_POST['suburb'];
$postcode=$_POST['postalcode'];
$state=$_POST['state'];
$service=$_POST['category'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO customer (contactFirstName,contactLastName,businessName,contactNumber,altNumber,email,streetNo,streetName,suburb,postalCode,state,serviceType)
VALUES ('$fname','$lname','$bname','$phone','$altphone','$email','$streetno','$street','$suburb','$postcode','$state','$service')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Check this code and let me know if you have any questions:
<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM serviceType";
$result = $conn->query($sql);
/************** IMPORTANT *************/
$whichForm = 1;//to know which form to show
$last_customer_id = 0;//to store last customer id
//to store your customer information
$fname=$lname=$bname=$phone=$altphone=$email=$streetno=$street=$suburb=$postcode=$state=$service='';
//To handle post operations after clicking on post.
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$whichForm = 2; // to show second form
//if it is first form
if($_POST['action'] == 'firstForm')
{
$fname=$_POST['firstname'];
$lname=$_POST['lastname'];
$bname=$_POST['businessname'];
$phone=$_POST['number'];
$altphone=$_POST['altno'];
$email=$_POST['email'];
$streetno=$_POST['streetno'];
$street=$_POST['street'];
$suburb=$_POST['suburb'];
$postcode=$_POST['postalcode'];
$state=$_POST['state'];
$service=$_POST['category'];
//Preparing your insert query
$sql = "INSERT INTO customer (contactFirstName,contactLastName,businessName,contactNumber,altNumber,email,streetNo,streetName,suburb,postalCode,state,serviceType) VALUES ('$fname','$lname','$bname','$phone','$altphone','$email','$streetno','$street','$suburb','$postcode','$state','$service')";
$conn->query($sql); //insert into db
//get last insert customer id and you already have your customer information
//in the variables above $fname, $lname.....etc
$last_customer_id = $conn->insert_id;
}
else{//do something with your second form
//get last customer info
$sql = "SELECT * FROM serviceType where id = ".$POST_['last_customer_id']."";
$result = $conn->query($sql);
$res = $result->fetch_assoc();
//you can access customer information like res['contactFirstName']
}
}
$conn->close(); //close your connection
?>
<!doctype html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>test</title>
</head>
<body>
<?php
if($whichForm == 1){ //if it is first form
?>
<form id="1" action="test2.php" method="post">
<!-- This input is needed to identify which form -->
<input type="hidden" name="action" value="firstForm" />
<p>First Name: <input type="text" name="firstname" value="<?php echo $fname; ?>"/>
Last Name: <input type="text" name="lastname" value="<?php echo $lname; ?>" /></p>
<p>Business Name: <input type="text" name="businessname" value="<?php echo $bname; ?>"/></p>
<p>Contact Number: <input type="text" name="number" value="<?php echo $phone; ?>"/>
Alt Number: <input type="text" name="altno" value="<?php echo $altphone; ?>"></p>
<p>Email Address:<input type="text" name="email" value="<?php echo $email; ?>"></p>
<p>Street No:<input tyep="text" name="streetno" value="<?php echo $streetno; ?>">
Street Name:<input type="text" name="street" value="<?php echo $street; ?>"></p>
<p>Suburb:<input type="text" name="suburb" value="<?php echo $suburb; ?>">
Postal Code:<input type="text" name="postalcode" value="<?php echo $postcode; ?>">
State: <input type="text" name="state" value="<?php echo $state; ?>"></p>
**<p>Type of Service Required: <select id="category" name="category" >
<option value="nill">---Select Service---</option>
<?php
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//this if to save the value of the selected category
if($row['jobType'] == $service)
{
echo '<option value= "'.$row['jobType'].'" SELECTED>' . $row['jobType'] . '</option>';
}
else
{
echo '<option value= "'.$row['jobType'].'">' . $row['jobType'] . '</option>';
}
}
}
?>
</select></p>
<button type="submit">Submit</button>
</form>
<?php
}//ending bracket for if($whichForm == 1)
else if($whichForm == 2){ // or just else will do fine
?>
<form id="2" action="test2.php" method="post">
<!-- This input is needed to identify which form -->
<input type="hidden" name="action" value="secondForm" />
<!-- This input is needed to store the last customer id -->
<input type="hidden" name="last_customer_id" value="<?php echo $last_customer_id; ?>" />
<!-- here you put your second form -->
<button type="submit">Submit</button>
</form>
<?php
}//ending bracket for else if($whichForm == 2)
?>
</body>
</html>
Assuming you are using a database object like mysqli to do DB interactions.
Say form1 generate insert query $insertQyery.
And you are executing this query (insert statement) like
$mysqli->query($insertQyery);
After the execution of this insert statement you can use
$customerId = $mysqli->insert_id
Now using this $customerId you can show records details on form2 or use this $customerId as reference on form2.
After customer submit FORM #1
on the next page
let's get the last customer details :-
<?php
//after mysqli connection
$contactFirstName = '';
$contactLastName = '';
$businessName = '';
$sql_get_data = "SELECT * FROM customer ORDER BY customerID DESC limit 1 ";
$query_get_data = mysqli_query($conn, $sql_get_data);
while ($row = mysqli_fetch_array($query_get_data, MYSQLI_ASSOC)) {
//specify which data you want to get from "customer" table
$contactFirstName = $row['contactFirstName'];
$contactLastName = $row['contactLastName'];
$businessName = $row['businessName'];
}
?>
HTML Form#2 :-
<form id="form2" method="post">
<input type="text" value="<?php echo 'contactFirstName'; ?>"
<input type="text" value="<?php echo 'contactLastName'; ?>"
<input type="text" value="<?php echo 'businessName'; ?>"
</form>
Hope this answer will help you.

Categories