How to make an html/php form? - php

I have a php file (let's call it first) that stores names in a database. I now have a different php file with a html/php form (let's call it second). How can I make the form (second) input names into my database using my inital php (first) file?
Below is my php form:
<!DOCTYPE HTML>
<HTML>
<head>
<title>PHP FORM</title>
</head>
<body>
<h2>PHP FORM for Process Form</h2>
<form method="post" action="processForm.php">
Name: <input type="text" name="names" required = "required"><br>
<input type="submit" value="Create Users" onclick="formInputNames"><br>
<input type="checkbox" name="activate" value="Activate">Activate
</form>
</body>
</html>
Below is 'php first':
$nameList = 'Obi One, Not Naw, Lent Over, Foo Bar';
$newerName = 'Green Sauce';
$nameList = newUse($newerName,$nameList);
$email = '#email.org';
$fullnames = explode(" ",$nameList);
function newUse($nep, $nameList){
if($nep == empty($nameSplit[0]) && empty($nameSplit[1]) || empty($newName)){
return "$nameList, $nep";
}
return $nameList;
}
/*I open the database here*/
foreach ($fullnames as $fullname){
$nameSplit = explode(" ", $fullname);
if ($nameList == empty($nameSplit[0]) || empty($nameList)){
echo 'No First Name Here Or No Name At All';
echo '<br>';
echo '<br>';
} elseif ($nameList == empty($nameSplit[1])){
echo 'No Last Name Here';
echo '<br>';
echo '<br>';
} else{
$firstName = $nameSplit[0];
$lastName = $nameSplit[1];
$emailUser = $nameSplit[0].$email;
echo 'First Name: ' . $firstName;
echo '<br>';
echo 'Last Name: ' . $lastName;
echo '<br>';
echo 'Email Address: ' . $firstName . $email;
echo '<br>';
echo '<br>';
}
$queryString = "INSERT INTO `project`.`user`
(`id`, `firstName`, `lastName`, `email`, `activated`, `date_created`)
VALUES
(NULL, '$firstName', '$lastName', '$emailUser', '0', NOW())";
$result = mysqli_query($conn, $queryString)
or die (mysqli_error($conn));
}
I'm new to php and I'm really at a lost here. I'm pretty sure I need to use POST but I don't really understand how. Please help me out. Thank You.
Everything I have googled has not helped me and some of the similar questions on this site have not either. I need help.

You seem to have problem only with how to post the values, So your HTML file:
<form method="post" action="processForm.php">
First Name: <input type="text" name="firstname">
Second Name: <input type="text" name="lastname">
<input type="submit" value="Submit">
</form>
Your PHP file:
$firstName = $_POST['firstname'];
$lastName = $_POST['lastname'];
$name = $firstName ." ". $lastName;
//Code for adding the values to the database.

If you put your function at the top of your processForm.php above where it is called it could be
// I am assuming this comes from your database
$nameList = 'Obi One, Not Naw, Lent Over, Foo Bar';
$newerName = $_POST['names'];
$email = '#email.org';
function newUse($nep, $nameList){
$nameSplit = array();
$nameSplit = explode(" ", $nep);
if(!empty($nameSplit[0]) && !empty($nameSplit[1]){
return "$nameList, $nep";
}
return $nameList;
}
$nameList = newUse($newerName,$nameList);
// need to explode on comma into name pairs with spaces or there will be nothing to explode into $nameSplit later.
$fullnames = explode(',', $nameList);
It might be worth making two text boxes - one for firstname name="firstname" and one for second name name="secondname", then putting the two together as in
$newerName = $_POST['firstname'] . " " . $_POST['secondname'];
This would ensure that you would reduce the risk of people putting two spaces or something else unwanted separating their names that would make your explode(); fail.
$newerName = mysqli_real_escape_string($newerName);
Before you put it into the function will help eliminate some of the security problems but it is not infallible.
The HTML would be
<form method="post" action="processForm.php">
First Name: <input type="text" name="firstname" required /><br />
Second Name: <input type="text" name="secondname" required /><br />
<input type="submit" value="Create Users" /><br />
<input type="checkbox" name="activate" value="Activate" />Activate
</form>
You could give your checkbox a value of 1 and pick that up as $activate = intval($_POST['activate']); where the forcing to integer will have the effect of cleaning it up. You could then use that as a variable where you currently have '0' in your MySql.

Related

How to insert textbox value from form to csv one by one?

My Goal is to insert the value from a textbox from a form to csv one by one.
I tried to look for answers in the internet but I can't seems to find similar scenario on this problem
<?php
if(isset($_POST['submit']))
{
//read data from form
$lName = filter_input(INPUT_POST, "lName");
$fName = filter_input(INPUT_POST, "fName");
$email = filter_input(INPUT_POST, "email");
$phone = filter_input(INPUT_POST, "phone");
//generate output for text file
$output = $fName . " ";
$output .= $lName . " ";
$output .= $email . " ";
$output .= $phone . " ";
//here "t" means tab
//here "n" newline
//open file for output with append mode "a"
$fp = fopen("contacts.csv", "a");
//write to the file
fwrite($fp, $output);
fclose($fp);
}
else
{
echo "empty submit";
}
?>
<html>
<head>
</head>
<body>
<form action="next_page.php" method="post" >
Lastname:<input type="text" name="lName" />
Firstname:<input type="text" name="fName" />
Email:<input type="text" name="email" />
Phone:<input type="text" name="phone" />
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>
My expected output is Lastname will be save in first cell, Firstname will be saev in 2nd cell, and so on.

I have multiple submit buttons and a validation issue with the second form

So I have two forms that are hidden when submitted. The validation for the second form isn't working. Any clue as to why?
if(isset($_POST['submit'])){
$feet = $_POST['feet'];
$lname = $_POST['lname'];
if(!is_numeric($feet)){
$isValid = false;
$feetError = "Try again buddy";
}
echo "Hello Captain " . $lname . " Are you" . $feet ."ft tall?";
}
elseif(isset($_POST['submit2'])){
$feet2 = $_POST['feet2'];
$lname2 = $_POST['lname2'];
$isValid2 = true;
if(!is_numeric($feet2)){
$isValid2 = false;
$feetError2 = "Try again buddy";
}
echo "Hello Captain " . $lname2 . " Are you" . $feet2 ."ft tall?";
}
else{
?>
<form name="formie" id="formie" action="test1.php" method="post">
<p><label>square feet</label><input type="text" id="feet" name="feet"><span><?PHP echo $feetError; ?></span></p>
<p><label>Last Name</label><input type="text" id="lname" name="lname"></p>
<p><button type="submit" name="submit" id="submit">Submit</button></p>
</form>
<form name="formie2" id="formie2" action="test1.php" method="post">
<p><label>square feet</label><input type="text" id="feet2" name="feet2"><span><?PHP echo $feetError2; ?></span></p>
<p><label>Last Name</label><input type="text" id="lname2" name="lname2"></p>
<p><button type="submit" name="submit2" id="submit2">Submit</button></p>
</form>
<?PHP
}
?>
These are all place holders BTW. The project I'm working on is much much larger, I just want to understand the whole 'hiding forms' thing before I try to implement it on a larger scale.
Thank You guys!
$isSubmitted = false;
$isValid = true;
$isValid2 = true;
$feetError = '';
$feetError2 = '';
if(isset($_POST['submit'])){
$isSubmitted = true;
$feet = $_POST['feet'];
$lname = $_POST['lname'];
if(!is_numeric($feet)){
$isValid = false;
$feetError = "Try again buddy";
} else {
echo "Hello Captain " . $lname . " Are you" . $feet ."ft tall?";
}
}
elseif(isset($_POST['submit2'])){
$isSubmitted = true;
$feet2 = $_POST['feet2'];
$lname2 = $_POST['lname2'];
if(!is_numeric($feet2)){
$isValid2 = false;
$feetError2 = "Try again buddy";
} else {
echo "Hello Captain " . $lname2 . " Are you" . $feet2 ."ft tall?";
}
}
?>
<?php if(!$isSubmitted || !$isValid || !$isValid2) { ?>
<form name="formie" id="formie" action="test1.php" method="post">
<p><label>square feet</label><input type="text" id="feet" name="feet"><span><?PHP echo $feetError; ?></span></p>
<p><label>Last Name</label><input type="text" id="lname" name="lname"></p>
<p><button type="submit" name="submit" id="submit">Submit</button></p>
</form>
<form name="formie2" id="formie2" action="test1.php" method="post">
<p><label>square feet</label><input type="text" id="feet2" name="feet2"><span><?PHP echo $feetError2; ?></span></p>
<p><label>Last Name</label><input type="text" id="lname2" name="lname2"></p>
<p><button type="submit" name="submit2" id="submit2">Submit</button></p>
</form>
<?php } ?>
When you submit a form, the PHP reloads the page. When the page is reloaded, it is reloaded WITH the previous posted values of your form. Therefore it will always trigger your first condition assuming the user is submitting the first form first.
You have 2 solutions. Do separate script, or use another if, instead the if - else. I'd recommend separate script though.
I recommend separate script for each form, with a header redirecting to your website after, it's easier to remember and to order your work afterwards.

Adding an image into a database using a html form

I am trying to add records into a database. Each record has a corresponding image. The records are getting inserted into the database but it is not working for the image. I am getting this error "connected succesfully
Notice: Undefined variable: sql in C:\xampp\htdocs\Syokimaufc\addplayer.php on line 35
Error: Query was empty" How can i solve this?
HTML form
<p> id: <input type="text" name="playerid"/></p>
<p> Name: <input type="text" name="name"/></p>
<p> Age: <input type="text" name="age"/></p>
<p> Position: <input type="text" name="position"/></p>
<p> Nationality: <input type="text" name="nationality"/></p>
<p> Photo: <input type="file" name="image"/></p>
<input type="submit" value="submit"/>
<form/>
php script
<?php
require 'connection.php';
$id = filter_input(INPUT_POST, 'playerid');
$name = filter_input(INPUT_POST, 'name');
$age = filter_input(INPUT_POST, 'age');
$position = filter_input(INPUT_POST, 'position');
$nationality = filter_input(INPUT_POST, 'nationality');
$_id = mysql_real_escape_string( $id );
$_name = mysql_real_escape_string( $name );
$_age = mysql_real_escape_string( $age );
$_position = mysql_real_escape_string( $position );
$_nationality = mysql_real_escape_string( $nationality );
if (isset($_POST['submit']))
{
$imageName = mysql_real_escape_string($_FILES ["image"]["iname"]);
$imageData = mysql_real_escape(file_get_contents($_FILES["image"]["tmp_name"]));
$imageType = mysql_real_escape_string($_FILES["image"]["iname"]);
if (substr($imageType,0,5) == "image")
{
$sql = "INSERT INTO players ( playerid, name, age, position, nationality, iname, image ) VALUES ( '$_id', '$_name', '$_age', '$_position', '$_nationality', '$imageName', '$imageData' )";
}
else
{
echo "only images are allowed";
}
}
if (!mysql_query($sql)){
die('Error: ' . mysql_error());
}
in your form try adding an attribute:
<form enctype="multipart/form-data">
......
..
</form>
Have you tried it with the name property in the submit ?, it seems that is not going to "if"
<input type="submit" name="submit" value="submit"/>
just check following steps:
In html file, a form with image upload should be set with enctype="multipart/form-data"
e.g. <form enctype="multipart/form-data>
In PHP script
$_FILES["image"]["iname"] is wrong.
$_FILES["image"]["name"] should be the right one.

Inserting HTML form submissions into MySQL table (using PDO)

I'm trying to create a webpage that has multiple forms that people will fill, click submit, PHP will handle running a query to insert all the data into the table, in their respective fields.
I created one that submitted one field completely fine, and as soon as I expanded it to 5 fields I realised I didn't know how to handle the code.
<html>
<head>
<title>Asset Pass</title>
</head>
<body>
<h1>Asset Submission</h1>
<p>Connection status: <?php include '../mysqlconnect.php'; echo $db . " active"; ?></p>
<form method="post">
<div><label for="type">Type:
<br/><input type="text" name="type" id="type"/></label></div>
<div><label for="name">Name:
<br/><input type="text" name="name" id="name"/></label></div>
<div><label for="desc">Description:
<br/><input type="text" name="desc" id="desc"/></label></div>
<div><label for="loc">Location:
<br/><input type="text" name="loc" id="loc"/></label></div>
<div><label for="label">Label:
<br/><input type="text" name="label" id="label"/></label></div>
<div><input type="submit" name="submit" value="GO"/></div>
</form>
<?php
#function aquery($asset) {
# include '../mysqlconnect.php';
# $conn->query("INSERT INTO kit VALUES ('$asset', '$name', '$desc', '$loc', '$label');");
#}
if ($_POST['submit']) {
include '../mysqlconnect.php';
foreach ($_POST['type'] as $key => $value)
{
$type = $_POST['type'] [$key];
$name = $_POST['name'] [$key];
$desc = $_POST['desc'] [$key];
$loc = $_POST['loc'] [$key];
$label = $_POST['label'][$key];
$sql = $conn->query("INSERT INTO Kit VALUES ('$type', '$name', '$desc', '$loc', '$label');");
}
}
## $asset = $_POST['name'];
# aquery($asset);
# printf("<h3>Entry Accepted</h3>" . "<br/><br/>" . "<strong>Submission: </strong>" . $asset . "<br/><br/>");
?>
</body>
</html>
Sorry for the butchered code - the commented bits at the top and bottom are the original fragments of code I tried using, the bit in the middle is a suggested online solution, and something close to what I think would work. I'm using PDO btw!
Didn't understand how $_POST and isset worked properly.
if (isset($_POST['submit']))
{
include '../mysqlconnect.php';
$type = filter_input(INPUT_POST, 'type', FILTER_SANITIZE_MAGIC_QUOTES);
and so forth, works perfectly.

how to insert multiple array into database using PHP

I need help. What seems to be the problem with our php codes? We can't seem to insert our data into our database. I'm just a beginner and I'm tasked to store multiple data into multiple arrays into our database. What we're actually doing is to enter a number (ex: 5) and 5 forms should show within that page. each form would consist of name address and tel phone number. after that we submit it to our database. We have already controlled hot many forms to show but we weren't able to store the data inserted. Can anyone help us please? Thank you.
form.php
<form method="POST" action="form.php">
<input type="text" name="waw" />
<input type="submit" />
<?php
$i=0;
while ($i<$_POST['waw'])
{
?>
</form>
<form method="POST" action="input.php">
<!-- Person #1 -->
<input type="text" name="username[]" />
<input type="text" name="phonenum[]" />
<input type="text" name="add[]" />
<?php
$i++;
}
?>
<input type="submit" />
</form>
input.php
<?php
$username="maizakath";
$password="12345";
$database="tryinsert";
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die("<b>Unable to specified database</b>");
$sql_start = 'INSERT INTO `mytable` VALUES ';
$sql_array = array();
$queue_num = $_POST['waw'];
foreach ($_POST['username'] as $row=>$name)
{
$username = $name;
$phonenum = $_POST['phonenum'][$row];
$add = $_POST['add'][$row];
$sql_array[] = '(' . $username . ', ' . $phonenum . ', ' . $add . ')';
if (count($sql_array) >= $queue_num)
{
mysql_query($sql_start . implode(', ', $sql_array));
$sql_array = array();
}
}
if (count($sql_array) > 0)
{
mysql_query($sql_start . implode(', ', $sql_array))or die(mysql_error());
}
?>
I've modified your code to make it work:
form.php
<form method="POST" action="form.php">
<input type="text" name="waw" />
<input type="submit" />
</form>
<form method="POST" action="input.php">
<?php
$i=0;
while ($i<$_GET['waw'])
{
?>
<!-- Person #1 -->
<input type="text" name="username[]" />
<input type="text" name="phonenum[]" />
<input type="text" name="add[]" /><br />
<?php
$i++;
}
?>
<input type="submit" />
</form>
input.php
<?php
$username="maizakath";
$password="12345";
$database="tryinsert";
mysql_connect('localhost',$username,$password);
#mysql_select_db($database) or die("<b>Unable to specified database</b>");
$sql_start = 'INSERT INTO `mytable` VALUES ';
$sql_array = array();
$queue_num = $_POST['waw'];
foreach ($_POST['username'] as $row=>$name)
{
$username = $name;
$phonenum = $_POST['phonenum'][$row];
$add = $_POST['add'][$row];
$sql_array[] = '("' . $username . '", "'.$phonenum.'", "'.$add.'")';
if (count($sql_array) >= $queue_num) {
$query_single=$sql_start . implode(', ', $sql_array);
mysql_query($query_single);
$sql_array = array();
}
}
if (count($sql_array) > 0) {
$query = $sql_start . implode(', ', $sql_array);
mysql_query($query)or die(mysql_error());
}
?>
It works fine. I've just tested it on my local machine.
EDIT(Comments):
Usage of variable $queue_num in input.php is senseless, because this variable is available only in form.php script('wow' input placed in another form, which is submitted to file form.php, not input.php). So if (count($sql_array) >= $queue_num) block works wrong;
Check your config settings for the database connection(as I've wrote in comment, you have to define constant with name 'localhost' or enclose word localhost with quotes);
I've modified your form, because it had wrong structure;
I didn't understand the objective of creating first form in form.php.
You can modify this code to make it more appropriate for your case. But firsat of all try to use this one.
Note. Use var_dump() function to see your $_POST array during debugging to understand, what variables are available.
I Had tried its work fine but when inserting into database it will insert null value also if user did'nt filled up the whole field.
I have stored two arrays in one table at the same time. Hope this will help you.
<?php
$i = 0;
foreach($element_name as $element_names){
$element_value = $_POST['element_value'];
$element_names_insert = mysql_query("insert into wp_remote_fields
set
remote_fields = '".$element_names."',
remote_values = '".$element_value[$i]."'
");
$i++;
}
?>

Categories