How to make form values remain in form - php

I'm developing a simple PHP website. I have a form for updating values. When that form is accessed via PHP(website) , It should have previous values, But it hasn't. How to do that ?
Because, Otherwise, It shows all fields empty and when one or two are updated, Other gets updated as empty. Please help !
<?php
require_once('../includes/config.php');
require_once('../includes/functions.php');
require_once('../includes/session.php');
require_once('../includes/database.php');
require_once('../includes/user.php');
require_once('../includes/photograph.php');
if (!$session->is_logged_in()) { redirect_to("login.php"); }
?>
<?php
// START FORM PROCESSING
if (isset($_POST['submit'])) { // Form has been submitted.
$errors = array();
// perform validations on the form data
$required_fields = array('lives_in', 'belongs_to', 'college', 'works_at', 'grade', 'grade2', 'hobbies', 'zodiac', 'phone_no', 'facebook', 'company', 'bio');
$errors = array_merge($errors, check_required_fields($required_fields, $_POST));
$lives_in = trim($database->escape_value($_POST['lives_in']));
$belongs_to = trim($database->escape_value($_POST['belongs_to']));
$college = trim($database->escape_value($_POST['college']));
$works_at = trim($database->escape_value($_POST['works_at']));
$grade = trim($database->escape_value($_POST['grade']));
$grade2 = trim($database->escape_value($_POST['grade2']));
$hobbies = trim($database->escape_value($_POST['hobbies']));
$zodiac = trim($database->escape_value($_POST['zodiac']));
$phone_no = trim($database->escape_value($_POST['phone_no']));
$facebook = trim($database->escape_value($_POST['facebook']));
$company = trim($database->escape_value($_POST['company']));
$bio = trim($database->escape_value($_POST['bio']));
if (empty($errors) ) {
$query = "UPDATE users
SET lives_in = '{$lives_in}',
belongs_to = '{$belongs_to}',
college = '{$college}' ,
works_at = '{$works_at}',
grade = '{$grade}',
grade2 = '{$grade2}',
hobbies = '{$hobbies}',
zodiac = '{$zodiac}',
phone_no = '{$phone_no}',
facebook = '{$facebook}',
company = '{$company}',
bio = '{$bio}'
WHERE id = 23
LIMIT 1";
$result = mysql_query($query, $database->connection);
if ($result) {
$message = "Account Updated";
} else {
$message = mysql_error();
}
} else {
if (count($errors) == 1) {
$message = mysql_error();;
} else {
$message = "There were " . count($errors) . " errors in the form.";
}
}
} else { // Form has not been submitted.
$lives_in = "";
$belongs_to = "";
$college = "";
$works_at = "";
$grade = "";
$grade2 = "";
$hobbies = "";
$zodiac = "";
$phone_no = "";
$facebook = "";
$company = "";
$bio = "";
}
?>

It's very easy, just print out the previous values in the form when you create it with php.
For example:
<input type="text" name="field_name" value="<?php echo $previous_value;?>" />
Or, if it's a select, let's say:
<select name="field_name">
<?php foreach($posible_values as $value){ ?>
<option value="<?php echo $value;?>"
<?php echo ($value==$previous_value)?'selected="selected"':'';?> >
<?echo $value?>
</option>
<?php } ?>
</select>

Related

Insert into database using excel from database start from col 2

I`m trying to insert data into a database, from an excel file but starting from column 2 because the first column is being used for the name of the row in the table.
This is my form to input the file, this code reads from the first column, I want to start reading from column 2.
<h2>Import Excel File into MySQL Database using PHP</h2>
<div class="outer-container">
<form action="import.php" method="post"
name="frmExcelImport" id="frmExcelImport" enctype="multipart/form-data">
<div>
<label>Choose Excel
File</label> <input type="file" name="file"
id="file" accept=".xls,.xlsx">
<button type="submit" id="submit" name="import"
class="btn-submit">Import</button>
</div>
</form>
</div>
<div id="response" class="<?php if(!empty($type)) { echo $type . " display-block"; } ?>"><?php if(!empty($message)) { echo $message; } ?></div>
and this is the action file:
<?php
include 'koneksi/koneksi.php';
require_once('vendor/php-excel-reader/excel_reader2.php');
require_once('vendor/SpreadsheetReader.php');
if (isset($_POST["import"]))
{
$allowedFileType = ['application/vnd.ms-excel','text/xls','text/xlsx','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
if(in_array($_FILES["file"]["type"],$allowedFileType)){
$targetPath = 'uploads/'.$_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], $targetPath);
$Reader = new SpreadsheetReader($targetPath);
$sheetCount = count($Reader->sheets());
for($i=0;$i<$sheetCount;$i++)
{
$Reader->ChangeSheet($i);
foreach ($Reader as $Row )
{
$id_koperasi = "";
if(isset($Row[0])) {
$id_koperasi = mysqli_real_escape_string($con,$Row[0]);
}
$nama_koperasi = "";
if(isset($Row[1])) {
$nama_koperasi = mysqli_real_escape_string($con,$Row[1]);
}
$alamat = "";
if(isset($Row[2])) {
$alamat = mysqli_real_escape_string($con,$Row[2]);
}
$telp = "";
if(isset($Row[3])) {
$telp = mysqli_real_escape_string($con,$Row[3]);
}
$hp = "";
if(isset($Row[4])) {
$hp = mysqli_real_escape_string($con,$Row[4]);
}
$nama_cp = "";
if(isset($Row[5])) {
$nama_cp = mysqli_real_escape_string($con,$Row[5]);
}
$email = "";
if(isset($Row[6])) {
$email = mysqli_real_escape_string($con,$Row[6]);
}
$tanggal_fu = "";
if(isset($Row[7])) {
$tanggal_fu = mysqli_real_escape_string($con,$Row[7]);
}
$ket_fu = "";
if(isset($Row[8])) {
$ket_fu = mysqli_real_escape_string($con,$Row[8]);
}
$hasil_pembahasan = "";
if(isset($Row[9])) {
$hasil_pembahasan = mysqli_real_escape_string($con,$Row[9]);
}
$status = "";
if(isset($Row[10])) {
$status = mysqli_real_escape_string($con,$Row[10]);
}
$provinsi = "";
if(isset($Row[11])) {
$provinsi = mysqli_real_escape_string($con,$Row[11]);
}
$kota = "";
if(isset($Row[12])) {
$kota = mysqli_real_escape_string($con,$Row[12]);
}
$kec = "";
if(isset($Row[13])) {
$kec = mysqli_real_escape_string($con,$Row[13]);
}
$kel = "";
if(isset($Row[14])) {
$kel = mysqli_real_escape_string($con,$Row[14]);
}
$rt = "";
if(isset($Row[15])) {
$rt = mysqli_real_escape_string($con,$Row[15]);
}
$rw = "";
if(isset($Row[16])) {
$rw = mysqli_real_escape_string($con,$Row[16]);
}
$jln = "";
if(isset($Row[17])) {
$jln = mysqli_real_escape_string($con,$Row[17]);
}
$kodep = "";
if(isset($Row[18])) {
$kodep = mysqli_real_escape_string($con,$Row[18]);
}
if (!empty($id_koperasi) || !empty($nama_koperasi) || !empty($alamat) || !empty($telp) || !empty($hp) || !empty($nama_cp) || !empty($email) || !empty($tanggal_fu) || !empty($ket_fu) || !empty($hasil_pembahasan) || !empty($status) || !empty($provinsi) || !empty($kota) || !empty($kec) || !empty($kel) || !empty($rt) || !empty($rw) || !empty($jln) || !empty($kodep) ) {
$query = "INSERT INTO t_koperasi(id,id_koperasi,nama_koperasi,alamat,telp,hp,nama_cp,email,tanggal_fu,ket_fu,hasil_pembahasan,status,provinsi,kota,kec,kel,rt,rw,jln,kodep) VALUES ('',
'$id_koperasi',
'$nama_koperasi',
'$alamat',
'$telp',
'$hp',
'$nama_cp',
'$email',
'$tanggal_fu',
'$ket_fu',
'$hasil_pembahasan',
'$status',
'$provinsi',
'$kota',
'$kec',
'$kel',
'$rt',
'$rw',
'$jln',
'$kodep')" or die(mysqli_error($con));
;
$result = mysqli_query($con, $query);
if (! empty($result)) {
$type = "success";
$message = "SUKSES";
} else {
$type = "error";
$message = "Problem in Importing Excel Data";
}
}
}
}
}
else
{
$type = "error";
$message = "Invalid File Type. Upload Excel File.";
}
}
include 'views/v_import.php'
?>
I already tried to put $col = 1 but it still wont work, I tried using the for=i but it still will not work.
a possible solution with an extra counter
$Reader->ChangeSheet($i);
$number = 0;
foreach ($Reader as $Row )
{
if ($number!=0) {
......
}
$number++;
}

PHP Form Processing Multiple Checkboxes

So i've got a table full of data. I have a page where i list all the contents of that able out through a while loop. Then the user can click a button on a record and it will generate an address label using the data it has and the generated label is done in a PDF. So that all works fine and dandy. However i was wondering is it possible to replace that button with an HTML Checkbox for each record to something like this
<input type="checkbox" name="<?php echo $recordTitle; ?>" />
<input type="hidden" name="<?php echo $recordID"; ?>" />
So this would allow people to select multiple records and then click one button and it would take all of those records and generate as many labels as it needed too. If this is possible, how would i process all of that, because i'd need to somehow loop through all the records the user has selected.
<?php
$eventSearch = $_POST['eventSearch'];
//Include Database connection
include '../includes/dbConnect.php';
foreach ($arr as &$value) {
$id = $value;
//Query Database for all customer info
$sql = "SELECT * FROM customerInterest WHERE `id` = '$value'";
$result = mysqli_query($dbLink, $sql);
$row = mysqli_fetch_assoc($result);
//require the document that creates the PDF
require('PDF_Label.php');
//Create a new PDF
$pdf = new PDF_Label('L7163');
$pdf->AddPage();
//assign the customer information to a variable
$sal = $row["salutation"];
$fn = $row["firstName"];
$ln = $row["lastName"];
$add1 = $row["contactAddress1"];
$add2 = $row["contactAddress2"];
$city = $row["contactAddressCity"];
$state = $row["contactAddressState"];
$post = $row["contactAddressPostcode"];
$country = $row["contactAddressCountry"];
if ($sal == "N/A") {
$sal = "";
}
if ($fn == "N/A") {
$fn = "";
}
if ($ln == "N/A") {
$ln = "";
}
if ($add1 == "N/A") {
$add1 = "";
}
if ($add2 == "N/A") {
$add2 = "";
}
if ($city == "N/A") {
$city = "";
}
if ($state == "N/A") {
$state = "";
}
if ($post == "N/A") {
$post = "";
}
if ($country == "N/A") {
$country = " ";
}
$add1 = $add1." ".$add2;
$post = str_replace(' ', '', $post);
$post = strtoupper($post);
$post = substr_replace($post, " ", 4, 0);
// Standard format
//create new page
// Print labels
$text = sprintf("%s\n%s\n%s\n%s %s",$sal." ".$fn." ".$ln, $add1, $city, $state, $post,$country);
$pdf->Add_Label($text);
}
//Output all the info
$pdf->Output();
?>
So the above contains the code i have now tried. I have posted the data to the PDf generating page (that is where all the code is from) and i keep getting the error (see below) and i cannot figure out why :/
Fatal error: Uncaught Error: Call to a member function Output() on null in /homepages/38/d735513801/htdocs/future/pdfGen/labelEX.php:80 Stack trace: #0 {main} thrown in /homepages/38/d735513801/htdocs/future/pdfGen/labelEX.php on line 80

alert shows entry updated succesfully but entry does'nt update in database

I am creating a updating form page. it shows no error but there is no updation in my database.
I already check whole the database row names but that doesnt help.
that code is a little bit long but please help.
<?php
if (isset($_POST['update'])) {
$update_id = $_GET['edit_form'];
$bill = $_POST['b_no'];
$naam = $_POST['name'];
$mobile_no = $_POST['mobile'];
$addres = $_POST['add'];
$detail = $_POST['p_detail'];
$p_img_name = $_FILES['p_img']['name'];
$p_img_type = $_FILES['p_img']['type'];
$p_img_size = $_FILES['p_img']['size'];
$p_img_tmp = $_FILES['p_img']['tmp_name'];
$prc = $_POST['price'];
$deposite = $_POST['d_amt'];
$remaning = $_POST['r_amt'];
$b_img_name = $_FILES['b_img']['name'];
$b_img_type = $_FILES['b_img']['type'];
$b_img_size = $_FILES['b_img']['size'];
$b_img_tmp = $_FILES['b_img']['tmp_name'];
$p_date = date('y-m-d');
move_uploaded_file($p_img_tmp, "images/Product/$p_img_name");
move_uploaded_file($b_img_tmp, "images/Bill/$b_img_name");
$update_query = "UPDATE new_entry SET bill_no='$bill', name='$naam',
mobile_no='$mobile_no', address='$addres', product_detail='detail',
product_image='$p_img_name', price='$prc', deposite_amt='deposite',
remaining='$remaning', bill_image='$b_img_name',Product_date='$p_date'
WHERE s_no='$update_id' ";
if(mysqli_query($conn, $update_query)) {
echo "<script> alert('Entry Updated Successfully') </script>";
echo "<script> window.open('view_entry.php','_self') </script>";
} else {
echo "cant Update Entry.." .mysqli_error($conn);
}
}
?>

Parse error: parse error in php

I have this php code that accesses the tables users and portfolio
However I keep running into Parse error: parse error in /Users/...../Sites/..../sell.php on line 28
If someone could help me out, it'd be of great help.
<?
// require common code
require_once("includes/common.php");
//check for errors
$error = false;
if (isset($_POST["submit"]))
{
if(empty($_POST["symbol"]))
{
$error = true;
$message = "Enter a name";
}
else if(empty($_POST["shares"]))
{
$error = true;
$message = "Enter the shares";
}
// check if user has the stocks and the shares
$id = $_SESSION["id"];
$symbol = $_POST["symbol"];
$sharesQuery = "SELECT shares FROM portfolio WHERE id = $id AND symbol = '$symbol' ";
else if(($shares = mysql_query($sharesQuery)) == false)
{
$error = true;
$message = "Don't have the stock";
}
// else, if everything checks out, delete it and increment the cash
else
{
$deleteQuery = "DELETE from portfolio WHERE id = $id AND symbol = '$symbol'";
mysql_query($deleteQuery);
$incrementQuery = "UPDATE users SET cash = cash + ($shares * lookup($symbol)->price) WHERE id = $id ";
mysql_query($incrementQuery);
//set the variables into session and then redicrect to sell2
$_SESSION["symbol"] = $_POST["symbol"];
$_SESSION["shares"] = $_POST["shares"];
redirect("sell2.php");
}
}
?>
From where is this else coming in? Add a }:
} else if(($shares = mysql_query($sharesQuery)) == false)
Your final code will be:
<?
// require common code
require_once("includes/common.php");
//check for errors
$error = false;
if (isset($_POST["submit"])) {
if (empty($_POST["symbol"])) {
$error = true;
$message = "Enter a name";
}
else if (empty($_POST["shares"])) {
$error = true;
$message = "Enter the shares";
}
// check if user has the stocks and the shares
$id = $_SESSION["id"];
$symbol = $_POST["symbol"];
$sharesQuery = "SELECT shares FROM portfolio WHERE id = $id AND symbol = '$symbol' ";
} else if (($shares = mysql_query($sharesQuery)) == false) {
$error = true;
$message = "Don't have the stock";
}
// else, if everything checks out, delete it and increment the cash
else {
$deleteQuery = "DELETE from portfolio WHERE id = $id AND symbol = '$symbol'";
mysql_query($deleteQuery);
$incrementQuery = "UPDATE users SET cash = cash + ($shares * lookup($symbol)->price) WHERE id = $id ";
mysql_query($incrementQuery);
//set the variables into session and then redicrect to sell2
$_SESSION["symbol"] = $_POST["symbol"];
$_SESSION["shares"] = $_POST["shares"];
redirect("sell2.php");
}
?>
On line 28:
else if(($shares = mysql_query($sharesQuery)) == false)
You need a bracket to close the current if statement before doing an else if:
<?
// require common code
require_once("includes/common.php");
//check for errors
$error = false;
// check if user has the stocks and the shares
$id = $_SESSION["id"];
$symbol = $_POST["symbol"];
$sharesQuery = "SELECT shares FROM portfolio WHERE id = $id AND symbol = '$symbol' ";
if (isset($_POST["submit"])){
if(empty($_POST["symbol"])){
$error = true;
$message = "Enter a name";
}else if(empty($_POST["shares"])){
$error = true;
$message = "Enter the shares";
}else if(($shares = mysql_query($sharesQuery)) == false){
$error = true;
$message = "Don't have the stock";
}else{
$deleteQuery = "DELETE from portfolio WHERE id = $id AND symbol = '$symbol'";
mysql_query($deleteQuery);
$incrementQuery = "UPDATE users SET cash = cash + ($shares * lookup($symbol)->price) WHERE id = $id ";
mysql_query($incrementQuery);
//set the variables into session and then redicrect to sell2
$_SESSION["symbol"] = $_POST["symbol"];
$_SESSION["shares"] = $_POST["shares"];
redirect("sell2.php");
}
}
?>
It was silly mistake on my part, the declarations for id and symbol should have been at the top of the condition, right after isset,
Thanks for the speedy answers

PHP Form for required Fields

I have a basic Form that submits data into a database and I want it to require certain fields to be submitted, so far it recongizes that the fields are empty, but it still submits regardless. I can't seem to find a solution..
Code
<?
// define variables and set to empty values
$asinErr = $qtyErr = $floorErr = $locErr;
$asin = $quantity = $floor = $location;
# this is processed when the form is submitted
# back on to this page (POST METHOD)
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
if (empty($_POST["asin"]))
{$asinErr = "ASIN is required";}
else
{$asin = addslashes($_POST["asin"]);}
if (empty($_POST["quantity"]))
{$qtyErr = "Quantity is required";}
else
{$quantity = addslashes($_POST["quantity"]);}
if (empty($_POST["floor"]))
{$floorErr = "Floor is required";}
else
{$floor = addslashes($_POST["floor"]);}
if (empty($_POST["location"]))
{$locErr = "Location is required";}
else
{$location = addslashes($_POST["location"]);}
# setup SQL statement
$sql = " INSERT INTO kiva_amnesty_log ";
$sql .= " (asin, quantity, floor, location, date) VALUES ";
$sql .= " ('$asin','$quantity','$floor','$location', now()) ";
#execute SQL statement
$result = mysql_query($sql, $cid);
# check for error
if (mysql_error()) { print "Database ERROR: " . mysql_error(); }
print "<h3><font color=red>New Amnesty Added - View it <a href=amnesty_log_summary.php>HERE</a></font></h3>";
}
?>
<form name="fa" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<table>
<tr><td>ASIN:</td><td><input type="text" name="asin" id="asin"><span class="error">* <?php echo $asinErr;?></span></td></tr>
<tr><td>Quantity:</td><td><input type="text" name="quantity" id="quantity"><span class="error">* <?php echo $qtyErr;?></span></td></tr>
<tr><td>Floor:</td><td><select name="floor"><option value="1">Floor 1</option><option value="2">Floor 2</option></select><span class="error">* <?php echo $floorErr;?></span></td></tr>
<tr><td>KIVA Floor:</td><td><input type="radio" value="Yes" name="location">Yes<input type="radio" value="No" name="location">No</select><span class="error">* <?php echo $locErr;?></span></td></tr>
<tr><td><input type="submit" name="submit" id="submit" value="Submit Amnesty!"></td></tr>
</table>
</form>
Updated:
<?
// define variables and set to empty values
$asinErr = $qtyErr = $floorErr = $locErr = "";
$asin = $quantity = $floor = $location = "";
$lb_error = 0;
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
if (empty($_POST["asin"])) {
$asinErr = "ASIN is required";
$lb_error = 1;
} else {
$asin = addslashes($_POST["asin"]);
}
if (empty($_POST["quantity"])) {
$qtyErr = "Quantity is required";
$lb_error = 1;
} else {
$quantity = addslashes($_POST["quantity"]);
}
if (empty($_POST["floor"])) {
$floorErr = "Floor is required";
$lb_error = 1;
} else {
$floor = addslashes($_POST["floor"]);
}
if (empty($_POST["location"])) {
$locErr = "Location is required";
$lb_error = 1;
} else {
$location = addslashes($_POST["location"]);
}
if($lb_error) {
continue;
}
# setup SQL statement
$sql = " INSERT INTO kiva_amnesty_log ";
$sql .= " (asin, quantity, floor, location, date) VALUES ";
$sql .= " ('$asin','$quantity','$floor','$location', curdate()) ";
#execute SQL statement
$result = mysql_query($sql, $cid);
# check for error
if (mysql_error()) { print "Database ERROR: " . mysql_error(); }
You want to check if you error variables are empty. If they are not, then break the script
ie
if(!empty($asinErr) || !empty($qtyErr) || !empty($floorErr) || !empty($locErr) ) {
break;
}
Something along these lines.
Check for the errors before you get to the point where you are writing to the database
Define at the top
$lb_error = 0;
Throughout your if/else checks for errors, if there is an error, assign the variable a 1
if (empty($_POST["asin"])) {
$asinErr = "ASIN is required";
$lb_error = 1;
} else {
$asin = addslashes($_POST["asin"]);
}
Then after you have completed all of these, do a check for errors and break if there are any
if($lb_error) {
break;
}

Categories