Creating an error in an else - php

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>

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
}

Form inserting empty data to database

Whenever I submit the form with empty input, it sends the empty input to my database. The form was working fine until after I used the htmlentities() for its functionality.
I used the gettype() function to return what's in the inserted variable and it returns "string", but when I checked the code from the browser, I could not see anything in the table.
This is the code snippet and the form processing code
<?php
$errors = [];
$missing = [];
if(isset($_POST['sendFirm']) ){
$expected = array('firmName','country','state','email','phoneNumber');
$required = array('firmName','country','state','phoneNumber');
<?php
foreach ($_POST as $key => $value) {
if(is_array($value)){
$value = $value;
}else{
$value = trim($value);
}
if(empty($value) && in_array($key, $required)){
$missing[] = $key;
$$key = '';
}elseif(in_array($key, $expected)){
$$key = "$value";
}
}
?>
}
?>
<?php
if($errors || $missing){
?>
<p>Please fix the following items</p>
<?php } ?>
<form method="post" action="<?php $_SERVER['PHP_SELF'] ?>">
<div class="form-group">
<label>Compnay Name
<?php if($missing && in_array('firmName', $missing)) { ?>
<span class="text-danger">Please enter firm name</span>
<?php } ?>
</label>
<input class="form-control" type="text" name="firmName" id="firmName" placeholder="Company Name"
<?php
if($errors || $missing){
print 'value="' . htmlentities($firmName) . '"';
}
>
<button class="btn btn-primary" type="submit"
name="sendFirm">Submit</button>
</form>
?>
>
<?php
if(isset($_POST['sendFirm'])){
try {
$connectToFirms = new
PDO('mysql:host=localhost;dbname=firms','root','2332');
$connectToFirms->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
$prepInsertion = $connectToFirms->prepare('INSERT INTO contractors
VALUES (null,?,?,?,?,?)');
$prepInsertion->execute(array($firmName, $country, $state, $email,
$phoneNumber));
}catch (PDOException $e) {
print "An error occure: " . $e->getMessage();
}
}
?>
The form is expected to insert inputs into the database only if the input is not empty and is also in the $expected[];
Don't insert data
I would stop the whole data insertion, if the expected input is not given. I would also send the input data one by one to PHP, so you have a better overview over your code. Good overview = less errors ;)
Try it this way:
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$firmname = htmlentities($_POST["firmName"], ENT_QUOTES);
$country = htmlentities($_POST["country"], ENT_QUOTES);
$state = htmlentities($_POST["state"], ENT_QUOTES);
$pn = htmlentities($_POST["phoneNumber"], ENT_QUOTES);
// LET'S START THE VALIDATION
// if the required fields are not empty, insert data
if (!empty($firmname) && !empty($country) && !empty(state) && !empty($pn)) {
// insert data
} else { // else stop insertion and return error message
// return error message
}
} else {
// redirect...
}
I hope, i understood your question correctly and could help.

Why is HTML in php function not visible in view source

function that runs when i want to edit a client status.
// deletes (sets inactive) client
function setClientStatus($client) {
if ($_GET['action'] == "setinactive") {
//database functions
$sql = 'UPDATE clients SET active="0" WHERE id="'. $client .'"';
$result = query($sql);
confirmQuery($result);
//set message to user to display
$_SESSION['error'] = false;
$msgs[] = "Client was set to inactive and removed from the list!";
$_SESSION['userMsg'] = $msgs;
}
if ($_GET['action'] == "setactive") {
//database functions
$sql = 'UPDATE clients SET active="1" WHERE id="'. $client .'"';
$result = query($sql);
confirmQuery($result);
//set message to user to display
$_SESSION['error'] = false;
$msgs[] = "Client was successfully restored!";
$_SESSION['userMsg'] = $msgs;
}
//display clients page with changes made
redirect('?page=clients');
}
function that displays the message.
//function that shows message and styles accordingly
function message($msgs) {
if(!empty($msgs)) {
foreach ($_SESSION['userMsg'] as $msg) {
if ($_SESSION['error'] == false) {
echo '<div class="noError">'.$msg.'</div>';
} else {
echo '<div class="error">'.$msg.'</div>';
}
}
}
unset($_SESSION['userMsg']);
unset($_SESSION['error']);
echo "hello";
}
here is where i call it in my page....
div class="pageContainer">
<?php
//display messages
message($_SESSION['userMsg']);
?>
</div>
Now when everything is run and i select to edit and client status (or add client, edit client as they all have the same message section, just with different message) i can see the message displayed on the screen. i have a javascript script that will hid the message after 5 seconds, but it doesn't hide. after viewing the page source i notice that the section of code is not visible. again, i can see it clearly see the message that is suppose to be there "Client was set to inactive and removed from the list!" (or whatever message is set to display) but it is NOT show in the view source html.
pic of page loaded with message
here is the view source.....
<div class="pageContainer">
<div>
** updated **
this small example script renders the html, but my above script doesn't...
function setError() {
$error[] = "Password field is to short";
$_SESSION['userMsg'] = $error;
//return $_SESSION['msg'];
}
function message($errors){
if(!empty($errors)) {
foreach ($_SESSION['userMsg'] as $error) {
echo $error.'<br>';
}
}
unset($_SESSION['userMsg']);
}
If I get you right, you want to display $msgs, so why you iterate $_SESSION['userMsg'] ?
Probably the $_SESSION['userMsg'] is null or empty. If you want to display the $msgs just iterate it. And later add to session if really needed. In you code, you always unset the $_SESSION['userMsg'] in the end of function, probably it is always null then. I didn't see the $_SESSION['userMsg'] needed here :
//function that shows message and styles accordingly
function message($msgs) {
if(!empty($msgs)) {
foreach ($msgs as $msg) {
if ($_SESSION['error'] == false) {
echo '<div class="noError">'.$msg.'</div>';
} else {
echo '<div class="error">'.$msg.'</div>';
}
}
}
unset($_SESSION['error']);
echo "hello";
}
UPDATED
After reading your comments, this is related to javascript problem. You should add the id in <div> in order for it's works.
if ($_SESSION['error'] == false) {
echo '<div id="noError" class="noError">'.$msg.'</div>';
} else {
echo '<div id="error" class="error">'.$msg.'</div>';
}

need help echo in index.php from process.php

After my form has been submitted and my message has been sent I want to go back to the index which this does, but I also want to display echo 'Message has been sent' in the index.php in a div instead of my process.php, how would I go about doing this. Sort of new to php if you need any more of my code I will provide or link to site. Thanks.
This is what i tried so far.
in my process.php file
if(!$mail->send()) {
$output = 1;
// $output = 'Mailer Error: ' . $mail->ErrorInfo;
} else {
$output = 2;
header('Location:index.php');
}
in my index.php file
<?php
if ($output == 2) {
echo "<b>Message has been sent</b>";
} elseif ($output == 1) {
echo "<b>Message could not be sent, please try again</b>";
} else {}
?>
The variable $output isn't set in your index.php file.
As an easy way to start you can try it like
header('Location:index.php?output='.$output);
and fetch output in your index.php with
$output = $_GET['output'];
at the beginning of your file, that way you will be able to make your if statements work.
Also be advised that you will never be redirected if $output = 1 in your process.php, as the header is only in the else statement. Simply place the header after your else statements closing bracket.
if(!$mail->send()) {
$output = 1;
} else {
$output = 2;
}
header('Location:index.php?output='.$output);
die();
index.php:
<?php
if (isset($_GET['output'])) {
$output = $_GET['output'];
if ($output == 2) {
echo "<b>Message has been sent</b>";
} elseif ($output == 1) {
echo "<b>Message could not be sent, please try again</b>";
}
}
Please be advised that you shouldn't use unsanitized request data (user input and what so ever) in a production environment, as this is a security risk.
This won't work, the value won't get passed to the index this way:
} else {
$output = 2;
header('Location:index.php');
}
Your options (short of redesigning the way it works) are POST or GET;
} else {
$output = 2;
header('Location:index.php?sent=1');
}
Then in your index.php:
<?php
if (isset($_GET['sent']) && $_GET['sent'] == 1) {
echo "<b>Message has been sent</b>";
}
?>

multiple SQL insertion & form validation In 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. =)

Categories