Submitting HTML form to PHP file - php

I have created two files on remote server. One is html form which asks to enter some fields and another is a php file which will get all the data and insert into the database.
For this from html file on click of submit button I am calling php file, but the file is not getting execute I think because when I click on submit it again reloads the same html page.
html :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>MCQ Questions</title>
</head>
<body>
<form method="post" >
<p> Enter the question :</p> <input name="question" type="input"> <br><br>
<p> Enter options :</p>
Enter option 1 : <input name="opt1" type="input"> <br><br>
Enter option 2 : <input name="opt2" type="input"> <br><br>
Enter option 3 : <input name="opt3" type="input"> <br><br>
Enter option 4 : <input name="opt4" type="input"> <br><br>
<p> Enter correct answer :</p>
<input name="ans" type="input"> <br><br>
<input type="submit" value = "Submit" onClick = "uploadQuestion.php">
</form>
</body>
</html>
php file:
<?php
$question=$_POST['question'];
$option1=$_POST['opt1'];
$option2=$_POST['opt2'];
$option3=$_POST['opt3'];
$option4=$_POST['opt4'];
$ans=$_POST['ans'];
$db_server = mysql_connect("address","username","pass");
if(!$db_server) {
die("Database connection failed: " . mysql_error());
}else{
$db_select = mysql_select_db("mlm",$db_server);
if (!$db_select) {
die("Database selection failed:: " . mysql_error());
}
}
$sql = "INSERT INTO questions (question,answer_a,answer_b,answer_c,answer_d,answer) VALUES ('$question','$option1',$option2,$option3,$option4,$ans)";
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
?>
I also tried this way :
<input type="submit" value = "Submit" onClick = "http://address/uploadQuestion.php">
But nothing is working. Whats going wrong here? I am a beginner in web development,, can anyone help please? Thank you..
EDIT :
$database = new Database('addredd','username','pass','handbook');
$dbConnection = $database->getDB();
$stmt = $dbConnection->prepare("insert into questions(question,answer_a,answer_b,answer_c,answer_d,answer) values(?,?,?,?,?,?)");
$stmt->execute(array($question,$option1,$option2,$option3,$option4,$ans));
I tried to use pdo statement but getting this error :
Fatal error: Class 'Database' not found in /var/www/html/uploadQuestion.php on line 12
EDIT2 :
I am trying to upload one file on server and want to save it in database also, so for this I have created 2 files one is index.php and another is uploadFile.php.
As you shown now I used pdo for this but when I click on upload image again same page is getting load.
index.php
<form action="index.php" method="post" enctype="multipart/form-data">
<p> Select image to upload:</p>
<input name = "file" type="file" id="fileToUpload"><br><br>
Enter chapter name :
<input name = "chapterName" type = "text"><br><br>
<input type="submit" value = "Upload Image">
</form>
<?php
if (isset($_FILES['file']['tmp_name']))
{
$ch = curl_init();
$cfile = new CURLFile($_FILES['file']['tmp_name'],$_FILES['file']['type'],$_FILES['file']['name']);
$data = array("myfile" => $cfile);
curl_setopt($ch, CURLOPT_URL, "http://host/NewProject/uploadFile.php");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOTP_POSTFIELDS, $data);
$response = curl_exec($ch);
if($response == true)
{
echo "File posted";
}
else{
echo "Error: " . curl_error($ch);
}
}
?>
uploadFile.php
<?php
ini_set('display_errors', 1);
if(isset($_FILES['myfile']['tmp_name']))
{
$path = "files/" . $_FILES['myfile']['name'];
move_uploaded_file($_FILES['myfile']['tmp_name'], $path);
$chapterName=$_POST['chapterName'];
$dbh = new PDO('mysql:host=host;dbname=database_name','username', 'password');
$stmt = $dbh->prepare("INSERT INTO chapters (title,file) VALUES (?, ?)");
$stmt->execute(array($chapterName,$path));
if ($dbh->lastInsertId())
{
echo 'File upploaded.';
}
else
{
echo 'File could not upload.';
}
}
?>
Please help.. Thank you..

First repair your form, type="" can't be named input u can check here https://www.w3schools.com/tags/att_input_type.asp
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>MCQ Questions</title>
</head>
<body>
<form action="uploadQuestion.php" method="post" enctype="multipart/form-data">
<p> Enter the question :</p> <input name="question" type="text"> <br><br>
<p> Enter options :</p>
Enter option 1 : <input name="opt1" type="text"> <br><br>
Enter option 2 : <input name="opt2" type="text"> <br><br>
Enter option 3 : <input name="opt3" type="text"> <br><br>
Enter option 4 : <input name="opt4" type="text"> <br><br>
<p> Enter correct answer :</p>
<input name="ans" type="text"> <br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Then yours php code
<?php
// mysql connection
$db_server = mysql_connect("address","username","pass");
// check for mysql connection
if(!$db_server)
{
die("Database connection failed: " . mysql_error());
}
else
{
// check if database exists
$db_select = mysql_select_db("mlm",$db_server);
if (!$db_select)
{
die("Database selection failed:: " . mysql_error());
}
}
// escape post variables
$question = mysql_real_escape_string($_POST['question']);
$option1 = mysql_real_escape_string($_POST['opt1']);
$option2 = mysql_real_escape_string($_POST['opt2']);
$option3 = mysql_real_escape_string($_POST['opt3']);
$option4 = mysql_real_escape_string($_POST['opt4']);
$ans = mysql_real_escape_string($_POST['ans']);
// make query
$sql = "INSERT INTO questions (question,answer_a,answer_b,answer_c,answer_d,answer) VALUES ('$question', '$option1', '$option2', '$option3', '$option4', '$ans')";
// check if query runs
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
?>
Or php with mysqli
<?php
// host, username, password, database name
$db_server = mysqli_connect("address", "username", "pass", "mlm");
// check for connection
if(!$db_server)
{
die("Database connection failed: " . mysqli_error($db_server));
}
// escape post variables
$question = mysqli_real_escape_string($db_server, $_POST['question']);
$option1 = mysqli_real_escape_string($db_server, $_POST['opt1']);
$option2 = mysqli_real_escape_string($db_server, $_POST['opt2']);
$option3 = mysqli_real_escape_string($db_server, $_POST['opt3']);
$option4 = mysqli_real_escape_string($db_server, $_POST['opt4']);
$ans = mysqli_real_escape_string($db_server, $_POST['ans']);
// make query
$sql = "INSERT INTO questions (question,answer_a,answer_b,answer_c,answer_d,answer) VALUES ('$question', '$option1', '$option2', '$option3', '$option4', '$ans')";
// check if query runs
if (!mysqli_query($db_server, $sql))
{
die('Error: ' . mysqli_error($db_server));
}
?>
Or php with prepared statements
<?php
// mysql connection
$dbh = new PDO('mysql:host=adress;dbname=database_name', 'username', 'password');
// escape post variables
$question = $_POST['question'];
$option1 = $_POST['opt1'];
$option2 = $_POST['opt2'];
$option3 = $_POST['opt3'];
$option4 = $_POST['opt4'];
$ans = $_POST['ans'];
$stmt = $dbh->prepare("INSERT INTO questions (question,answer_a,answer_b,answer_c,answer_d,answer) VALUES ( ?, ?, ?, ?, ?, ?)");
$stmt->execute(array($question, $option1, $option2, $option3, $option4, $ans));
if ($dbh->lastInsertId())
{
echo 'Sucess.';
}
else
{
echo 'Fail.';
}
?>

Change your from code to this
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>MCQ Questions</title>
</head>
<body>
<form action="uploadQuestion.php" method="post" enctype="multipart/form-data">
<p> Enter the question :</p> <input name="question" type="input"> <br><br>
<p> Enter options :</p>
Enter option 1 : <input name="opt1" type="input"> <br><br> Enter option 2 : <input name="opt2" type="input"> <br><br> Enter option 3 : <input name="opt3" type="input"> <br><br> Enter option 4 : <input name="opt4" type="input"> <br><br>
<p> Enter correct answer :</p>
<input name="ans" type="input"> <br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

Related

Insert images into a database

Im trying to upload an image to a mysql database, but when I upload the image I receive the message of confirmation, but when i check my database the image row is empty, what am I doing wrong?
<?php include "connection.php"; ?>
<?php
$n=$_POST["num"];
$t=$_POST["texto"];
$i=$_POST["imagem"];
$image = addslashes(file_get_contents($_FILE['$i']['tmp_name']));
if ($connect->connect_error){
die("Connection failed: " . $connect->connect_error);
}
$sql = "UPDATE servicos SET texto='$t', imagem='{$image}' where nmr=$n" ;
if ($connect->query($sql) === TRUE) {
echo "informação atualizada";
} else {
echo "Error: " . $sql . "<br>" . $connect->error;
}
$connect->close();
?>
<html>
<body>
<div class="formulario" style="width: 100%; height: 100%;">
<form enctype="multipart/form-data" name="form1" target="apresenta" method="post" action="menu2.php" style="position:absolute; top:70;left:10
border:thin; border-style:none;">
<label> Atualizar dados </label><br>
Numero: <input type="text" name="num" value=""><br>
Texto: <input type="text" name="texto" value=""><br>
Imagem: <input type="file" name="imagem" value=""><br>
<input type="submit" name="submit" value="enviar">
<input type="reset" value="limpar">
</form>
</div>
</body>
</html>
Besides all the comments stating "You shouldn't store files in tables because...", this is what works (with PHP 7):
<?php
if(isset($_POST['submit'])) {
var_dump($_FILES);
$dbh = new PDO("mysql:host=127.0.0.1;dbname=test", "root", "");
$stm = $dbh->prepare("INSERT INTO test_img (cont) VALUES (?)");
$stm->execute(array(file_get_contents($_FILES['fileinput']['tmp_name'])));
}
?>
<form method="post" enctype="multipart/form-data">
File: <input type="file" name="fileinput"><br>
<button name="submit">Upload</button>
</form>
Possible error sources:
$connect->query($sql) === TRUE should be $connect->query($sql) !== false
The entry you want to UPDATE does not exist
imagem='{$image}' is a rather "hacky" way do insert variables, use concatenation: $sql = "UPDATE servicos SET texto='".$t."', imagem='".$image."' where nmr=".$n;
Hope this helps.

Can't insert new records through PHP into mysql database

When I press the submit button I get error.
object not found error.
And the page automatically adds empty entries with auto incremented primary key (without pressing the submit button).
I am still a beginner in PHP, I searched thoroughly but I can't find out what's wrong in code.
<html>
<head>
<title>Add New Record in MySQL Database</title>
</head>
<body>
<form action="insert.php" method="post">
<p>
<label for="Name">Full Name:</label>
<input type="text" name="Name" id="Name">
</p>
<p>
<label for="Code">Code:</label>
<input type="text" name="Code" id="Code">
</p>
<p>
<label for="GPA">GPA:</label>
<input type="text" name="GPA" id="GPA">
</p>
<input type="submit" value="Submit">
</form>
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "username", "password", "students");
// Check connection
if ($link === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$full_name = filter_input(INPUT_POST, 'full_name');
$code = filter_input(INPUT_POST, 'code');
$gpa = filter_input(INPUT_POST, 'gpa');
// attempt insert query execution
$sql = "INSERT INTO info VALUES ('$full_name', '$code', '$gpa')";
if (mysqli_query($link, $sql)) {
echo "Records added successfully. $full_name";
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
</body>
</html>
Try this:
$full_name = filter_input(INPUT_POST, 'Name');
$code = filter_input(INPUT_POST, 'Code');
$gpa = filter_input(INPUT_POST, 'GPA');
The reason why I wrote that is because your input names contain Name, Code and GPA so you need to write this exactly as your input names (case-sensitive).
Do with isset(). when the submit button clicks only the code runs.
Inside the php you should use the form input name field.
<?php
if(isset($_POST['submit'])){
$link = mysqli_connect("localhost", "username", "password", "students");
if ($link === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$full_name = filter_input(INPUT_POST, 'full_name');
$code = filter_input(INPUT_POST, 'code');
$gpa = filter_input(INPUT_POST, 'gpa');
//to prevent sql injection attack
$full_name = mysqli_real_escape_string($link, $full_name);
$code = mysqli_real_escape_string($link, $code);
$gpa = mysqli_real_escape_string($link, $gpa);
// attempt insert query execution
$sql = "INSERT INTO info (Name,Code,GPA) VALUES ('$full_name', '$code', '$gpa')";
if (mysqli_query($link, $sql)) {
echo "Records added successfully. $full_name";
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
}
?>
<html>
<head>
<title>Add New Record in MySQL Database</title>
</head>
<body>
<form action="insert.php" method="post">
<p>
<label for="Name">Full Name:</label>
<input type="text" name="full_name" id="Name">
</p>
<p>
<label for="Code">Code:</label>
<input type="text" name="code" id="Code">
</p>
<p>
<label for="GPA">GPA:</label>
<input type="text" name="gpa" id="GPA">
</p>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
The problem is the input name. You named Full Name input with name="Name", but you declare $full_name = filter_input(INPUT_POST, 'full_name'); in php section. you must change full_name to Name. As well as the Code and GPA input.

PHP form, converting input field into a drop down list

The below code is a simple form that is sending the data that is inputted to my local database.
<html>
<head>
<title>!!!!!!!!!!!!!!</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="main">
<h1>Insert data into database using mysqli</h1>
<div id="login">
<h2>Student's Form</h2>
<hr/>
<form action="" method="post">
<label>Student Name :</label>
<input type="text" name="stu_name" id="name" required="required" placeholder="Please Enter Name"/><br /><br />
<label>Student Email :</label>
<input type="email" name="stu_email" id="email" required="required" placeholder="john123#gmail.com"/><br/><br />
<label>Student City :</label>
<input type="text" name="stu_city" id="school" required="required" placeholder="Please Enter Your City"/><br/><br />
<input type="submit" value=" Submit " name="submit"/><br />
</form>
</div>
<!-- Right side div -->
</div>
<?php
if(isset($_POST["submit"])){
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "Student";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO students (student_name, student_email, student_school)
VALUES ('".$_POST["stu_name"]."','".$_POST["stu_email"]."','".$_POST["stu_city"]."')";
if ($conn->query($sql) === TRUE) {
echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
} else {
echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" . $conn->error."');</script>";
}
$conn->close();
}
?>
</body>
</html>
The issue that I am finding is that I am trying to change the Student City input field into a drop down where the values is retrieve from the database and put into a drop down list for a new user to select.
Could someone advise on what needs to be done please.
i am trying to use the below code and send the below list to my database.
<option value="US">United States</option>
<option value="UK">United Kingdom</option>
<option value="France">France</option>
<option value="Mexico">Mexico</option>
but i am finding it hard to send the these values to the database with my above code as well as where to place this code.
As a rough example of how you could build the dropdown menu using data from your db this should give you the general idea perhaps.
/* store formatted menu options in temp array */
$html=array();
/* query db to find schools/cities */
$sql='select distinct `student_school` from `students` order by `student_school`';
$res=$mysqli_query( $conn, $sql );
/* process recordset and store options */
if( $res ){
while( $rs=mysqli_fetch_object( $res ) ){
$html[]="<option value='{$rs->student_school}'>{$rs->student_school}";
}
}
/* render menu */
echo "<select name='stu_city'>", implode( PHP_EOL, $html ), "</select>";
You need to refactor your code by moving the if (isset($_POST)) above the html:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "Student";
// Create connection
$conn = new mysqli ( $servername, $username, $password, $dbname );
// Check connection
if ($conn->connect_error) {
die ( "Connection failed: " . $conn->connect_error );
}
$sql = "SELECT city_name FROM cities" ;
if ($conn->query ( $sql ) === TRUE) {
$cities = ... // build the cities from the query result
} else {
$cities = '<option value="none">No cities found</option>' ;
}
if (isset ( $_POST ["submit"] )) {
$sql = "INSERT INTO students (student_name, student_email, student_school)
VALUES ('" . $_POST ["stu_name"] . "','" . $_POST ["stu_email"] . "','" . $_POST ["stu_city"] . "')";
if ($conn->query ( $sql ) === TRUE) {
echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
} else {
echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" . $conn->error . "');</script>";
}
$conn->close ();
}
?>
<html>
<head>
<title>!!!!!!!!!!!!!!</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="main">
<h1>Insert data into database using mysqli</h1>
<div id="login">
<h2>Student's Form</h2>
<hr />
<form action="" method="post">
<label>Student Name :</label> <input type="text" name="stu_name"
id="name" required="required" placeholder="Please Enter Name" /><br />
<br /> <label>Student Email :</label> <input type="email"
name="stu_email" id="email" required="required"
placeholder="john123#gmail.com" /><br />
<br /> <label>Student City :</label> <select name="stu_city" multiple><?php echo $cities; ?>
</select>><br />
<br /> <input type="submit" value=" Submit " name="submit" /><br />
</form>
</div>
<!-- Right side div -->
</div>
</body>
</html>
Use the Select tag: Lets say you hav a column in your database with Student City, like this, lets say the database field is called city
City 1
City 2
City 3
Step 1: Query the database and fetch all the Cities
$sql = "SELECT city FROM table_name";
$result = $conn->query($sql);
Then you come to your dropdown:
<select name="stu_city" id="..." required>
<?php
while($cities = $conn->fetch_array($result){
extract($cities);
echo "<option value='...'>$city</option>";
}
?>
</select>
You need to refactor your code by moving the if (isset($_POST)) above the html:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "Student";
// Create connection
$conn = new mysqli ( $servername, $username, $password, $dbname );
// Check connection
if ($conn->connect_error) {
die ( "Connection failed: " . $conn->connect_error );
}
$sql = "SELECT city_name FROM cities" ;
$result = $conn->query ( $sql );
if (isset ( $_POST ["submit"] )) {
$sql = "INSERT INTO students (student_name, student_email, student_school)
VALUES ('" . $_POST ["stu_name"] . "','" . $_POST ["stu_email"] . "','" . $_POST ["stu_city"] . "')";
if ($conn->query ( $sql ) === TRUE) {
echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
} else {
echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" . $conn->error . "');</script>";
}
$conn->close ();
}
?>
<html>
<head>
<title>!!!!!!!!!!!!!!</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="main">
<h1>Insert data into database using mysqli</h1>
<div id="login">
<h2>Student's Form</h2>
<hr />
<form action="" method="post">
<label>Student Name :</label> <input type="text" name="stu_name"
id="name" required="required" placeholder="Please Enter Name" /><br />
<br /> <label>Student Email :</label> <input type="email"
name="stu_email" id="email" required="required"
placeholder="john123#gmail.com" /><br />
<br /> <label>Student City :</label> <select name="stu_city" multiple>
<?php
if ($result == TRUE) {
while($cities = $conn->fetch_array($result)){
extract($cities);
echo "<option value=''>$city_name</option>";
}
}
else {
echo "<option value='none'>No cities found</option>";
}
?>
</select>><br />
<br /> <input type="submit" value=" Submit " name="submit" /><br />
</form>
</div>
<!-- Right side div -->
</div>
</body>
</html>

How to store input given by user in html form in sql using php

This is my PHP code.
<html><head>
<title>login.php</title>
<link rel = "stylesheet" href="login-style.css">
</head>
<body>
<div class = "container">
<div class = "message">
<?php
define('DB_NAME','mydb');
define('DB_USER','root');
define('DB_PASSWORD','');
define('DB_HOST','127.0.0.1');
$link = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);
if($link){
die('could not connect:'. mysql_error());
}
$db_selected = mysql_select_db(DB_NAME,$link);
if(!$db_selected){
die('can\'t use'.DB_NAME . ': ' . mysql_error());
}
$value1 = $_POST['name'];
$value2 = $_POST['password'];
$sql = "INSERT INTO Account (username,password) VALUES ('$value1','$value2')";
if(!mysql_query($sql))
{die('ERROR'.mysql_error());
}
mysql_close();
?>
<h1>Thank you for logging in </h1>
<form action = "form.html">
<p class ="submit">
<button type ="submit" >
GO TO FORM
</button>
</p>
</div>
</div>
</body>
</html>
I want to store the data in MySQL but when I run the html code (which i have connected to this php code using action =" name of this file"), no entry is done in database I created, can you tell me what is done wrong and help me to correct it?
<DOCTYPE! html>
<html lang = "en-US">
<head>
<meta charset = "UTF-8">
<title>Sign-In</title>
<link rel = "stylesheet" href ="style-sign.css">
<script type = "text/javascript">
function validateForm(){
var x = document.forms["forma"]["login"].value;
if(x == null || x == "")
{ alert("fill the field ");
return false;
}
var y = document.forms["forma"]["password"].value;
if( y == null || y == "")
{
alert("fill the field");
return false;
}
}
</script>
</head>
<body >
<div class="container">
<div class="login">
<h1>Login</h1>
<form name = "forma" method="post" onsubmit="return validateForm()" action = "login.php">
<p>
<input type="text" name="name" value="" placeholder="Username or Email">
</p>
<p>
<input type="password" name="password" value="" placeholder="Password">
</p>
<p class="submit">
<input type="submit" name="commit" value="Login" >
</p>
</form>
</div>
</div>
</body>
</html>
this is my html code which i have connected to this php file ,I am using xampp and using phpmyadmin , I am not getting any error and apache and mysql both are running
help me with this problem
Change the following:
$sql = "INSERT INTO Account (username,password) VALUES ('$value1','$value2')";
To:
$sql = "INSERT INTO Account (username,password) VALUES ($value1,$value2)";
EDIT:
You do not have input fields setup for the username and password. So POST will not work.
First you From needs an action and a method.
Best woould be to rename the file to form.php
<form action = "form.php" method="POST">
in the result file ...
Connect to the database
$mysqli= #new mysqli('localhost', 'fake_user', 'my_password', 'my_db');
if ($mysqli->connect_errno) {
die('Connect Error: ' . $mysqli->connect_errno);
}
escape your value strings
$query= "INSERT INTO Account (username,password) VALUES ('".$mysqli->real_escape_string($value1)."','".$mysqli->real_escape_string($value2)."')"
Execute query
$result=$mysqli->query($query);
Verify results if any or check if an Error occured
if(!$result) {
$ErrMessage = $mysqli->error . "\n";
$mysqli->close();
die( $ErrMessage) ;
}

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