multiple SQL insertion & form validation In php - php

I am trying to do multiple product add with a form using php and mysql , and i am confusing on the concept of doing these,
My expecting output is , provide a form with at least ten rows of multiple field to be fill and do the validation among these , and proceed to insertion if no error .
Here is what i understand about single form insertion so far:
$add_errors = array();
//if there is a post request
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// do some validation
if (empty($_POST['name'])) {
$add_errors['name'] = 'Please enter the name!';
}
if (empty($_POST['description'])) {
$add_errors['description'] = 'Please enter the description!';
}
if (empty($add_errors)) { // If everything's OK.
//do the insertion
$q = 'INSERT INTO ........')';
}
}//end of form submission
echo '<form action="product_add.php" enctype="multipart/form-data" method="post" accept-charset="utf-8">';
echo '<input type=..... name=...... id=.....>';
echo '<input type=..... name=...... id=.....>';
echo '<input type=..... name=...... id=.....>';
echo '</form';
//this form is only a single row with multiple column(field) ,I am trying to make it into multiple column

I would rewrite the above code...I'm going to rewrite it here:
<?php
$rows = 10; // rows desired.
//if there is a post request
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
while($i < $rows){
if (empty($_POST['description'.$i])) {
$add_errors['description'.$i] = 'Please enter the description!';
}
// more error checking if needed...
++$i;
}
if (empty($add_errors)) { // If everything's OK.
//do the insertion
$q = 'INSERT INTO ........')';
}
}//end of form submission
echo '<form action="product_add.php" enctype="multipart/form-data" method="post" accept-charset="utf-8">';
$i = 0;
while($i < $rows){
echo '<input type=..... name="description'.$i.'" id=.....>';
++$i;
}
echo '</form';
?>
Try something like that...(my code might have an error or two in it as I just wrote it here and didn't test it) but that's the general idea. =)

Related

PHP Array Size Loop

We need to create a program that lets the user input the array size, their name, and age (depending on the array size the user entered). After that, we need to display all the elements of the array.
This is my code, but I'm having a problem adding a new element for another user and displaying it.
<html>
<head>
<title> PHP Array </title>
</head>
<body>
<form method="post" action="example.php">
<h3> Please enter the your information: </h3>
Array Size: <input type="text" name="arraysize"/> <br/><br>
Name: <input type="text" name="name" /><br/><br/>
Age: <input type="text" name="age"/> <br/><br/>
<input type="submit" name="submit" value="Submit"/>
<input type="reset" name="cancel" value="Cancel"/><br/><br/>
<?php
if(isset($_POST['submit'])){
if((!empty($_POST['name'])) && (!empty($_POST['age'])) && (!empty($_POST['arraysize']))){
$info = array($_POST['arraysize'], $_POST['name'], $_POST['g6ave']);
$arraylength = count($info);
for ($i=0; $i<=$arraylength ; $i++) {
$name = $_POST['name'];
for ($j=1; $j<=$i; $j++){
echo "User's Name" .$i. ": " .$name. [$j] ."<br>";
$age = $_POST['age'];
for($k=0; $k<=$i; $k++){
echo "User's Age: " .$age. [$k] ."<br/>";
}
}
}
}
}
?>
</body>
</html>
One approach (of other possible approaches) below should give you the main ideas. I also commented the aim of the each script part.
Approach below assumes that you'll use same URL for all your form pages. (1st, 2nd and the success page)
I hope this helps.
session_start(); //Start new or resume existing session
if (isset($_SESSION['form_success']) && $_SESSION['form_success'] === true)
{
require 'success_page.php';
unset($_SESSION['form_success']); // don't needed anymore
return; //not to continue to execute the code
}
// decide the page from user
if (isset($_POST['page']))
{
$page = $_POST['page'];
}
else
{
// display the first form page for the 1st time
require 'first_page_form.php';
return; //not to continue to execute the code
}
// if the first page was submitted.
if ($page === 'first') // or a specific POST flag from 1st page
{
//verify data from first page
$warnings = [];
if (first_page_data_valid() === true)
{
require 'second_page_form.php';
return; //not to continue to execute the code
}
// populate $warnings during first_page_data_valid()
//if first page data are invalid
print_r($warnings);
require 'first_page_form.php'; //display again
return; //not to continue to execute the code
}
// if the second page was submitted.
if ($page === 'second') // or a specific POST flag from 2nd page
{
//verify data from second page
$warnings = [];
if (second_page_data_valid() === true) // populate $warnings during second_page_data_valid()
{
// do things. ex: DB operations.
if (db_actions_success() === true)
{
$_SESSION['form_success'] = true; // defined and set to true.
// PHP permanent URL redirection. usage of 301 is important.
// it clears POST content. Prevents F5/refresh.
header("Location: https://www.url.com/form.php", true, 301);
exit; // good/recommended to use after redirect
}
else
{
echo 'System down or I have a bug. Try again later.';
return; //not to continue to execute the code
}
}
//if second page data is invalid
print_r($warnings);
require 'second_page_form.php'; //display again
return; //not to continue to execute the code
}

PHP If / Else statement going directly to the Else without waiting for form input

Ok so I have a form with 1 input and a submit button. Now I am using an if/else statement to make three acceptable answers for that input. Yes, No, or anything else. This if/else is working the thing is the code is kicking out the else function as soon as the page is loaded. I would like there to be nothing there until the user inputs then it would show one of three answers.
Welcome to your Adventure! You awake to the sound of rats scurrying around your dank, dark cell. It takes a minute for your eyes to adjust to your surroundings. In the corner of the room you see what looks like a rusty key.
<br/>
Do you want to pick up the key?<br/>
<?php
//These are the project's variables.
$text2 = 'You take the key and the crumby loaf of bread.<br/>';
$text3 = 'You decide to waste away in misery!<br/>';
$text4 = 'I didnt understand your answer. Please try again.<br/>';
$a = 'yes';
$b = 'no';
// If / Else operators.
if(isset($_POST['senddata'])) {
$usertypes = $_POST['name'];
}
if ($usertypes == $a){
echo ($text2);
}
elseif ($usertypes == $b){
echo ($text3);
}
else {
echo ($text4);
}
?>
<form action="phpgametest.php" method="post">
<input type="text" name="name" /><br>
<input type="submit" name="senddata" /><br>
</form>
You just need to call the code only when the POST value is set. This way it will only execute the code when the form was submitted (aka $_POST['senddata'] is set):
if(isset($_POST['senddata'])) {
$usertypes = $_POST['name'];
if ($usertypes == $a){
echo ($text2);
}
elseif ($usertypes == $b){
echo ($text3);
}
else {
echo ($text4);
}
}
Just put the validation in the first if statement like this:
if(isset($_POST['senddata'])) {
$usertypes = $_POST['name'];
if ($usertypes == $a) {
echo ($text2);
} elseif ($usertypes == $b) {
echo ($text3);
} else {
echo ($text4);
}
}
When you load your page the browser is making a GET request, when you submit your form the browser is making a POST request. You can check what request is made using:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Your form was submitted
}
Put this around your form processing code in order to keep it from being executed on GET request.

Creating an error in an else

Basically I want to add one last piece of validation, if nothing is selected on the items page then an error appears or the user is returned to another page.
When submit is selected the form action sends it to the confirm page and the below is executed which displays the items selected if there is 1 or more entered if ($partno == $varname & $qty > 0) but I dont no what to put in the else part to return an error or take the user back to the previous page.
<?php
$visitor = $_POST['visitor'];
echo "<p>" . 'Hello ' . "<b>" . $visitor . "</b> " . 'please confirm your purchase(s) below.' . "</p>";
if (!($data = file('items.txt'))) {
echo 'ERROR: Failed to open file! </body></html>';
exit;
}
$total = 0;
foreach ($_POST as $varname => $varvalue) {
$qty = $varvalue;
foreach ($data as $thedata) {
list($partno, $name, $description, $price, $image) = explode('|', $thedata);
if ($partno == $varname & $qty > 0) {
echo "<tr><td><img src='$image' width='50' height='50' alt='image'</td>
<td>$partno<input type='hidden' name='$partno' value=$partno></td><td>$name</td><td>£$price</td>
<td> $qty</td><td><input type='hidden' name='visitor' value=$visitor></td>
<td><input type='hidden' name='qty' value=$qty></td></tr>";
$total = $total + $price * $qty;
} else {
}
}
}
?>
You'd have something like this:
$errors = array();
foreach(...) {
if ($partno == $varname & $qty > 0) {
... code for "ok" stuff
} else {
$errors[] = "$partno is incorrect";
}
}
if (count($errors) > 0) {
die("Errors: " . implode($errors));
}
... proceed to "success" code ...
Basically, for every test that fails, you record a message. Once the loop exits, if there's any error messages, you display them and abort processing. If there's no errors, you proceed onwards with the rest of the code.
Why not use a try catch block?
try {
if (isset($_POST)) {
if (!$email) {
throw new Exception('email is not valid', 100);
}
// everything is good process the request
}
throw new Exception('Error!', 200);
} catch (Exception $e) {
if ($e->getCode == 200) {
// redirect
} else {
// do something else
}
}
throw an Exception in your If statement, then put your data in try/catch block, so it will catch an exception if error occured
Consider the following approach: both the form and the php code to do something with the form data are on the same page. If the form was posted, you'll first check if the form was ok, after that you'll do something with the submitted data. If the form was not valid, display an error message.
The advantage is: no die() in the middle of your code, no strange redirects, everything in one script.
// simplified code in example.php
<?php
// in this variable we'll save success/error messages to print it
$msg = "";
// run this php code if the form was submitted
if(isset($_POST['submit'])) {
// is the form valid?
if (strlen($_POST['username']) == 0) {
$msg = "Please enter a username";
}
else {
// all validation tests are passed, give the user a nice feedback
// do something with the data, e.g. save it to the db
$msg = "Your data was saved. Have a great day";
}
}
?>
<div class="msg"><?php print $msg; ?></div>
<form method="post">
<input type="text" name="username">
<input type="submit" name="submit" value="Submit">
</form>

Empty input type not being posted in html

I created a PHP function that will create a form for any table that you have in a database. This function allows you to specify the name of the table and a list of all the columns you want in your html form. Everything works great, if the user puts something in for the text inputs. If they don't, then strange things happen when trying to retrieve the column name. Please see the function below...
function generateSubmissionFromTable($db, $tablename, $rowstoinclude,$action)
{
$query = 'SHOW COLUMNS from '.$tablename;
$colsresult = mysql_query($query,$db);
$table = array();
while($row = mysql_fetch_array($colsresult))
{
array_push($table,$row[0]);
}
$finalcolumns = array();
foreach($table as $row)
{
foreach($rowstoinclude as $inc)
{
if($row == $inc)
{
array_push($finalcolumns,$row);
}
}
}
echo '<form name="loginy" method="post" action="'.$action.'">';
foreach($finalcolumns as $column)
{
echo 'Please enter the '.$column.'<br/>';
echo '<input type=text name=column['.$column.'] value="blah"/><br/>';
}
echo '<input type="hidden" name="tablename" value="'.$tablename.'" />';
echo '<button type="button" size="4" style="font-size:35px;" onClick="document.loginy.submit()">Submit</button>';
echo '</form>';
}
Now, comes the weird part... I have another function that will generate the query statement based off that automatic form generation.
function submitDataToTable($post)
{
$query = 'INSERT INTO '.$post['tablename'].'(';
$buf = "";
while($col = current($post['column']))
{
$query = $query.$buf.key($post['column']);
$buf=",";
next($post['column']);
}
$buf = "";
$query = $query.') VALUES (';
foreach($post['column'] as $val)
{
$query = $query.$buf.$val;
$buf = ",";
}
$query = $query.')';
echo 'QUERY='.$query;
}
Now for example I have a table that I want to input for 3 columns (name, link, descritpion) and I fill in the top 2 and not the bottom, the query gets generated as this...
QUERY=INSERT INTO LinksWebsites(name,link) VALUES (blah,blah,)
which as you can see, the query is missing the column (name,link,descritption) but what is weird if you take a look at the post...
POST =Array ( [column] => Array ( [name] => blah [link] => blah [description] => ) [tablename] => LinksWebsites )
which shows all the keys, but my PHP method of extracting the keys is not showing all the keys! (Might have something to do with the current($array) and key($array) calls?)
Try putting a java script in your html where you will put the php function that text inputs must not be blank before trying to submit it.
<script>
function validateForm()
{
if (inputbox==null || inputbox=="")
{alert("Input should not be empty");
return false;
}
}
</script>
Just include the onsubmit="return validateForm()" in the form tag.

Server Side Form Validation PHP with multi-file Upload

HTML:
Owner: input type="text" name="owner[]" />
Category:
<select name="cat[]">
<option value="clothes">Clothes</option>
<option value="shoes">Shoes</option>
<option value="accessories">Accessories</option>
</select>
Upload: <input type="file" name="image[]" />
whith function that clone the same fields when click on "+ button"
I count the POST field with:
$num = count($_FILES['image']['name']);
because i want to know how many times the end user clone the fields.
what i want is Make sure that the user has to fill all fields which he opend with "+ button" i cant check all the hidden fields i want to check just the field he opend.
so what can i do ?
i cant do like this:
$owner = $_POST['owner'][$i];
$cat = $_POST['cat'][$i];
$file = $_FILES['image'][$i];
if ($owner && $cat && $file)
echo "bla bla bla";
else
echo "fill all the fields!";
can anyone help me ?
thank you
There are some points which you need to make sure beforehand. Whenever you are using any input field's name attribute as "owner[]" or "cat[]" or "image[]", you will get an array then. But since, input file's property accessing capability is already 2D array by default, so now you will be able to access those properties as a 3D array.
When you have added a "[]" for the input file field's name attribute, you will now get the name of the 1st file as "$_FILES['image'][0]['name']", because array indices start with 0. As per your question, you can validate using the following way:-
<?php
$numOwners = count($_POST['owner']);
$numCats = count($_POST['cat']);
$numFiles = count($_FILES['image']);
// Check to see if the number of Fields for each (Owners, Categories & Files) are the same
if ($numFiles === $numCats && $numFiles === $numOwners) {
$boolInconsistencyOwners = FALSE;
$boolInconsistencyCats = FALSE;
$boolInconsistencyFiles = FALSE;
for ($i = 0; $i < $numFiles; $i++) {
if (empty($_POST['owner'][$i])) {
$boolInconsistencyOwners = TRUE;
break;
}
if (empty($_POST['cat'][$i])) {
$boolInconsistencyCats = TRUE;
break;
}
if (!is_uploaded_file($_FILES['image'][$i]['tmp_name'])) {
$boolInconsistencyFiles = TRUE;
break;
}
}
if ($boolInconsistencyOwners || $boolInconsistencyCats || $boolInconsistencyFiles) {
echo "I knew that there will be some problems with users' mentality!";
// Redirect with proper Error Messages
}
else {
echo "Wow, Users have improved & have become quite obedient!";
// Proceed with normal requirements
}
}
else {
echo "Something fishy is going on!";
}
?>
Hope it helps.

Categories