I am studying an example of filling out a form.
https://github.com/sitepoint-editors/basic-form-validation-with-php/blob/main/index.php
And I can't figure out how to properly separate HTML and PHP code if I need to get the output of incorrectly filled fields on the same page.
I want to get something like that:
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Fruit Survey</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<h1>The World of Fruit</h1>
<h2>Fruit Survey</h2>
<form class="wrapper" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<label for="name">Name</label>
<div>
<input type="text"
name="name"
id="name"
value="<?php echo htmlspecialchars($values['name']);?>">
<?php if (in_array('name', $errors)): ?>
<span class="error">Missing</span>
<?php endif; ?>
</div>
<label for="address">Address</label>
<div>
<input type="text"
name="address"
id="address"
value="<?php echo htmlspecialchars($values['address']);?>">
<?php if (in_array('address', $errors)): ?>
<span class="error">Missing</span>
<?php endif; ?>
</div>
<label for="email">Email</label>
<div>
<input type="text"
name="email"
id="email"
value="<?php echo htmlspecialchars($values['email']);?>">
<?php if (in_array('email', $errors)): ?>
<span class="error">Missing</span>
<?php endif; ?>
</div>
<div class="field-label">How many pieces of fruit do you eat per day?</div>
<div>
<label>
<input type="radio"
name="howMany"
<?php if (isset($values['howMany']) && $values['howMany'] == "zero") echo "checked"; ?>
value="zero">
0
</label>
<label>
<input type="radio"
name="howMany"
<?php if (isset($values['howMany']) && $values['howMany'] == "one") echo "checked"; ?>
value="one">
1
</label>
<label>
<input type="radio"
name="howMany"
<?php if (isset($values['howMany']) && $values['howMany'] == "two") echo "checked"; ?>
value="two">
2
</label>
<label>
<input type="radio"
name="howMany"
<?php if (isset($values['howMany']) && $values['howMany'] == "twoplus") echo "checked"; ?>
value="twoplus">
More than 2
</label>
<?php if (in_array('howMany', $errors)): ?>
<span class="error">Missing</span>
<?php endif; ?>
</div>
<label for="favoriteFruit">My favourite fruit</label>
<div>
<select name="favoriteFruit[]" id="favoriteFruit" size="4" multiple="">
<?php
$options = ["apple", "banana", "plum", "pomegranate", "strawberry", "watermelon"];
foreach ($options as $option) {
printf(
'<option value="%s" %s>%s</option>',
$option,
(in_array($option, $values['favoriteFruit'])) ? "selected" : '',
ucfirst($option)
);
}
?>
</select>
<?php if (in_array('favoriteFruit', $errors)): ?>
<span class="error">Missing</span>
<?php endif; ?>
</div>
<label for="brochure">Would you like a brochure?</label>
<div>
<input type="checkbox"
name="brochure"
id="brochure"
<?php if (isset($values['brochure']) && $values['brochure'] == "Yes") echo "checked"; ?>
value="Yes">
</div>
<div>
<input type="submit" name="submit" value="Submit">
</div>
</form>
</body>
</html>
process.php
<?php
$errors = [];
$fields = ['name', 'address', 'email', 'howMany', 'favoriteFruit', 'brochure'];
$optionalFields = ['brochure'];
$values = [];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
foreach ($fields as $field) {
if (empty($_POST[$field]) && !in_array($field, $optionalFields)) {
$errors[] = $field;
} else {
$values[$field] = $_POST[$field];
}
}
if (empty($errors)) {
foreach ($fields as $field) {
if ($field === "favoriteFruit") {
printf("%s: %s<br />", $field, var_export($_POST[$field], TRUE));
} else {
printf("%s: %s<br />", $field, $_POST[$field]);
}
}
exit;
}
}
//MYSQL
require_once('db-connect.php');
$statement = $mysqli->prepare("INSERT INTO users_data (name, address, email, howMany, favoriteFruit, brochure) VALUES(?, ?, ?, ?, ?, ?)");
$statement->bind_param('ssssss', $name, $address, $email, $howMany, $favoriteFruit, $brochure);
if($statement->execute()){
print "Hello, " . $name . "!, your request has been sent!";
}else{
print $mysqli->error;
}
?>
But for that I need to replace <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> with <form method="post" action="process.php">
But then field validation and error output in the form does not work.
like this man
php:
<?php
$errors = [];
$fields = ['name', 'address', 'email', 'howMany', 'favoriteFruit', 'brochure'];
$optionalFields = ['brochure'];
$values = [];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
foreach ($fields as $field) {
if (empty($_POST[$field]) && !in_array($field, $optionalFields)) {
$errors[] = $field;
} else {
$values[$field] = $_POST[$field];
}
}
And what ever you put as a value in html forms
like this
<label for="favoriteFruit">My favorite fruit</label>
<div>
<select name="favoriteFruit[]" id="favoriteFruit" size="4" multiple="">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="plum">Plum</option>
<option value="pomegranate">Pomegranate</option>
<option value="strawberry">Strawberry</option>
<option value="watermelon">Watermelon</option>
</select>
</div>
<label>
<input type="radio" name="howMany" value="zero"> 0
</label>
<label>
<input type="radio" name="howMany" value="one"> 1
</label>
<label>
<input type="radio" name="howMany" value="two"> 2
</label>
<label>
<input type="radio" name="howMany" value="twoplus"> More than 2
</label>
<label for="name">Name</label>
<div>
<input type="text" name="name" id="name" value="">
</div>
<label for="address">Address</label>
<div>
<input type="text" name="address" id="address" value="">
</div>
<label for="email">Email</label>
<div>
<input type="text" name="email" id="email" value="">
</div>
Related
<!doctype html>
<?php
This is for setting cookies
//first failed attempt
if (isset($_POST['firstname']) != null || isset($_POST['lastname']) != null ||
isset($_POST['phonenumber']) != null || isset($_POST['email']) != null
|| isset($_POST['sulleyaddress']) != null || isset($_POST['question1']) != null
|| isset($_POST['question2']) != null || isset($_POST['question3']) != null
|| isset($_POST['question4']) != null || isset($_POST['question5']) != null) {
setcookie('firstname',$_POST['firstname']);
setcookie('lastname',$_POST['lastname']);
setcookie('phonenumber',$_POST['phonenumber']);
setcookie('email',$_POST['email']);
setcookie('sulleyaddress',$_POST['sulleyaddress']);
setcookie('question1',$_POST['question1']);
setcookie('question2',$_POST['question2']);
setcookie('question3',$_POST['question3']);
setcookie('question4',$_POST['question4']);
setcookie('question5',$_POST['question5']);
}
this is for reseting cookies
//second failed attempt
if (isset($_POST['firstname']) == null) {
setcookie('firstname','');
}
if (isset($_POST['lastname']) == null) {
setcookie('lastname','');
}
if (isset($_POST['phonenumber']) == null) {
setcookie('phonenumber','');
}
if (isset($_POST['email']) == null) {
setcookie('email','');
}
if (isset($_POST['sulleyaddress']) == null) {
setcookie('sulleyaddress','');
}
if (isset($_POST['question1']) == null) {
setcookie('question1','');
}
if (isset($_POST['question2']) == null) {
setcookie('question2','');
}
if (isset($_POST['question3']) == null) {
setcookie('question3','');
}
if (isset($_POST['question4']) == null) {
setcookie('question4','');
}
if (isset($_POST['question5']) == null) {
setcookie('question5','');
}
?>
<html>
<head>
<title>Assignment 2 - Anthony Taveras</title>
<style>#import url("css/styles.css");</style>
<!-- <link rel="stylesheet" href="styles.css" /> -->
</head>
<body>
<?php
1st step. Make the form appear. Allow user to enter and submit data.
if (!isset($_POST['submit'])) {
?>
<div id="content-container">
<div id="content">
<form name="form" id="form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<fieldset>
<legend>Please Fill Out the Form</legend>
<ol>
<li><input type="text" name="firstname" value="<?php if (isset($_COOKIE['firstname'])) {echo $_COOKIE['firstname'];} ?>" ><label> First Name</label></li>
<li><input type="text" name="lastname" value="<?php if (isset($_COOKIE['lastname'])) {echo $_COOKIE['lastname'];} ?>" ><label> Last Name</label></li>
<li><input type="text" name="phonenumber" value="<?php if (isset($_COOKIE['phonenumber'])) {echo $_COOKIE['phonenumber'];} ?>" ><label> Phone Number</label></li>
<li><input type="text" name="email" value="<?php if (isset($_COOKIE['email'])) {echo $_COOKIE['email'];} ?>" ><label> Email</label></li>
<li><input type="text" name="sulleyaddress" value="<?php if (isset($_COOKIE['sulleyaddress'])) {echo $_COOKIE['sulleyaddress'];} ?>" ><label> Sulley Address</label></li>
</ol>
</fieldset>
<fieldset>
<legend>Please answer these questions</legend>
<ol>
<li class="question"><input type="text" name="question1" value="<?php if (isset($_COOKIE['question1'])) {echo $_COOKIE['question1'];} ?>" ><label> What is your favorite color?</label></li>
<li class="question"><input type="text" name="question2" value="<?php if (isset($_COOKIE['question2'])) {echo $_COOKIE['question2'];} ?>" ><label> Where were you born?</label></li>
<li class="question"><input type="text" name="question3" value="<?php if (isset($_COOKIE['question3'])) {echo $_COOKIE['question3'];} ?>" ><label> What is your favorite food?</label></li>
<li class="question"><input type="text" name="question4" value="<?php if (isset($_COOKIE['question4'])) {echo $_COOKIE['question4'];} ?>" ><label> What is your favorite movie?</label></li>
<li class="question"><input type="text" name="question5" value="<?php if (isset($_COOKIE['question5'])) {echo $_COOKIE['question5'];} ?>" ><label> What is your favorite book?</label></li>
<li><input type="submit" name="submit" value="Submit" /></li>
</ol>
</fieldset>
</form>
</div>
</div>
2nd step once submitted user can view responses
<?php
} elseif (isset($_POST['submit'])) {
?>
<!--=============================================Form Preview--------------------------------------->
<div id="content-container">
<div id="content">
<h1> Here's what you put down</h1>
<p> First Name: <?php print $_POST['firstname']; ?> </p>
<p> Last Name: <?php print $_POST['lastname']; ?> </p>
<p> Phone Number: <?php print $_POST['phonenumber']; ?> </p>
<p> Email: <?php print $_POST['email']; ?> </p>
<p> Sulley Address: <?php print $_POST['sulleyaddress']; ?> </p>
<p class="question"> What is your favorite color? <?php print $_POST['question1']; ?> </p>
<p class="question"> Where were you born? <?php print $_POST['question2']; ?> </p>
<p class="question"> What is your favorite food? <?php print $_POST['question3']; ?> </p>
<p class="question"> What is your favorite movie? <?php print $_POST['question4']; ?> </p>
<p class="question"> What is your favorite book? <?php print $_POST['question5']; ?> </p>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="submit" name="edit" value="Edit" />
</form>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="submit" name="confirm" value="Finish" />
</form>
</div>
</div>
This is the problem area. This last step of the if else statement will not work properly. I'm not sure why. Any help is needed. Thanks.
<?php } elseif (isset($_POST['confirm'])) {
?>
<!--=============================================Form Confirmed--------------------------------------->
<div id="content-container">
<div id="content">
<p> Thank you, your data has been submitted</p>
</div>
</div>
<?php }
?>
</body>
</html>
You've got two form tags. One has the submit, one the hidden field.
You're not passing the variable therefore.
Try troubleshooting!
echo '<pre>';
print_r($_POST);
I would guess that it is because the forms are empty.
Try:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input id='placeholder' name='placeholder' type='text' value='placeholder' hidden>
<input type="submit" name="confirm" value="Finish" />
</form>
Here i have numerous input fields in a form, which are working perfectly. And now, i want to add new input boxes and their labels according to property_type , Which is already exist on this page.
Now, Kindly Suggest me How can i add new fields in that form.
Here is my Form Code
<div class="dashboard_price_left">
<h3>
<?php
if ($this->lang->line('BasePrice') != '') {
echo stripslashes($this->lang->line('BasePrice'));
} else
echo "Base Price";
?>
</h3>
<p>
<?php
if ($this->lang->line('Atitleandsummary') != '') {
echo stripslashes($this->lang->line('Atitleandsummary'));
} else
echo "Set weekly or monthly price guests will see for your listing.";
?>
</p>
</div>
<?php
if ($listDetail->row()->home_type == 'Office') {
} else if ($listDetail->row()->home_type == 'House') {
}
?>
<form id="pricelist" name="pricelist" action="site/product/savePriceList" method="post">
<div class="dashboard_price_right">
<label><?php
if ($this->lang->line('Pernight') != '') {
echo stripslashes($this->lang->line('Pernight'));
} else
echo "Per night";
?>
</label>
<div class="amoutnt-container">
<?php if ($currentCurrency == '') { ?>
<span class="WebRupee"><?php echo $currencyDetail->row()->currency_symbols; ?></span>
<?php } else { ?>
<span class="WebRupee"><?php echo $currentCurrency; ?></span>
<?php } ?>
<input type="text" id="price" value="<?php
if ($listDetail->row()->price != '0.00') {
echo intval($listDetail->row()->price);
}
?>" class="per_amount_scroll" name="price" onkeypress="return onlyNumbersWithDot(event);" onchange="javascript:Detailview(this,<?php echo $listDetail->row()->id; ?>, 'price');" />
<input type="hidden" id="id" name="id" value="<?php echo $listDetail->row()->id; ?>" />
</div>
<div class="dashboard_currency">
<label><?php
if ($this->lang->line('Currency') != '') {
echo stripslashes($this->lang->line('Currency'));
} else
echo "Currency";
?>
</label>
<div class="select select-large select-block">
<select name="currency" id="currency" onchange="javascript:Detailview(this,<?php echo $listDetail->row()->id; ?>, 'currency');get_currency_symbol(this)" >
<!--<option value="">select</option>-->
<?php foreach ($currencyDetail->result() as $currency) { ?>
<option value="<?php echo $currency->currency_type; ?>" <?php if ($listDetail->row()->currency == $currency->currency_type) echo 'selected="selected"'; ?>><?php echo $currency->currency_type; ?></option>
<?php } ?>
</select>
</div>
</div>
</div>
</form>
Here is a pic of my Property prices form
Note: There are two types of property that are following:
1. Office
2. House
on the basis of these property, I want to add more fields in my form.
Please suggest me, Thanks in Advance :)
you can change it base on conditon and pass hidden field which indicates you office or house.
<?php
if ($listDetail->row()->home_type == 'Office')
{
<input type="hidden" name="home_type" value="Office" />
<input type="text" name="per_day" value="" />
<input type="text" name="half_day" value="" />
<input type="text" name="per_hour" value="" />
}
else if ($listDetail->row()->home_type == 'House')
{
<input type="hidden" name="home_type" value="House" />
<input type="text" name="per_night" value="" />
<input type="text" name="per_day" value="" />
<input type="text" name="per_hour" value="" />
}
?>
My code is:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SomuFinance - Personal Finance Manager</title>
<link rel="stylesheet" type="text/css" href="indexStyle.css">
<script src="scripts/jquery-3.1.0.min.js"></script>
<script type="text/javascript" src="scripts/jquery.validate.min.js"></script>
<style type="text/css">
#addItemContainer {
background-color: rgba(204,207,232,1);
}
</style>
<script type="text/javascript">
var flag=0;
</script>
</head>
<body>
<form id="list" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<div id="container">
<input type="submit" class="button" name="edit" id="edit" value="Edit" />
<input type="button" class="button" name="delete" value="Delete" />
<input type="hidden" id="action" name="action">
<table id="listDB">
<tr>
<th>Select</th>
<th>ID</th>
<th>Category ID</th>
<th>Shop</th>
<th>Item</th>
<th>Quantity</th>
<th>Unit</th>
<th>Price Based On</th>
<th>MRP</th>
<th>Seller's Price</th>
<th>Last Updated On</th>
</tr>
<?php
$dbc = mysqli_connect('localhost','root','atlantis2016','itemDB')
or die("Error Connecting to Database");
if(isset($_POST['confirmDelete']))
{
if($_POST['action']=='confirmDelete')
{
foreach ($_POST['selected'] as $delete_id)
{
$query = "DELETE FROM grocery WHERE id = $delete_id";
mysqli_query($dbc, $query)
or die('Error querying database.');
}
}
}
$query1 = "SELECT DISTINCT category FROM grocery";
$result1 = mysqli_query($dbc, $query1)
or die("Error Querying Database");
while($row = mysqli_fetch_array($result1))
{
$category = $row['category'];
$query2 = "SELECT * FROM grocery WHERE category='$category' ORDER BY item ASC";
$result2 = mysqli_query($dbc, $query2)
or die("Error Querying Database");
echo '<tr>';
echo '<td class="catHead" colspan=11>'.$category.'</td>';
echo '</tr>';
$catCount=1;
while($inRow = mysqli_fetch_array($result2))
{
$id = $inRow['id'];
$shop = $inRow['shop'];
$item = $inRow['item'];
$qnty = $inRow['quantity'];
$unit = $inRow['unit'];
$price_based_on = $inRow['price_based_on'];
$mrp = $inRow['MRP'];
$sellers_price = $inRow['sellers_price'];
$last_updated_on = $inRow['last_updated_on'];
echo '<tr>';
echo '<td><input type="checkbox" id="selected" value="' . $id . '" name="selected[]" /></td>';
echo '<td>'.$id.'</td>';
echo '<td>'.$catCount.'</td>';
echo '<td>'.$shop.'</td>';
echo '<td class="leftAligned">'.$item.'</td>';
echo '<td>'.$qnty.'</td>';
echo '<td>'.$unit.'</td>';
echo '<td>'.$price_based_on.'</td>';
echo '<td class="pri">₹'.$mrp.'</td>';
echo '<td class="pri">₹'.$sellers_price.'</td>';
echo '<td>'.$last_updated_on.'</td>';
echo '</tr>';
$catCount++;
}
}
?>
</table>
</div>
<div class="dialogBG">
<div id="deleteConfirmDialog" class="dialog">
<div class="closeDialog"></div>
<p>Sure you want to delete the selected Data?</p>
<input type="submit" id="confirmDelete" class="dialogButton" name="confirmDelete" value="Delete" />
<input type="button" id="cancelDelete" class="dialogButton cancelButton" name="cancelDelete" value="Cancel" />
</div>
</div>
</form>
<div class="dialogBG">
<div id="addItemContainer" class="dialog">
<div class="closeDialog"></div>
<h1>Edit Item</h1>
<form id="data" method="post" action="<?php $_SERVER['PHP_SELF']; ?>">
<?php
if(isset($_POST['action']))
{
if($_POST['action']=='edit')
{
echo '<script>flag=1;</script>';
foreach ($_POST['selected'] as $edit_id)
{
$query = "SELECT * FROM grocery WHERE id = $edit_id";
$result = mysqli_query($dbc, $query)
or die('Error querying database.');
break;
}
$inRow = mysqli_fetch_array($result);
$id = $inRow['id'];
$shop = $inRow['shop'];
$category = $inRow['category'];
$item = $inRow['item'];
$qnty = $inRow['quantity'];
$unit = $inRow['unit'];
$price_based_on = $inRow['price_based_on'];
$mrp = $inRow['MRP'];
$sellers_price = $inRow['sellers_price'];
$last_updated_on = $inRow['last_updated_on'];
}
}
?>
<div class="leftAligned">
<div class="inp">
<label for="shop">ID : </label>
<input type="text" id="id" name="id" value="<?php echo $id; ?>" required disabled>
</div> <br>
<div class="inp">
<label for="shop">Shop : </label>
<input type="text" id="shop" name="shop" value="<?php echo $shop; ?>" required>
</div> <br>
<div class="inp">
<label for="category">Category : </label>
<input type="text" id="category" name="category" value="<?php echo $category; ?>" required>
</div> <br>
<div class="inp">
<label for="item">Item : </label>
<input type="text" id="item" name="item" value="<?php echo $item; ?>" required>
</div> <br>
<div class="inp">
<label for="qnty">Quantity : </label>
<input type="text" id="qnty" name="qnty" value="<?php echo $qnty; ?>" required>
</div> <br>
<div class="inp">
<label for="unit">Unit : </label>
<input type="text" id="unit" name="unit" value="<?php echo $unit; ?>" required>
</div> <br>
<div class="inp">
<label for="price_based_on">Price based on : </label>
<select name="price_based_on" id="price_based_on">
<option value="kilos">Kilos</option>
<option value="packet">Packet</option>
<option value="bottle">Bottle</option>
<option value="box">Box</option>
<option value="piece">Piece</option>
</select>
</div> <br>
<div class="inp">
<label for="mrp">MRP (₹) : </label>
<input type="text" id="mrp" name="mrp" value="<?php echo $mrp; ?>" required>
</div> <br>
<div class="inp">
<label for="sellers_price">Seller's Price (₹) : </label>
<input type="text" id="sellers_price" value="<?php echo $sellers_price; ?>" name="sellers_price" required>
</div> <br>
<div class="inp">
<label for="last_updated_on">Last Updated on : </label>
<input type="date" id="last_updated_on" name="last_updated_on" value="<?php echo $last_updated_on; ?>" required>
</div>
</div>
<div class="inp">
<input id="insertButton" type="submit" name="submit" value="Insert">
</div>
<div id="message">
<?php
if(isset($_POST['submit']))
{
echo "<script> alert('$id'); </script>";
$shop = $_POST['shop'];
$category = $_POST['category'];
$item = $_POST['item'];
$qnty = $_POST['qnty'];
$unit = $_POST['unit'];
$price_based_on = $_POST['price_based_on'];
$mrp = $_POST['mrp'];
$sellers_price = $_POST['sellers_price'];
$last_updated_on = $_POST['last_updated_on'];
$result=null;
$query = "UPDATE grocery SET shop='$shop', category='$category', item='$item', quantity='$qnty', unit='$unit', price_based_on='$price_based_on', mrp='$mrp', sellers_price='$sellers_price', last_updated_on='$last_updated_on' WHERE id='$id'";
if(!empty($shop)&&!empty($category)&&!empty($item)&&is_numeric($qnty)&&!empty($unit)&&is_numeric($mrp)&&is_numeric($sellers_price)&&!empty($last_updated_on))
{
$result = mysqli_query($dbc, $query)
or die(mysqli_error($dbc));
}
if($result)
{
echo '<span class="success">Item Edited Successfully!</span>';
}
else
{
echo '<span class="failure">Failed to insert Item.</span>';
}
//header("Refresh:2");
}
?>
<script>
$(document).ready(function(){
$( "#data" ).validate({
rules: {
qnty: {
number: true
},
mrp: {
number: true
},
sellers_price: {
number: true
}
},
messages: {
qnty : {
number: '<br> <span class="failure err">Enter a valid quantity</span>'
},
mrp : {
number: '<br> <span class="failure err">Enter a valid MRP</span>'
},
sellers_price : {
number: '<br> <span class="failure err">Enter a valid Price</span>'
},
}
});
});
</script>
</div>
</form>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('.button').click(function(event){
if($(this).val()=="Delete")
{
$("#deleteConfirmDialog").show(200).parent(".dialogBG").fadeIn(200);
$("#action").val('confirmDelete');
}
else if($(this).val()=="Edit")
{
event.preventDefault();
$("#action").val('edit');
$("#list").submit();
}
});
if(flag===1)
{
console.log("This shouldn't be there if the page reloads!");
$("#addItemContainer").show(200).parent(".dialogBG").fadeIn(200);
}
$('#confirmDelete').click(function(){
$(".closeDialog").trigger("click");
});
$('#cancelDelete').click(function(){
$("input:checkbox[name='selected[]']").prop('checked', false);
});
$(".closeDialog").click(function (e){
$(this).parent(".dialog").hide('200').parent(".dialogBG").fadeOut('200');
});
$(".cancelButton").click(function (e){
$(this).parent(".dialog").hide('200').parent(".dialogBG").fadeOut('200');
});
});
</script>
<?php
mysqli_close($dbc);
?>
</body>
</html>
Notice that I obtain the id of the first selected element by using the lines:
foreach ($_POST['selected'] as $edit_id)
{
$query = "SELECT * FROM grocery WHERE id = $edit_id";
$result = mysqli_query($dbc, $query)
or die('Error querying database.');
break;
}
$inRow = mysqli_fetch_array($result);
$id = $inRow['id'];
Now, I use the id(which is exactly the same as edit_id) thus obtained to access the record in the DB, and show it in the popup.
<div class="leftAligned">
<div class="inp">
<label for="shop">ID : </label>
<input type="text" id="id" name="id" value="<?php echo $id; ?>" required disabled>
</div> <br>
<div class="inp">
<label for="shop">Shop : </label>
<input type="text" id="shop" name="shop" value="<?php echo $shop; ?>" required>
</div> <br>
<div class="inp">
<label for="category">Category : </label>
<input type="text" id="category" name="category" value="<?php echo $category; ?>" required>
</div> <br>
<div class="inp">
<label for="item">Item : </label>
<input type="text" id="item" name="item" value="<?php echo $item; ?>" required>
</div> <br>
<div class="inp">
<label for="qnty">Quantity : </label>
<input type="text" id="qnty" name="qnty" value="<?php echo $qnty; ?>" required>
</div> <br>
<div class="inp">
<label for="unit">Unit : </label>
<input type="text" id="unit" name="unit" value="<?php echo $unit; ?>" required>
</div> <br>
<div class="inp">
<label for="price_based_on">Price based on : </label>
<select name="price_based_on" id="price_based_on">
<option value="kilos">Kilos</option>
<option value="packet">Packet</option>
<option value="bottle">Bottle</option>
<option value="box">Box</option>
<option value="piece">Piece</option>
</select>
</div> <br>
<div class="inp">
<label for="mrp">MRP (₹) : </label>
<input type="text" id="mrp" name="mrp" value="<?php echo $mrp; ?>" required>
</div> <br>
<div class="inp">
<label for="sellers_price">Seller's Price (₹) : </label>
<input type="text" id="sellers_price" value="<?php echo $sellers_price; ?>" name="sellers_price" required>
</div> <br>
<div class="inp">
<label for="last_updated_on">Last Updated on : </label>
<input type="date" id="last_updated_on" name="last_updated_on" value="<?php echo $last_updated_on; ?>" required>
</div>
</div>
The ID and all the relevant details thus far are exactly as they should be.
However, further down, when I try to use the ID to update the record, using the statement
UPDATE grocery SET shop='$shop', category='$category', item='$item',
quantity='$qnty', unit='$unit', price_based_on='$price_based_on',
mrp='$mrp', sellers_price='$sellers_price',
last_updated_on='$last_updated_on'
WHERE id='$id'
somehow the id has changed to the last value of id in the table. So, instead of updating the table's correct record with the updated values, since the id "magically" changes at this point (after the sumbit button has been pressed), the last value of the id appears. I want the id to stay the same as the original id.
Why is this happening and how can I solve this?
Im doing a registration form and I have to enter the information in to 3 tables in mysql. I have tried a few things but cant seem to get it right. This is what I have so far. My registration form looks as follows:
function fix($str){
$str = trim($str);
$str = stripslashes($str);
return $str;
}
if($_POST['submit'])
{
$first = fix($_POST['firstName']);
$last = fix($_POST['lastName']);
$email = fix($_POST['email']);
$userName = fix($_POST['userName']);
$passWord = fix($_POST['passWord']);
$reTyped = fix($_POST['confPassword']);
$secA = $_POST['secA'];
$secQ = $_POST['secQ'];
require_once('user_registration.php');
}
?>
<!DOCTYPE, Head, Body & Nav here>
<div class="account-container register">
<div class="content clearfix">
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="POST">
<h1>New User Registration</h1>
<div class="login-fields">
<div class="field">
<label for="firstName">First Name:</label>
<input type="text" id="firstName" name="firstName" placeholder="First Name" class="login" />
</div> <!-- /field -->
<div class="field">
<label for="lastName">Last Name:</label>
<input type="text" id="lastName" name="lastName" placeholder="Last Name" class="login" />
</div> <!-- /field -->
<div class="field">
<label for="userName">User Name:</label>
<input type="text" id="userName" name="userName" placeholder="User Name" class="login" />
</div><!-- /field -->
<div class="field">
<label for="email">Email Address:</label>
<input type="text" id="email" name="email" placeholder="Email" class="login" />
</div> <!-- /field -->
<div class="field">
<label for="passWord">Password:</label>
<input type="password" id="passWord" name="passWord" placeholder="Password" class="login" />
</div> <!-- /field -->
<div class="field">
<label for="confPassword">Confirm Password:</label>
<input type="password" id="confPassword" name="confPassword" placeholder="Confirm Password" class="login" />
</div><!--field-->
<div class="field">
<label for="secQ">Security Question</label>
<select name="secQ" id="secQuestion" placeholder="Security" class="dropdown">
<option value="No Selection"
<?php if(!$_POST || $_POST['secQ'] == 'No Selection')
{ echo 'selected'; }?>>--Select A Security Question--</option>
<option value="0"
<?php if(!$_POST || $_POST['secQ'] == '0')
{ echo 'selected'; }?>>What is your mothers maiden name</option>
<option value="1"
<?php if(!$_POST || $_POST['secQ'] == '1')
{ echo 'selected'; }?>>In what city were you born</option>
<option value="2"
<?php if(!$_POST || $_POST['secQ'] == '2')
{ echo 'selected'; }?>>What is your favorite color</option>
<option value="3"
<?php if(!$_POST || $_POST['secQ'] == '3')
{ echo 'selected'; }?>>What year did you graduate HighSchool</option>
<option value="4"
<?php if(!$_POST || $_POST['secQ'] == '4')
{ echo 'selected'; }?>>What is the name of your first boy/girl friend</option>
<option value="5"
<?php if(!$_POST || $_POST['secQ'] == '5')
{ echo 'selected'; }?>>What was the name of your first pet</option>
<option value="6"
<?php if(!$_POST || $_POST['secQ'] == '6')
{ echo 'selected'; }?>>What street did you grow up on</option>
</select>
</div>
<div class="field">
<label for="secA">Security Answer</label>
<input type="text" id="secA" name="secA" placeholder="Answer" class="login" />
</div>
</div> <!-- /login-fields -->
<div class="login-actions">
<span class="login-checkbox">
<input id="Field" name="terms" type="checkbox" class="field login-checkbox" value="First Choice" tabindex="4" />
<label class="choice" for="Field">Agree with the Terms & Conditions.</label>
</span>
<input type="submit" id="register" name="submit" class="button btn btn-primary btn-large" value="Register" />
</div> <!-- .actions -->
</form>
</div> <!-- /content -->
Then the PHP page I have attached to the form as noted in the first "if" statement is the following - user_registration.php:
<?php
require_once('includes/checkPassword.php');
$usernameMinChars = 6;
$errors = array();
if (strlen($userName) < $usernameMinChars)
{
$errors[] = "Username must be at least $usernameMinChars characters.";
}
if (preg_match('/\s/', $userName))
{
$errors[] = 'Username should not contain spaces.';
}
$checkPwd = new CheckPassword($passWord);
$checkPwd->requireMixedCase();
$passwordOK = $checkPwd->check();
if (!$passwordOK) {
$errors[] = array_merge($errors, $checkPwd->getErrors());
}
if ($passWord != $reTyped) {
$errors[] = "Your passwords don't match.";
}
if (!$errors) {
//include connection file
require('includes/usrConnect.php');
$conn = dbConnect('write');
//create salt using current timestamp
$salt = SALT .time();
//encrypt pwd with salt
$hashword = sha1($passWord . $salt);
//prepare sql statement
$sql = "INSERT INTO User (User_Name) VALUES('$userName')";
$sql .= "INSERT INTO User_Parameter (User_Identity, User_Password, User_Salt) VALUES('$User_Identity', '$hashword', '$salt')";
$sql .= "INSERT INTO User_Profile (User_Identity, Profile_FirstName, Profile_LastName, Profile_Email, Profile_Question, Profile_Answer)
VALUES('$User_Identity', '$first', '$last', '$email', '$secQ', '$secA')";
if($stmt = $conn->query($sql))
{
$User_Identity = $stmt->insert_id;
do{
if($result = $conn->affected_rows())
{
while ($result > 0)
{
$success = 'User successfully created '.$User_Identity;
header('Location: login.php');
}
} $result->free();
}while($conn->next_result());
}
elseif($stmt->errno == 1062)
{
$errors[] = "$userName already exists, Please select another username.";
}else{
$errors[] = 'Sorry, there was a problem processing your request.';
}
}
?>
The problem is that I have 3 tables to insert the information in to. User(for the user_name), User_Parameter(for the password & salt), & User_Profile(for the name, email, & security question / answer).
I just cant figure out how to do the queries correctly. I have tried it this way and I have also tried naming each query something different and can't get it nested correctly in order to correctly get the User_Identity from the first insert in order to input the information in the other queries. Can anyone help?
I think you must execute these 3 queries separately, it actually will work.
$conn->query("INSERT INTO User (User_Name) VALUES('$userName')");
$conn->query("INSERT INTO User_Parameter (User_Identity, User_Password, User_Salt) VALUES('$User_Identity', '$hashword', '$salt')");
$stmt = $conn->query("INSERT INTO User_Profile (User_Identity, Profile_FirstName, Profile_LastName, Profile_Email, Profile_Question, Profile_Answer) VALUES('$User_Identity', '$first', '$last', '$email', '$secQ', '$secA')");
if ($stmt) {
// then your code goes
}
I think just complete this three tables into one.
and using one insert query
I've got a slight problem with my CI2.0.2 application.
From what I can tell, it is not getting any post data from a form and so is failing to run an update function, though most pages work fine.
The form is as follows:
<?php echo form_open('job/update/', array('id' => 'update', 'name' => 'update')); ?>
<div class="images">
<?php echo img('application/images/updateJob.png');?>
</div>
<h1>Update Job</h1>
<br><br><br><br>
<div class="fieldset">
<?php
if (isset($error))
{
echo '<div id ="error">';
echo '<h2>Error:</h2>';
echo '<p>'.$error.'</p>';
echo '</div>';
}
?>
<input type="hidden" name="c" id='c' value="<?php if(!empty($view[0])) { echo $view[0]; } else { echo "0"; } ?>">
<div class="left">
<h4>Job Details:</h4>
<div>
<label for="job_number">Job No:</label>
<input type="text" name="job_number" id="job_number" value="<?php echo $job['jobno']; ?>" disabled="disabled">
</div>
<div>
<label for="date">Date:</label>
<input type="text" name="date" id="date" value="<?php echo $job['datetime']->format('d-M-Y'); ?>">
</div>
<div>
<label for="council">Council:</label>
<input type="text" name="council" id="council" value="<?php echo htmlspecialchars($job['council']); ?>"> *
</div>
<div>
<label for="dano">DA No:</label>
<input type="text" name="dano" id="dano" value="<?php echo htmlspecialchars($job['dano']); ?>">
</div>
<div>
<label for="client">Client:</label>
<input type="text" name="client" id="client" value="<?php echo $job['clientid']; ?>" disabled="disabled">
</div>
</div>
<div class="right" style="margin-left: 390px;">
<h4>Location:</h4>
<label for="street_no">Street No:</label>
<input type="text" name="street_no" id="street_no" value="<?php echo $address['streetno']; ?>"> *
<br>
<label for="street_name">Street Name:</label>
<input type="text" name="street_name" id="street_name" value="<?php echo $address['streetname']; ?>"> *
<br>
<label for="street_type">Street Type:</label>
<select name="street_type" id="street_type">
<?php
foreach ($street_types as $type)
{
echo '<option';
if ($type == $address['streettype']) echo ' selected="selected"';
echo '>'.$type.'</option>';
}
?>
</select> *
<br>
<label for="suburb">Suburb:</label>
<input type="text" name="suburb" id="suburb" value="<?php echo $address['suburb']; ?>"> *
<br>
<label for="postcode">Postcode:</label>
<input type="text" name="postcode" id="postcode" value="<?php echo $address['postcode']; ?>"> *
<br>
<label for="state">State:</label>
<input type="text" name="state" id="state" value="<?php echo $address['state']; ?>"> *
<br>
<label for="country">Country:</label>
<input type="text" name="country" id="country" value="<?php echo $address['country']; ?>">
<br>
<label for="dp">DP:</label>
<input type="text" name="dp" id="dp" value="<?php echo $address['dp']; ?>">
<br>
<label for="lot_no">Lot No:</label>
<input type="text" name="lot_no" id="lot_no" value="<?php echo $address['lotno']; ?>">
<br>
<label for="po_box">PO Box:</label>
<input type="text" name="po_box" id="po_box" value="<?php echo $address['pobox']; ?>">
</div>
<div>
<input type="submit" id="submit" name="submit" value="Submit" class="button">
<p>* = Required fields</p>
</div>
</div>
<?php echo form_close();?>
And the update section of the controller is as follows:
/**
* Update an existing job.
* #param int $job_number The number of the job to update.
*/
public function update($job_number=0)
{
$this->load->model('Job_model');
$job = array();
$address = array();
// Get post data.
$job['joblocation'] = '';
$job['jobno'] = $this->input->post('job_number');
$job['datetime'] = new DateTime($this->input->post('date'));
$job['dano'] = $this->input->post('dano');
$job['council'] = $this->input->post('council');
echo $job['jobno'];
echo $job['dano'];
echo $job['council'];
$address['streetno'] = $this->input->post('street_no');
$address['streetname'] = $this->input->post('street_name');
$address['suburb'] = $this->input->post('suburb');
$address['country'] = $this->input->post('country');
$address['postcode'] = $this->input->post('postcode');
$address['state'] = $this->input->post('state');
$address['dp'] = $this->input->post('dp');
$address['lotno'] = $this->input->post('lot_no');
$address['pobox'] = $this->input->post('po_box');
$address['streettype'] = $this->input->post('street_type');
echo "here2";
if (isset($_POST['submit']))
{
$this->Job_model->update($job);
echo "here";
redirect('job/');
}
// Otherwise, get the data from the database.
else
{
$job = $this->Job_model->search($job_number);
$job = $job[0];
$job['datetime'] = new DateTime($job['datetime']);
$address = $this->Job_model->get_address($job['joblocation']);
$address = $address[0];
}
// Get the street types.
$street_types = array();
$this->load->model('staff_model');
$streets = $this->staff_model->get_street_types();
foreach ($streets as $street)
{
$street_types[$street['streettype']] = $street['streettype'];
}
// Load the client list.
$clients = array();
$this->load->model('client_model');
$people = $this->client_model->get_client_person_list();
$companies = $this->client_model->get_client_company_list();
// Allocate view data.
$viewdata = array();
$viewdata['job'] = $job;
$viewdata['street_types'] = $street_types;
$viewdata['address'] = $address;
$viewdata['people'] = $people;
$viewdata['companies'] = $companies;
$this->layout->view('job/update', $viewdata);
}
Any ideas why this might be happening?
Thanks in advance,
James
Try changing the quotes you're using on this line:
<input type="hidden" name="c" id='c' value="<?php if(!empty($view[0])) { echo $view[0]; } else { echo '0'; } ?>" />
The way you had it with the double quotes around the 0 you were breaking that php because the first one would be closing the opening value quote.