PHP form submission for multiple entry - php

How can I keep the current form with clear fields after successful insertion. I have used to php files, one for connecting the database and another for collecting data from user. Both of the files code are given below:
For connecting database:
<?php
$servername = "localhost";
$username = "local";
$password = "host";
$dbname = "form";
$conn = mysqli_connect($servername,$username,$password,$dbname);
if(!$conn){
die("Connection failed: ".mysqli_connect_error());
}
$roll=$_POST['roll'];
$name=$_POST['name'];
$city=$_POST['city'];
$sql = "insert into people_info (roll,name,city) values ('$roll','$name','$city')";
if(mysqli_query($conn,$sql)){
echo "New record created successflly";
}
else{
echo "Error: ".$sql."<br>".mysqli_error($conn);
}
mysqli_close($conn);
?>
And the form page is:
<html>
<body>
<form action="connection.php" method="post">
<table border="1">
<tr>
<th>
Field
</th>
<th>
Value
</th>
</tr>
<tr>
<td>
Roll:
</td>
<td>
<input type="text" name="roll"/><br>
</td>
</tr>
<tr>
<td>
Name:
</td>
<td>
<input type="text" name="name"/><br>
</td>
</tr>
<tr>
<td>
City:
</td>
<td>
<input type="text" name="city"/><br>
</td>
</tr>
<tr>
<td>
<input type="submit"/>
</td>
</tr>
</table>
</form>
</body>
</html>

Instead of this:
if(mysqli_query($conn,$sql)){
echo "New record created successfully";
}
else{
echo "Error: ".$sql."<br>".mysqli_error($conn);
}
try
if(mysqli_query($conn,$sql)){
header('location: page1.php?message=New record created successfully');
}
else{
header('location: page1.php?message=' . mysqli_error($conn));
}
here header() function will redirect you to form page with $message variable having response message. Use it to show the response on page.

Related

How can i insert html table data into sql database using php?

This is my table html code. I tried sending the data using the normal insert but it only sends the last row data. I don't know how to send the full data . Can someone please help me with this.
<form action="admin_schedule_employee.php" id="schedule_employee" method="post" >
<input type="date" class="input-sm" name="scheduledate" style="margin:10px;">
<table class="table-responsive table table striped table-bordered">
<thead>
<tr>
<th style="width:20%">Employee First Name</th>
<th style="width:20%">Employee ID</th>
<th style="width:20%">Start Time</th>
<th style="width:20%">End Time</th>
</tr>
<?php while($row = mysqli_fetch_array($search_result)): ?>
<tr>
<td><input disabled name="employeename" type="text" value="<?php echo $row['fname']; ?>"></input></td>
<td><input disabled name="employeeid" type="number" value="<?php echo $row['employee_id']; ?>"></input></td>
<td><input name="starttime" type="time"></td>
<td><input name="endtime" type="time"></td>
</tr>
<?php endwhile; ?>
</thead>
<tbody>
</tbody>
</table>
<input type="submit" name="Schedule" value="Schedule">
</form>[This is how my table look like i want to send the whole data to sql database using php][1]
To start with, you will need to create multiple pages:
form.php
process.php
done.php
Creating your user form is simple, place the table in form tags like you have done above, here is an example. Save this page as form.php
<form id="new record" action="process.php" method="POST">
<table width="500px">
<tr>
<td width="50%">
<input type="text" name="fname" id="fname">
</td>
<td width="50%">
<input type="text" name="lname" id="lname">
</td>
</tr>
<tr>
<td width="50%">
</td>
<td width="50%">
<input type="submit" value="Add Record">
</td>
</tr>
</table>
</form>
Next, you will need to create a page which can process this data, and add it to your mysql database. For the following example, I have omitted my database details and substituted them, but you should add your own.
For this example, imagine my database has a table with only an fname and an lname column.
<meta http-equiv="refresh" content="0; url=/done.php" />
<?php
$servername = "your_server_name";
$username = "mysql_username";
$password = 'mysql_password';
$dbname = "database_name";
$fname = $_GET['fname'];
$lname = $_GET['lname'];
try {
$conn = new PDO("mysql:host=$servername; dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO online (fname, lname)
VALUES ('$fname', '$lname')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record inserted";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
Hopefully, that will work to insert the record. Now we need a table on the done.php page which can display all the records in the database. Use the following code:
<html lang="en">
<head>
<meta http-equiv="refresh" content="5; url=/done.php" />
<meta charset="utf-8" />
<title></title>
</head>
<body>
<?php
$servername = "your_server_name";
$username = "mysql_username";
$password = 'mysql_password';
$dbname = "database_name";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * from table_name";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo $row["fname"]. ": ";
echo $row["lname"]. "<br /><br />";
}
} else {
echo "No messages";
}
mysqli_close($conn);
?>
</body>
</html>
Hopefully this will work for you.

Empty SQL after form submission

I've searched and searched I cannot find an answer to this
I've made a form HERE It's very basic. Somehow it's not submitting the final data. the code is
<form class="form" action="submit.php" method="post">
<table>
<tr>
<td>Team Name: </td>
<td><input type="text" name="team"></td>
</tr>
<tr>
<td>Captains xbox tag: </td>
<td><input type="text" name="cap"></td>
<tr>
<td>Captains E-mail:</td>
<td><input type="text" name="email"></td>
</tr>
<tr>
<td>Team Mates: </td>
<td><TEXTAREA name="teammates" rows="6" cols="50">
Please place each team member on a new line
</TEXTAREA><br></td>
</tr>
<tr>
<td>Sub team mates: </td>
<td><TEXTAREA name="subs" rows="2" cols="50"></TEXTAREA></td>
</tr>
</table>
<p><input type="submit"></p>
</form>
That's the form
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO tournament1 (team, teammates, cap, email, subs)
VALUES ('$_POST[team]','$_POST[cap]','$_POST[email]','$_POST[teammates]','$_POST[subs]')";
if ($conn->query($sql) === TRUE) {
echo "Your team has been submitted Thankyou. You will be redirected back to the tournaments page Shortly";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
What am I doing wrong? It will connect and do something because the ID fills because of its autoincremented. everything else gets lost.
Thanks in advance guys
Kyle
So I switched it around a little for you but this should work fine..
firstly the form, I have added an isset in for you:
<form class="form" action="submit.php" method="post">
<table>
<tr>
<td>Team Name: </td>
<td><input type="text" name="team"></td>
</tr>
<tr>
<td>Captains xbox tag: </td>
<td><input type="text" name="cap"></td>
<tr>
<td>Captains E-mail:</td>
<td><input type="text" name="email"></td>
</tr>
<tr>
<td>Team Mates: </td>
<td><TEXTAREA name="teammates" rows="6" cols="50">
Please place each team member on a new line
</TEXTAREA><br></td>
</tr>
<tr>
<td>Sub team mates: </td>
<td><TEXTAREA name="subs" rows="2" cols="50"></TEXTAREA></td>
</tr>
</table>
<p><input type="submit" name="sendit"></p>
</form>
You'll notice I have changed action to action="" so it runs under its own page.
Followed next by the PHP of which I have added conditions into for you.
Add the PHP to submit.php
Please note: you can also add required at the end of each input field.
if (isset($_POST['sendit']))
{
$team = $_POST['team'];
$captain = $_POST['cap'];
$email = $_POST['email'];
$mates = $_POST['teammates'];
$sub = $_POST['subs'];
if (!empty($team))
{
if (!empty($captain))
{
if (!empty($email))
{
if (!empty($mates))
{
if (!empty($sub))
{
$sql = "INSERT INTO `tournament1` (team, teammates, cap, email, subs) VALUES ('$team', '$mates', '$captain', '$email', '$sub')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
} else {
echo "Please add subs..";
}
} else {
echo "Please add mates..";
}
} else {
echo "Please add captains email..";
}
} else {
echo "Please add captains name..";
}
} else {
echo "Please add team name..";
}
}

Adding Data to mySql

I have a form and trying to insert data to the mysql database. but it always jump into the error.
Same database connection working fine to view data already in the database.
Database Connection for the page stored in a separate file :
<?php
$host ="localhost";
$user = "CENSORED";
$password = "CENSORED";
$link = mysql_connect($host,$user,$password) or die("An error occurred while connecting...");
//Database Selection
$dbname="CENSORED";
mysql_select_db($dbname);
?>
HTML Form
<form action="add_admin.php" method="post">
<table>
<tr>
<td>Email Address :</td>
<td><input id="admin_email" name="admin_email" type="text" size="20"</></td>
</tr>
<tr>
<td>Name :</td>
<td><input id="admin_name" name="admin_name" type="text" size="20"</></td>
</tr>
<tr>
<td>Mobile :</td>
<td><input id="admin_mobile" name="admin_mobile" type="text" size="12"</></td>
</tr>
<tr>
<td>Address :</td>
<td><textarea id="admin_address" name="admin_address" rows="4" cols="50"/> </textarea></td>
</tr>
<td>Password :</td>
<td><input id="admin_pw" name="admin_pw" type="text" size="20"</></td>
</tr>
<td><input type="reset" value="Reset"></td>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
PHP Code
<?php
$admin_email=$_POST['admin_email'];
$admin_name=$_POST['admin_name'];
$admin_mobile=$_POST['admin_mobile'];
$admin_address=$_POST['admin_address'];
$admin_password=$_POST['admin_password'];
$sql = "INSERT INTO admin (admin_email,admin_name,admin_mobile,admin_address,admin_password) VALUES ('$admin_email','$admin_name','$admin_mobile','$admin_address','$admin_password')";
if( mysql_query($link,$sql))
{
echo "Records Added";
}
else
{
echo "ERROR";
mysql_error($link);
}
mysql_close($link);
?>
Thanks in advance.
you have to include your Database connection file which you have kept as separate file in your php file.
<?php
include("dbconnection filename.php"):// this line.
$admin_email=$_POST['admin_email'];
$admin_name=$_POST['admin_name'];
$admin_mobile=$_POST['admin_mobile'];
$admin_address=$_POST['admin_address'];
$admin_password=$_POST['admin_password'];
$sql = "INSERT INTO admin (admin_email,admin_name,admin_mobile,admin_address,admin_password) VALUES ('$admin_email','$admin_name','$admin_mobile','$admin_address','$admin_password')";
if( mysql_query($link,$sql))
{
echo "Records Added";
}
else
{
echo "ERROR";
mysql_error($link);
}
mysql_close($link);
?>
Change to this
$sql = "INSERT INTO admin (admin_email,admin_name,admin_mobile,admin_address,admin_password) VALUES ('".$admin_email."','".$admin_name."','".$admin_mobile."','".$admin_address."','".$admin_password."')";
use mysql_real_escape_string
$admin_email=mysql_real_escape_string($_POST['admin_email']);
$admin_name=mysql_real_escape_string($_POST['admin_name']);
$admin_mobile=mysql_real_escape_string($_POST['admin_mobile']);
$admin_address=mysql_real_escape_string($_POST['admin_address']);
$admin_password=mysql_real_escape_string($_POST['admin_password']);
You have problems with connecting to a database. I don't like your approach to of connecting to a database so i'll provide mine approach (which works so far).
Your database config should look like
class DataBaseClass{
public $_host = "localhost";
public $_user = "X32284679";
public $_database = "X32284679";
public $_pass = "X32284679";
function connectToDatabase(){
$conn = new mysqli($this->_host, $this->_user, $this->_pass, $this->_database);
$conn->set_charset("utf8");
return $conn;
if(! $conn) {
echo "Problems with connecting to database!";
exit;
}
}
}
Later on in some other code you use this file like this
require('nameOfFile.php');
$db = new DataBaseClass();
$mysqli=$db->connectToDatabase();
$sql = "INSERT INTO admin (admin_email,admin_name,admin_mobile,admin_address,admin_password) VALUES ('$admin_email','$admin_name','$admin_mobile','$admin_address','$admin_password')";
if($rs = $mysqli->query($sql)) {
//inserted
else {
//not inserted
$mysqli->close();
}
And so on, try this approach and see if it helps you.
In your PHP page you should include your connection file:
require_once('yourdbconnection.php');
And change $_POST['admin_password'] to $_POST['admin_pw'] according to your HTML.
HTML
<form action="add_admin.php" method="post">
<table>
<tr>
<td>Email Address :</td>
<td><input id="admin_email" name="admin_email" type="text" size="20"></td>
</tr>
<tr>
<td>Name :</td>
<td><input id="admin_name" name="admin_name" type="text" size="20"></td>
</tr>
<tr>
<td>Mobile :</td>
<td><input id="admin_mobile" name="admin_mobile" type="text" size="12"></td>
</tr>
<tr>
<td>Address :</td>
<td><textarea id="admin_address" name="admin_address" rows="4" cols="50"> </textarea></td>
</tr>
<td>Password :</td>
<td><input id="admin_pw" name="admin_pw" type="text" size="20"></td>
</tr>
<td><input type="reset" value="Reset"></td>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
PHP
<?php
require_once('yourdbconnection.php');
$admin_email=$_POST['admin_email'];
$admin_name=$_POST['admin_name'];
$admin_mobile=$_POST['admin_mobile'];
$admin_address=$_POST['admin_address'];
$admin_password=$_POST['admin_pw'];
$sql = "INSERT INTO admin (admin_email,admin_name,admin_mobile,admin_address,admin_password) VALUES ('$admin_email','$admin_name','$admin_mobile','$admin_address','$admin_password')";
mysqli_query($link, $sql) or die("Error: " . mysqli_error($link));
mysqli_close($link);
?>
This works for me. If it doesn't for you then:
Check if query columns match table columns
Check if you are using the right database and the right table
Check if you are checking result on the right database and the right table
Hope this helps!
EDIT
NOTE: I highly suggest you to switch from mysql to mysqli since mysql is now deprecated.
As you asked me to help out in one of my previous answers i decided to do some fancy stuff with this code :)
Remember, the db rows need to be named the same as your form name="name" for this to work!
db_connect.php:
$dbhost = ""; // this will ususally be 'localhost', but can sometimes differ
$dbname = ""; // the name of the database that you are going to use for this project
$dbuser = ""; // the username that you created, or were given, to access your database
$dbpass = ""; // the password that you created, or were given, to access your database
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die('An error occured while connecting to: '. $dbhost.' as: '.$dbuser);
mysql_select_db($dbname, $conn) or die('Sorry, an error occured when selecting the database: '.$dbname);
form.php:
<form action="add_admin.php" method="post">
<table>
<tr>
<td>Email Address :</td>
<td><input id="admin_email" name="admin_email" type="text" size="20"</></td>
</tr>
<tr>
<td>Name :</td>
<td><input id="admin_name" name="admin_name" type="text" size="20"</></td>
</tr>
<tr>
<td>Mobile :</td>
<td><input id="admin_mobile" name="admin_mobile" type="text" size="12"</></td>
</tr>
<tr>
<td>Address :</td>
<td><textarea id="admin_address" name="admin_address" rows="4" cols="50"/> </textarea></td>
</tr>
<td>Password :</td>
<td><input id="admin_pw" name="admin_pw" type="text" size="20"</></td>
</tr>
<td><input type="reset" value="Reset"></td>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
add_admin.php:
include 'db_connect.php'; //include connection
//Why add all post thingys when you can do it dynamically ?
$i = count($_POST);
$e = 0;
//Do a foreach loop on all POSTS coming in to this file..
foreach($_POST as $Key => $Value){
//Add commas behind everything :)
if($e++ < $i - 1){
//Escaping all the strings:
$Rows .= mysql_real_escape_string($Key).", ";
$Values .= "'".mysql_real_escape_string($Value)."', ";
}
//if its the last one, dont add a comma behind!
else{
//Still escaping all the strings:
$Rows .= mysql_real_escape_string($Key);
$Values .= "'".mysql_real_escape_string($Value)."'";
}
}//end foreach loop
//Insert etc etc...
$sql = mysql_query("INSERT INTO admin($Rows) VALUES($Values)");
//If successful:
if(mysql_query($conn, $sql)){
echo "Records added.";
}
//Error ?
else{
echo "Sorry, an error occured while inserting to: ".$Rows;
echo "<br/>";
mysql_error($conn);
}
//Close connection:
mysql_close($conn);

Post Data from One PHP File to Another Gives Error

I have two php files, one file submits data to a second file for an update action into mysql database.
below is the code for the file that submits data
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="test"; // Database name
$tbl_name="test_mysql"; // Table name
$server_name="localhost";
// Create connection
$con = new mysqli($server_name, $username, $password, $db_name , 3306);
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
// get value of id that sent from address bar
$id=$_GET['id'];
// Retrieve data from database
$sql="SELECT * FROM $tbl_name WHERE id='$id'";
$result = $con->query($sql);
$rows = $result->fetch_assoc();
?>
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<form name="form1" method="post" action="update_ac.php">
<td>
<table width="100%" border="0" cellspacing="1" cellpadding="0">
<tr>
<td> </td>
<td colspan="3"><strong>Update data in mysql</strong> </td>
</tr>
<tr>
<td align="center"> </td>
<td align="center"> </td>
<td align="center"> </td>
<td align="center"> </td>
</tr>
<tr>
<td align="center"> </td>
<td align="center"><strong>Name</strong></td>
<td align="center"><strong>Lastname</strong></td>
<td align="center"><strong>Email</strong></td>
</tr>
<tr>
<td> </td>
<td align="center">
<input name="name" type="text" id="name" value="<?php echo $rows['name']; ?>">
</td>
<td align="center">
<input name="lastname" type="text" id="lastname" value="<?php echo $rows['lastname']; ?>" size="15">
</td>
<td>
<input name="email" type="text" id="email" value="<?php echo $rows['email']; ?>" size="15">
</td>
</tr>
<tr>
<td> </td>
<td>
<input name="id" type="hidden" id="id" value="<?php echo $rows['id']; ?>">
</td>
<td align="center">
<input type="submit" name="Submit" value="Submit">
</td>
<td> </td>
</tr>
</table>
</td>
</form>
</tr>
</table>
<?php
// close connection
$con->close();
?>
the second file for the update action is presented below
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="test"; // Database name
$tbl_name="test_mysql"; // Table name
$server_name="localhost";
// Create connection
$con = new mysqli($server_name, $username, $password, $db_name , 3306);
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
// update data in mysql database
$sql="UPDATE $tbl_name SET name='$name', lastname='$lastname', email='$email' WHERE id='$id'";
$result=$con->query($sql);
// if successfully updated.
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='list_records.php'>View result</a>";
}
else {
echo "ERROR";
}
?>
the error page is presented below.
An suggestions to fix the problem
Well you haven't set those values yet that's why it's getting an error.
First you must wrap your second file to check if it has submitted the form. Then set those variables inside.
<?php
if(isset($_POST['Submit'])) {
$name = $_POST['name'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$id = $_POST['id'];
// rest of your code goes here
}
Make changes to your second file as
<?php
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$id = $_POST['id'];
// add you rest of code
}
You should define some variables before line
$sql="UPDATE $tbl_name SET name='$name', lastname='$lastname', email='$email' WHERE id='$id'";
For example
$tbl_name = 'mytable';
$name = 'ABC';
$lastname = 'XYZ';
$email = 'abc#example.com';
$sql="UPDATE $tbl_name SET name='$name', lastname='$lastname', email='$email' WHERE id='$id'";
User this at top of your request page.
$name=$_POST['name'];
$lastname=$_POST['lastname'];
$email=$_POST['email'];
$id=$_POST['id'];
In your second file where you write sql query to update data,
You are using :-
undefine variable
name, lastname, email, id
get posted value in these variable like that, before sql query:-
$name= $_POST['name'];
$lastname= $_POST['lastname'];

SQL form run from include not working in firefox/safari

**
This is the code for one of several forms saved as php includes for use on the same admin page. They work individually in all browsers but do not work in safari or firefox from the admin page. Any Thoughts?
Thanks for your help!
(I know I need to switch over to prepared statements) **
<?php
$servername = "1.1.1.1:111";
$username = "root";
$password = "root";
$dbname = "sit";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$result = mysqli_query($conn, "SELECT * FROM `calltoaction` ");
$values = mysqli_fetch_array($result);
$calltoaction_title = $_POST['calltoaction_title'];
$calltoaction_content = $_POST['calltoaction_content'];
if(isset($_POST['calltoaction_title'])){
$calltoaction= "UPDATE calltoaction SET calltoaction_title='$calltoaction_title' ,calltoaction_content='$calltoaction_content' WHERE calltoaction_id='1'";
if (mysqli_query($conn, $calltoaction)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
}
?>
<form id="comment_form" method="post" action="<?php $calltoaction?>" onsubmit="setTimeout(function () { window.location.reload(); }, 10), location.reload(true);">
<table width="100%" border="0" cellspacing="1" cellpadding="2">
<tr>
<td width="85%">About Us Title</td>
</tr>
<tr>
<td><input class="commentarea" name="calltoaction_title" type="text" id="calltoaction_title"value="<?php echo $values['calltoaction_title']?>"></td>
</tr>
<tr>
<td width="85%" >Testimonial</td>
</tr>
<tr>
<td width="85%" >About Us Content</td>
</tr>
<tr>
<td><pre><textarea class="commentarea" name="calltoaction_content" type="text" id="calltoaction_content" rows= "10" ><?php echo $values['calltoaction_content']?></textarea></pre></td>
</tr>
<tr>
<td>
<input type="submit" value="Update">
</td>
</tr>
</table>
</form>
<?php mysqli_close($conn); ?>

Categories