I have a number of registration pages on my web application and a number of textboxes in a form that pushes the values enter to another php page which writes it to the database. The code for it looks like this
<form action = "submitEvent.php" method = "post">
Event Name: <br>
<input type = "text" name = "eventname" >
<br>
Event Type: <br>
<input type = "text" name = "eventtype" >
<br>
Charity Number: <br>
<input type = "text" name = "charityid" >
<br>
Contact Details: <br>
<input type = "text" name = "contactdetails" >
<br>
Location: <br>
<input type = "text" name = "eventlocation" >
<br>
Date : <br>
<input type ="date" name ="eventdate">
<br>
<input type = "submit" value = "Submit">
</form>
and then the submitEvent.php file looks like this
<?php
$eventname = filter_input(INPUT_POST, 'eventname');
$eventtype = filter_input(INPUT_POST, 'eventtype');
$charitynumber = filter_input(INPUT_POST, 'charityid');
$contactdetails = filter_input(INPUT_POST, 'contactdetails');
$eventlocation = filter_input(INPUT_POST, 'eventlocation');
$eventdate = filter_input(INPUT_POST, 'eventdate');
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "fyp";
//Create new connection
$conn = new mysqli($servername, $username, $password, $dbname);
//Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql = "INSERT
INTO event (eventname, eventtype, charityid, contactdetails, location, date) VALUES ('$eventname', '$eventtype', '$charitynumber', '$contactdetails', '$eventlocation', '$eventdate')";
if ($conn->query($sql) === TRUE) {
echo "New record created succesfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
?>
Is there an easier way to do this as I have a number of pages like this? Would I be able to put it into one page?
Yes, it is possible to have all this in one page. You can use isset($_POST) to check if there is data available and then process it.
But modulation (having separate files) makes it easy. It helps to debug when you have php and html codes in diff files.
You can check if the form is submitted or not and act accordingly.
To check if you the form is submitted you can check if $_POST['Submit'] is set.
<?php
if(isset($_POST['Submit'])){
/* PHP code here */
}
?>
<!-- And point the form to submit to itself. -->
<form action="thisPage.php" method="post">
<!-- Rest of form here -->
The most basic way is add a hidden field to your form and on the form page check for that in php.
HTML
<form action = "form_page.php" method = "post">
<input type="hidden" name="submitted" value="1">
.....
</form>
PHP:
<?php
if(isset($_POST["submitted"])){
/*PHP processing code goes here*/
}
?>
Related
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.
I have been working on this Login script for awhile and everything works, except this update function. I have tried changing variable name and everything else. On UpdateUser.php, the code works if I insert variables instead of the $[POST] variables. I am at a loss. Any help would be greatly appreciated. Sorry for the messy code, this is a class assignment, so I wasn't worried about password security at the moment.
This is index4.php
<form id="form" action="index4.php" method="post">
<h2>Update Your Login</h2>
UserName:<br>
<input type="text" id="useuserName" required />
<br>
Password:<br>
<input type="text" id="usepassWord" required />
<br>
First Name:<br>
<input type="text" id="usefirstName" required />
<br>
Last Name:<br>
<input type="text" id="uselastName" required />
<br>
<input id="updateuser" type ="submit" />
</form>
<script>
$('#updateuser').click(function() {
var useID = $_SESSION["id"];
var useuserName = $("#useuserName").val();
var usepassWord = $("#usepassWord").val();
var usefirstName = $("#usefirstName").val();
var uselastName = $("#uselastName").val();
var usePermissions = $_SESSION["Permissions"];
$.ajax({
type : 'POST',
url : '',
data :{action:'updateuser', useID:useID, useuserName:useuserName, uselastName:uselastName, usePermissions:usePermissions},
error: function (html) {
alert( "What the duck" );
},
});
});
</script>
This is the UpdateUser.php file
<?php
//Update
if($_POST['action'] == 'updateuser'){
//Set Variables
$servername = "localhost";
$username = "root";
$password = "";
$db = "userdb";
//Create connection
$conn = new mysqli($servername, $username, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection: Failed! " . $conn->connect_error);
}
//Actual Code
$useID = $_POST['useID'];
$useuserName = $_POST['useuserName'];
$usepassWord = $_POST['usePassword'];
$usefirstName = $_POST['usefirstName'];
$uselastName = $_POST['uselastName'];
$usePermissions = $_POST['usePermissions'];
//Create Query
$sql = "UPDATE users SET userName = '$useuserName', Pass = '$usepassWord', firstName = '$usefirstName', lastname = '$uselastName', Permissions = '$usePermissions' WHERE id =" . $useID ."";
//Did it work Check
if ($conn->query($sql) === TRUE) {
echo "Cool";
} else {
echo "What " . $conn->error;
}
//Close Out
$conn->close();
}
?>
I'm trying to add a string to my database, where I have two columns: "id" and "image". The "id" column is supposed to increment and the "image" column should get a string. This is my phpcode:
<?php
$servername = "somename";
$username = "someusername";
$password = "somepssword";
$dbname = "somedatabase";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$image = $_POST["image"];
$sql = "INSERT INTO photos (image) VALUES ('$image')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
the html form:
the html form:
<body>
<form method="post" action="phpcode.php">
<input type="text" name="message" size="55">
<input type="submit"name="submit" value="Send">
</form>
</body>
</html>
I use this app to send a post to the server: https://www.getpostman.com/ yet for some reason it only increments a value id and doesn't receive anything for image like here:
enter image description here
<form method="post" action="phpcode.php">
<input type="text" name="message" size="55">
<input type="submit"name="submit" value="Send">
</form>
As suspected, your name attribute field is wrong as it does not correspond to what you are trying to post .
Change to
<form method="post" action="phpcode.php">
<input type="text" name="image" size="55">
<input type="submit"name="submit" value="Send">
</form>
When submitting forms, PHP reads from your "name" attribute on your form. That is what you are posting to your controller 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 :)
Hello guys i need some help.I connected to database from server and can insert some info like $sql = "INSERT INTO Posts (Text_Post) VALUES ('Sample Text')";. Now I want to save on click text from <input type="text" /> to database. Can you tell me what i am doing wrong.
<?php
$servername = "google.com";
$username = "google";
$password = "google";
$dbname = "google";
// 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'])) {
$sql = "INSERT INTO Posts (Text_Post) VALUES ('".$_POST['text']."')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>anonim</title>
</head>
<body>
<form name="form" action="" method="post">
<input type="text" name="text" id="text" value="Salut" /=>
<input type="submit" id="Submit" />
</form>
</body>
</html>
You're missing the name tag on your submit. When data is POST'ed to the server, it uses the name tag.
<input type="submit" id="submit" name="Submit">
Remember to watch your Capitals also - (since you're checking if Submit is SET then you need to POST the submit).
You could just do:
if(isset($_POST['text'])) {
Also, going off the comments: I'd suggest taking a look at this link because you're prone to SQL Injections.
when we are going to post a form using POST or GET. we should always give name to all our fieds so we get get them just using $_POST['name'] or $_GET['name']. In Your case just give a name to your submit tag and check whether data is submitted or not.
replace
<input type="submit" id="Submit" />
with
<input type="submit" id="submit" name="submit">
and check it like
if(isset($_POST['submit'])) {// it will only check where form is posted or not
// your code...
}