Unable to submit CSV file to uploader - php

I've made a CSV uploaded where the user must tell the program the exact name of certain columns in the CSV file so it can access and grab data to store in database. I have some error messages where whenever they don't fill something out that is necessary it will take them back to form to fix what ever mistakes they made. The issue is it always takes me back and I don't really know why.
Code for Uploader ---------------------------------------------------------------------
try {
# MySQL with PDO_MYSQL
$DBH = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch(PDOException $e) {
echo "I'm sorry, I'm afraid I can't do that.";
file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}
function returnBack(){
header("Location:csvuploader/csvuploaderform.php?seterror=1");
exit;
}
if (isset($_POST['submit'])){
/*******************************GET NAME OF COLUMNS IN CSV FILE *********************************************************/
if (empty($_POST['files'])){
returnBack();
}
if (empty($_POST['firstname'])){
returnBack();
}
if (empty($_POST['lastname'])){
returnBack();
}if (empty($_POST['email'])){
returnBack();
}
if (empty($_POST['phone'])){
returnBack();
}
$file = $_FILES['files']['tmp_name'];
$handle = fopen($file , "r");
$fileop = fgetcsv($handle,1000,",");
$firstname_index = array_search($_POST['firstname'],$fileop);
if (empty($firstname_index)){
returnBack();
}
$lastname_index = array_search($_POST['lastname'],$fileop);
if (empty($lastname_index)){
returnBack();
}
$email_index = array_search($_POST['email'],$fileop);
if (empty($email_index)){
returnBack();
}
$phone_index = array_search($_POST['phone'],$fileop);
if (empty($phone_index)){
returnBack();
}
/***********************ASSIGN COLUMN VALUES TO ACCORDING VARIABLES AND INSERT THEN INTO CSV TABLE IN DB *************************************/
while (($fileop = fgetcsv($handle,1000,",")) !== false)
{
$firstname = $fileop[$firstname_index];
$lastname = $fileop[$lastname_index];
$email = $fileop[$email_index];
$phone = $fileop[$phone_index];
$insertdata = $DBH->prepare("INSERT INTO csv (firtname, lastname, email, phone) VALUES ('$firstname','$lastname','$email','$phone')");
$insertdata->execute();
}
if ($insetdata){
echo "Successfully Uploaded. Thank you.";
}
}
Thank you for your time!
UPDATED ---------------------------
form code
<table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form method="post" action="csvuploader.php" enctype="multipart/form-data">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td colspan="3"><strong>CSV Uploader </strong></td>
</tr>
<tr>
<td>Enter Name of First Name Column </td>
<td>:</td>
<td><input name="fisrtname" type="text" ><?php
$setError=$_GET['seterror'];
if($setError == 1){
echo "<span class='errorMsg'>Need Exact Name</span>";
}
?> </td>
</tr>
<tr>
<td>Enter Name of Last Name Column </td>
<td>:</td>
<td><input name="lastname" type="text" ><?php
$setError=$_GET['seterror'];
if($setError == 1){
echo "<span class='errorMsg'>Need Exact Name</span>";
}
?></td>
</tr>
<tr>
<td>Enter Name of Email Column </td>
<td>:</td>
<td><input name="email" type="text" ><?php
$setError=$_GET['seterror'];
if($setError == 1){
echo "<span class='errorMsg'>Need Exact Name</span>";
}
?></td>
</tr>
<tr>
<td>Enter Name of Phone Number Column </td>
<td>:</td>
<td><input name="phone" type="text" ><?php
$setError=$_GET['seterror'];
if($setError == 1){
echo "<span class='errorMsg'>Need Exact Name</span>";
}
?></td>
</tr>
<tr>
<td width="294"><input type="file" name="files" /><?php
$setError=$_GET['seterror'];
if($setError == 1){
echo "<span class='errorMsg'>Select a File</span>";
}
?></td>
</tr>
<br />
<tr>
<td><input type="submit" name="submit" value="Submit" /></td>
</tr>
</table>
</td>
</form>
</tr>
</table>

I'm not sure how your data file look, but you might want to use trim on fgetcsved array values, because the last values are very likely to include a line-end:
$fileop=fgetcsv($handle);
$fileop=array_map("trim",$fileop);
/*recognize index*/
while (($fileop=fgetcsv($handle))!==false)
{
$fileop=array_map("trim",$fileop);
$firstname=$fileop[$firstname_index];
/*insert into DB*/
}
Edit:
Oops, seems I missed something...you're using
if(empty($firstname_index))
in your code, but if, for instance, array_search($_POST["firstname"],$fileop) returns 0 (which is the first index in an array), your empty($firstname_index) will be TRUE, and you will be kicked back.
You should use
if($firstname_index===false)
instead (in all four indexes). PHP Document.
Edit #2:
Also, it's better to make you title-matching case-insensitive:
$fileop=fgetcsv($handle);
$fileop=array_map("strtoupper",array_map("trim",$fileop));
$firstname_index=array_search(strtoupper($_POST["firstname"]),$fileop);
if($firstname_index===false) returnBack();
/*and all four indexes*/

Related

php update record doesn't work due to lookup variable somehow being dropped

So I'm having a challenge with a subscription system that I've been building.
I'm using a simple login php page to validate the username and password of the user against the DB, once authenticated the script creates a secure session and calls the edit_subscription.php file and passes the ID of the user through the Url.
The edit_subscription.php file takes the ID and pulls the user info using MYsql
and loads their info into a form. The user can then edit or modify their subscription details and press the submit button to update the DB.
Everything works except the mysql Update back to the DB.
I've managed to narrow the problem down to the ID variable
If I hardcode the variable into the update command it works and the db is updated
If I hardcode the ID into a variable used in the update command, it works up to a point. if I move that hardcoded variable in front of line 42 the update command will no longer work.
I think it's something to do with the post command, but even when I load the old ID into a hidden form and try to have it repost for the update command it still doesn't work and treats the variable as if it's empty.
I've tried for hours to get this working, and just can seem to get it going.
anyone have any suggestions pertaining to specifically this issue
(please don't comment of security or, best practices unless it relates specifically to the issue described thanks)
<?
$id = htmlspecialchars($_GET['ID']);
$username="****";
$database="****";
$host="****";
$pass ="****";
mysql_connect($host,$username,$pass);
#mysql_select_db($database) or die( "Unable to select database");
$result = mysql_query("SELECT * FROM `****`.`****` WHERE `Subscriber ID` = '$id' LIMIT 1");
$name_old=mysql_result($result,0,"Name");
$address1_old=mysql_result($result,0,"Address 1");
$address2_old=mysql_result($result,0,"Address 2");
$city_old=mysql_result($result,0,"City");
$prov_old=mysql_result($result,0,"Prov");
$postal_old=mysql_result($result,0,"Postal");
$country_old=mysql_result($result,0,"Country");
$email_old=mysql_result($result,0,"Email");
$qty_old=mysql_result($result,0,"qty");
$status_old=mysql_result($result,0,"Status");
$ezine_old=mysql_result($result,0,"Ezine");
$mailout_old=mysql_result($result,0,"Mailout");
$password_old=mysql_result($result,0,"Password");
$nameErr = $emailErr = $passwordErr = "";
$name=$_POST['name'];
$email=$_POST['email'];
$address1=$_POST['address1'];
$address2=$_POST['address2'];
$city=$_POST['city'];
$province=$_POST['prov'];
$postal=$_POST['postal'];
$country=$_POST['country'];
$password=$_POST['password'];
$mailout=$_POST['mailout'];
$ezine=$_POST['ezine'];
$status="Subscribed";
$qty=$_POST['qty'];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["password"])) {
$passwordErr = "* Password is required";
}
if (empty($_POST["name"])) {
$nameErr = "* Name is required";
} else {
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "* Invalid Characters";
}
}
if(isset($_POST['mailout'])){}
else{
$mailout="NO";
}
if(isset($_POST['ezine'])){}
else{
$ezine="NO";
}
if (empty($_POST["email"])) {
$emailErr = "* Email is required";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "* Invalid email";
}
}
if($name != NULL AND $nameErr == ""){
if($email != NULL AND $emailErr == ""){
if($password != NULL AND $passwordErr == ""){
mysql_query("UPDATE `Subscribers` SET
`Name` ='$name',
`Email` = '$email',
`Address 1` = '$address1',
`Address 2` = '$address2',
`City` = '$city',
`Prov` = '$province',
`Postal` = '$postal',
`Country` = '$country',
`Password` = '$password',
`qty` = '$qty',
`Status` = '$status',
`Mailout` = '$mailout',
`Ezine` = '$ezine',
WHERE `Subscriber ID` = $id");
mysql_close();
echo ("<p align=\"center\"><font color=\"red\">Thank you for updating your subscription, you should receive an email confirmation shortly</font></p>");
}
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table width="100%" border="0">
<tr>
<td width="11%" align="right">Name</td>
<td width="3%"> </td>
<td width="47%"><input type="text" name="name" value="<?php echo $name_old;?>">
<font color="red"> <?php echo $nameErr;?></font></td>
<td width="39%" bgcolor="#CCCCCC"><input type="checkbox" name="ezine" value="YES"
<? if($ezine_old =="YES"){echo "checked";} ?>>
Subscribe by email</td>
</tr>
<tr>
<td width="11%" align="right">Address 1</td>
<td> </td>
<td width="47%"><input type="text" name="address1" value="<?php echo $address1_old;?>"></td>
<td bgcolor="#CCCCCC"><input type="checkbox" name="mailout" value="YES" <? if($mailout_old =="YES"){echo "checked";} ?>>
Subscribe by Post </td>
</tr>
<tr>
<td width="11%" align="right">Address 2</td>
<td> </td>
<td width="47%"><input type="text" name="address2" value="<?php echo $address2_old;?>"></td>
<td bgcolor="#CCCCCC"><input type="text" name="qty" value="<?php echo $qty_old;?>" size="5">
# of copies.</td>
</tr>
<tr>
<td align="right">City</td>
<td> </td>
<td><input type="text" name="city" value="<?php echo $city_old;?>"></td>
<td> </td>
</tr>
<tr>
<td align="right">Province</td>
<td> </td>
<td><input type="text" name="prov" value="<?php echo $prov_old;?>" >
<td> </td>
</tr>
<tr>
<td align="right">Postal</td>
<td> </td>
<td><input type="text" name="postal"value="<?php echo $postal_old;?>" ></td>
<td></td>
</tr>
<tr>
<td align="right">Country</td>
<td> </td>
<td><input type="text" name="country" value="<?php echo $country_old;?>" ></td>
<td> </td>
</tr>
<tr>
<td align="right">Email</td>
<td> </td>
<td colspan="2"><input type="text" name="email" value="<?php echo $email_old;?>">
<font color="red"><?php echo $emailErr;?></font></td>
</tr>
<tr>
<td align="right">Password</td>
<td> </td>
<td colspan="2"><input type="password" name="password" value="<?php echo $password_old;?>">
<font color="red"> <?php echo $passwordErr;?></font></td>
</tr>
<tr>
<td align="right"> </td>
<td> </td>
<td> </td>
<td></td>
</tr>
<tr>
<td align="right"> </td>
<td><img src="images/shim.png" width="20" height="20" /></td>
<td><input type="Submit" ></td>
<td> </td>
</tr>
</table>
<p> </p>
</form>
There is a comma after
Ezine = '$ezine' ,
Remove it. Also you shall also use mysqli extension or PDO sql . mysql_ is deprecated
As you said, there is a lot wrong with that code.. however to satisfy your question here is the simple answer:
You left an extra comma in your update statement.
`Ezine` = '$ezine',
In the future try always checking if the query went through.
$result = mysql_query(..);
if($result) {
// it worked
} else {
// it failed
echo mysql_error(); // or mysqli_error($link); or $link->error, etc.
}
Best of luck

php validation code format

Okay I have this MySQL database form and am trying to add validation to it. After 2 days of fighting with it, I thought I would get some advice. Would like that the selected item from dropdown and Firstname, Phone, Email, are all required. Then I want to verify that the data in the Firstname, Lastname, Phone (doesn't have to be any special format), Email and Comments are all acceptable formats before putting in database. Here is what I have so far:
<?php
include('inc_header.php');
if(isset($_POST['add']))
{
require('dbcon.php');
if(! get_magic_quotes_gpc() )
{
$Id = addslashes ($_POST['Id']);
$List = addslashes ($_POST['List']);
$Firstname = addslashes ($_POST['Firstname']);
$Lastname = addslashes ($_POST['Lastname']);
$Phone = addslashes ($_POST['Phone']);
$Email= addslashes ($_POST['Email']);
$Calltime = addslashes ($_POST['Calltime']);
$Comment = addslashes ($_POST['Comment']);
}
else
{
$Id = $_POST['Id'];
$Date = $_POST['Date'];
$List = $_POST['List'];
$Firstname = $_POST['Firstname'];
$Lastname = $_POST['Lastname'];
$Phone = $_POST['Phone'];
$Email = $_POST['Email'];
$Calltime = $_POST['Calltime'];
$Comment = $_POST['Comment'];
}
$error = '';
//put chosen function here
function validate_Firstname($input, $pattern = "/([A-Za-z0-9])")
{
return !preg_match($pattern, $input);
}
function validate_Phone($input, $pattern = "/([A-Za-z0-9])")
{
return !preg_match($pattern, $input);
}
function isValidEmail( $Email ){
return filter_var( $Email, FILTER_VALIDATE_EMAIL );
}
//get values and validate each one as required
$List = mysql_real_escape_string($_POST['List']);
if(!$List){ $error .= "Please choose one<br />"; }
$Firstname = mysql_real_escape_string($_POST['Firstname']);
if(!$Firstname){ $error .= "First name is required<br />"; }
//get values and validate each one as required
$Lastname = mysql_real_escape_string($_POST['Lastname']);
if(!$Lastname){ $error .= "Last name is required<br />"; }
//repeat for each field
$Email = mysql_real_escape_string($_POST['Email']);
if(!isValidEmail($Email)){ $error .= "The email entered is invalid<br />"; }
//and so on...
if(!$error){
//add insert into database code here
$sql = "INSERT INTO contacts ".
"(`Id`,`Date`,`List`,`Firstname`,`Lastname`,`Phone`,`Email`,`Calltime`,`Comment`)".
"VALUES'$Id,','$Date','$List','$Firstname','$Lastname','$Phone','$Email','$Calltime','$Comment') ";
mysql_select_db('hmintcwa_contacts');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully<br /><br /><a href=contactsadd.php><font color=#000000>Back</font></a>\n";
mysql_close($conn);
}
else
{
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" name="ContactForm">
<table bgcolor="#000000" width="500" cellpadding="5" cellspacing="1" border="0">
<input type="hidden" name="Id" id="Id">
<tr>
<td bgcolor="#e9e9e9" align="right">Requested Info</td>
<td bgcolor="#ffffff" align="left"><select name="List">
<option value="0" > Please Choose One </option>
<option value="Market Analysis" > Market Analysis </option>
<option value="Consultation" > Consultation </option></select></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Date</td>
<input name="Date" type="hidden" id="Date" value="<? print(Date("l F d, Y")); ?>" />
<td bgcolor="#ffffff" align="left"><? print(Date("l F d, Y")); ?></td>
</tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Firstname</td>
<td bgcolor="#ffffff" align="left"><input name="Firstname" type="text" size="20" id="Firstname"></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Lastname</td>
<td bgcolor="#ffffff" align="left"><input type="text" name="Lastname" size="20" id="Lastname"></td>
</tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Phone</td>
<td bgcolor="#ffffff" align="left"><input type="text" name="Phone" size="20" id="Phone"></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Email</td>
<td bgcolor="#ffffff" align="left"><input type="text" name="Email" size="20" id="Email"></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Preferred Calltime</td>
<td bgcolor="#ffffff" align="left"><input type="text" name="Calltime" size="20" id="Calltime"> If none put N/A</td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Comment</td>
<td bgcolor="#ffffff" align="left"><textarea name="Comment" cols="40" rows="8" id="Comment"></textarea></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right"> </td>
<td bgcolor="#ffffff" align="center"><br>
<input name="add" type="submit" id="add" value="Add Contact"><input type="reset" name="Reset" value="Clear Form"><input type=button value="Cancel" onClick="history.go(-1)"><br>
</td>
</tr>
</table>
</form>
<br> </center>
<?php
}
?>
</body>
</html>
So far I just keep chasing error message. Please forgive formatting I am trying to learn be gentle.
Your query arguments are backwards, and you should be using mysqli_. Here is the correct order.
$retval = mysqli_query($conn, $sql);
mysqli_query documentation
you need an end bracket for this statement: (if(!$error){)
edit: the } you were missing is actually a closing bracket for if(isset($_POST['add'])), not magic quotes. sorry!
//and so on...
if(!$error)
{
//add insert into database code here
// this probably won't run right...
// you're missing a ( after the word values...
// insert into tablename (id, name, stuff) values (1,'gloomy','stuff);
// this part of your statement is not correct: "VALUES'$Id,','$Date',
// and the commas are off, too.
$sql = "INSERT INTO contacts ".
"(`Id`,`Date`,`List`,`Firstname`,`Lastname`,`Phone`,`Email`,`Calltime`,`Comment`)".
"VALUES'$Id,','$Date','$List','$Firstname','$Lastname','$Phone','$Email','$Calltime','$Comment') ";
// print your SQL here to make sure it is correct.
// copy and paste it to run it directly in the DB. if it won't run there
// it won't run here
print $sql."<br/>";
mysql_select_db('hmintcwa_contacts');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully<br /><br /><a href=contactsadd.php><font color=#000000>Back</font></a>\n";
mysql_close($conn);
} // <-------- you're missing this closing bracket
} // this ends the statement for if(isset($_POST['add'])) { ....
else
{
// REMOVE this... or else it will print the world else somewhere
// i put this here to debug...
print "else<br/>";
?>
formatting your code helps a lot
EDIT: looking over the code, there's a lot of small issues everywhere. I'm not trying to be mean. I'm just saying... why don't you try to break the code up into smaller pieces and make sure all the parts will compile and work properly on their own before putting them all together? This is a lot to tackle all at once. Just try to dump your variables (arrays in particular) when you need to and each time you write a new chunk, make sure it works correctly and make sure everything else still works correctly. Then, move forward... it's easier to isolate problems that way.
this works for me. it uses pdo. oh, and now you don't need to worry about sql injection as much. this pretty much takes care of it completely. like everything, there's always ways around things but you do not need to check for magic quotes, you do not need to escape anything. doing the parameterization handles all that for you.
edit: so... when you write code... don't write a whole bunch of stuff and then see if it all works. write a few lines. test. write some more. test. make sure the new stuff works. make sure the old stuff still works. write a little more. i have absolutely no clue how you got that far with so many little issues. i'm not trying to be mean. write code in lil chunks, though. even logic. always test everything again, then move on.
and I left my debug statements in there... the print_r($array) and the var_dump(variable) so that you can see how that stuff is set up, where your values are coming from, what everything holds at whatever point, how to use them, where to put them. it will print weird things now. comment it out or remove them.
I understand there's a lot more tutorials for mysql_ functions but they are old and not safe at all. If you have issues using PDO, just come back to StackOverflow with your errors, issues and code and just write a disclaimer that "you know mysql_ functions are bad but the pdo is harder to learn" and people will be happy to help because it is that much better.
these are important PDO pages:
$stmt->bindParam()
$stmt->execute()
$stmt->rowCount() (I didn't use this but you might want it later)
$stmt->fetchAll() - for your select statements. this returns all the data in a huge array
how to prepare statements
and the code...
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
// include('inc_header.php');
function validate_Firstname($input, $pattern = "/([A-Za-z0-9])") {
return !preg_match($pattern, $input);
}
function validate_Phone($input, $pattern = "/([A-Za-z0-9])") {
return !preg_match($pattern, $input);
}
function isValidEmail($Email) {
return filter_var($Email, FILTER_VALIDATE_EMAIL);
}
// ====================================================================================
// ====================================================================================
if (!empty($_POST)) {
print "<pre>This is your \$_POST array \n\n".print_r($_POST,true)."</pre>";
}
$error = '';
if (isset($_POST['add']))
{
// require('dbcon.php');
$conn = new PDO('mysql:host=localhost;dbname=test', 'root', '');
// what if the array index ['whatever'] doesn't exist? errors.
// so we need to check and make sure it is set... then assign.
// this also gives us a blank default value, which is nice....
$id = isset($_POST['Id']) ? $_POST['Id'] : 'NULL';
$date = isset($_POST['Date']) ? $_POST['Date'] : '';
$list = isset($_POST['List']) ? $_POST['List'] : '';
$firstname = isset($_POST['Firstname']) ? $_POST['Firstname'] : '';
$lastname = isset($_POST['Lastname']) ? $_POST['Lastname'] : '';
$phone = isset($_POST['Phone']) ? $_POST['Phone'] : '';
$email = isset($_POST['Email']) ? $_POST['Email'] : '';
$calltime = isset($_POST['Calltime']) ? $_POST['Calltime'] : '';
$comment = isset($_POST['Comment']) ? $_POST['Comment'] : '';
if (!$list) {
$error .= "Please choose one<br />";
}
if (!$firstname) {
$error .= "First name is required<br />";
}
if (!$lastname) {
$error .= "Last name is required<br />";
}
if (!isValidEmail($email)) {
$error .= "The email entered is invalid<br />";
}
var_dump($error);
if (!$error)
{
$stmt = $conn->prepare("INSERT INTO contacts (id, date, list, firstname, lastname, phone, email, calltime, comment) \n".
" VALUES (:id, :date, :list, :firstname, :lastname, :phone, :email, :calltime, :comment) ");
$success = $stmt->execute(array(':id'=>$id, ':date'=>$date, ':list'=>$list, ':firstname'=>$firstname, 'lastname'=>$lastname,
':phone'=>$phone, ':email'=>$email, ':calltime'=>$calltime, ':comment'=>$comment));
if (!$success)
{
echo "\nPDO::errorInfo():\n";
print "<pre>".print_r($dbh->errorInfo(),true)."/<pre>";
}
else
{
print "it worked! the new row's ID is ".$conn->lastInsertId()."...!!!<br/>";
}
echo "Entered data successfully<br/><br/>";
} // end of if (!$error) { ... }
else
{
print "$error<br/>";
}
echo "<a href='contactsadd.php' style='font-color=#000000'>Back</a>\n";
} // end of if(isset($_POST['add'])) { ... }
else
{
// ====================================================================================
// ====================================================================================
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" name="ContactForm">
<table bgcolor="#000000" width="500" cellpadding="5" cellspacing="1" border="0">
<input type="hidden" name="Id" id="Id">
<tr>
<td bgcolor="#e9e9e9" align="right">Requested Info</td>
<td bgcolor="#ffffff" align="left"><select name="List">
<option value="0" > Please Choose One </option>
<option value="Market Analysis" > Market Analysis </option>
<option value="Consultation" > Consultation </option></select></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Date</td>
<input name="Date" type="hidden" id="Date" value="<?php print(Date("l F d, Y")); ?>" />
<td bgcolor="#ffffff" align="left"><?phpprint(Date("l F d, Y")); ?></td>
</tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Firstname</td>
<td bgcolor="#ffffff" align="left"><input name="Firstname" type="text" size="20" id="Firstname"></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Lastname</td>
<td bgcolor="#ffffff" align="left"><input type="text" name="Lastname" size="20" id="Lastname"></td>
</tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Phone</td>
<td bgcolor="#ffffff" align="left"><input type="text" name="Phone" size="20" id="Phone"></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Email</td>
<td bgcolor="#ffffff" align="left"><input type="text" name="Email" size="20" id="Email"></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Preferred Calltime</td>
<td bgcolor="#ffffff" align="left"><input type="text" name="Calltime" size="20" id="Calltime"> If none put N/A</td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Comment</td>
<td bgcolor="#ffffff" align="left"><textarea name="Comment" cols="40" rows="8" id="Comment"></textarea></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right"> </td>
<td bgcolor="#ffffff" align="center"><br>
<input name="add" type="submit" id="add" value="Add Contact"><input type="reset" name="Reset" value="Clear Form"><input type=button value="Cancel" onClick="history.go(-1)"><br>
</td>
</tr>
</table>
</form>
<br> </center>
<?php
}
?>

Input values doesnt get display in the browser instead shows blank field

I just need to insert my form data into mysql database & display it in browser. But, when I fill up the form & click submit , the row gets added but with no data except for ID field which is autoincremented.. even the table in phpmyadmin looks same with the row added & empty fileds.
any suggestions will be highly appreciated...
my html form looks like this,
<table border="1">
<tr>
<td align="center">Form Input Students Data</td>
</tr>
<tr>
<td>
<table>
<form method="POST" action="data_insert_htmlform.php/">
<tr>
<td><label for="Name">Name</label></td>
<td><input type="text" name="name" size="20">
</td>
</tr>
<tr>
<td><label for="Age">Age</label></td>
<td><input type="text" name="age" size="20">
</td>
</tr>
<tr>
<td><label for="Birth_Date">Birth_Date</label></td>
<td><input type="text" name="Birth_Date" size="20">
</td>
</tr>
<tr>
<td><label for="Address"Address</label></td>
<td><input type="text" name="address" size="40">
</td>
</tr>
<tr>
<td></td>
<td align="center">
<input type="submit" name="submit" value="Sent">
</td>
</tr>
</form>
</table>
</td>
</tr>
</table>
and my php code,
<?php
error_reporting(E_ERROR | E_PARSE);
$database = 'students';
$continued=mysql_connect("localhost" , "root", "");
if(mysql_select_db($database))
echo ("<br><br>connection to the database succeeds");
else
echo ("connection failed");
/*$name = $_POST['name'];
$age = $_POST['age'];
$birth_date = $_POST['Birth_date'];
$address = $_POST['address'];*/
$insert = "INSERT INTO students_basicinfo(Name, Age, Birth_Date, Address) VALUES ('{$_POST['name']}','{$_POST['age']}' , '{$_POST['Birth_date']}' , '{$_POST['address']}')";
$abc = mysql_query($insert);
if($abc){
echo("<br>Input data is succeed");
}else{
echo("<br>Input data is fail");
}
$order = "SELECT * FROM students_basicinfo";
$result = mysql_query($order);
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
echo "<table border='1'>";
while($data = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>".$data[ID]."</td>";
echo "<td>".$data[Name]."</td>";
echo "<td>".$data[Age]."</td>";
echo "<td>".$data[Birth_Date]."</td>";
echo "<td>".$data[Address]."</td>";
echo "</tr>";
}
echo "</table>";
?>
This issue about input name case sensitive
Change $_POST['Birth_date'] to $_POST['Birth_Date'] with uppercase D
Try following query, this will work.
$insert = "INSERT INTO students_basicinfo(Name, Age, Birth_Date, Address) VALUES ('{$_POST['name']}','{$_POST['age']}' , '{$_POST['Birth_Date']}' , '{$_POST['address']}')";
Replace
'{$_POST['name']}','{$_POST['age']}' , '{$_POST['Birth_date']}' , '{$_POST['address']}'
with
'".$_POST['name']."','".$_POST['age']."' , '".$_POST['Birth_date']."' , '".$_POST['address']."'
Try :
echo "<tr>";
echo "<td>".$data['ID']."</td>";
echo "<td>".$data['Name']."</td>";
echo "<td>".$data['Age']."</td>";
echo "<td>".$data['Birth_Date']."</td>";
echo "<td>".$data['Address']."</td>";
echo "</tr>";
(Use prepared statements.)
Dump the statement, in a HTML comment <!-- ... ---> so you can try it yourself.
Use echo mysql_error() to check for errors.
I mistrust the date field, DATE? Use '2013-08-31or '2013-08-31 14_:07 / '2013-08-31T14_:07`.

Validating a greater than/less than numeric amount on php form

I am trying to create a form in which a logged in user can enter a sale (ltd_entry_amount), but only sales that are $200.00 or more, but with no luck. If I get rid of the '> 199.99' the form works ok but for now the 'Please check all manatory fields are complete and try again.' message shows. Can anyone help?
<?php
require_once ('./includes/config.inc.php');
$page_title = 'Log a Sale';
include ('./includes/header.html');
if (!isset($_SESSION['ltd_user_id'])) {
$url = 'http://' . $_SERVER['HTTP_HOST']
. dirname($_SERVER['PHP_SELF']);
if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) {
$url = substr ($url, 0, -1); // Chop off the slash.
}
$url .= '/login.php';
ob_end_clean(); // Delete the buffer.
header("Location: $url");
exit(); // Quit the script.
}
$users = $_SESSION['ltd_user_id'];
if (isset($_POST['submitted'])) {// Handle the form.
require_once ('database.php');
// Connect to the database.
$errors = array(); // Initialize error array.
// Check for a Invoice Number.
if (empty($_POST['ltd_invoice_no'])) {
$errors[] = '<p>• You forgot to enter your Invoice Number.</p>';
} else {
$inv = escape_data($_POST['ltd_invoice_no']);
}
// Check for invoice amount.
if (empty($_POST['ltd_entry_amount']) < 199.99) {
$errors[] = '<p>• You forgot to enter your Total Amount. Please ensure it is at least $200.00</p>';
} else {
$amount = escape_data($_POST['ltd_entry_amount']);
}
// Check for business name.
if (empty($_POST['ltd_business_name'])) {
$errors[] = '• You forgot to enter your Dealership Name.';
} else {
$dealer = escape_data($_POST['ltd_business_name']);
}
if (empty($errors) && $amount) { // If everything's OK. // If everything's OK.
// Make sure the invoice number is available.
$uid = #mysql_insert_id(); //Get the url ID.
// Add the user.
$query = "INSERT INTO ltd_sales_list (ltd_item_id , ltd_user_id, ltd_invoice_no, ltd_entry_amount, ltd_entry_userdate, ltd_business_name, ltd_entry_date) VALUES
('$uid', '$users', '$inv', '$amount', '$_POST[ltd_entry_userdate]', '$dealer' , NOW())";
$result = #mysql_query ($query); // Run the query.
if (mysql_affected_rows() == 1) {
// If it ran OK.
echo 'Your sale is registered into the system.';
include ('./includes/footer.html'); // Include the HTML footer.
exit();
} else { // If it did not run OK.
echo 'You could not be registered due to a system error. We apologize for any inconvenience.';
}
} else { // If one of the data tests failed.
echo 'Please check all manatory fields are complete and try again.';
}
mysql_close(); // Close the database connection.
} // End of the main Submit conditional.
?>
<form action="logsale.php" method="post">
<table width="550" border="0" cellspacing="1" cellpadding="5">
<tr>
<td width="250"><div align="right">Invoice Number <span class="red_light">*</span></div></td>
<td width="267">
<input type="text" name="ltd_invoice_no" size="30" maxlength="30" value="<?php if (isset($_POST['ltd_invoice_no'])) echo $_POST['ltd_invoice_no']; ?>" /></td>
</tr>
<tr>
<td><div align="right">Total Amount of sale
<em><strong>(exc. GST)</strong></em> <span class="red_light">*</span></div></td>
<td>
<input type="text" name="ltd_entry_amount" size="30" maxlength="30"
value="<?php if (isset($_POST['ltd_entry_amount'])) echo $_POST['ltd_entry_amount']; ?>" /></td>
</tr>
<tr>
<td></td>
<td>Please enter number only</td>
</tr>
<tr>
<td><div align="right">Date of Invoice</div></td>
<td>
<script type="text/javascript">
$(function() {
$("#datepicker").datepicker({ dateFormat: "dd/mm/yy" }).val()
});
</script>
<input size="30" maxlength="10" id="datepicker" name="ltd_entry_userdate" type="text" value="<?php if (isset($_POST['ltd_entry_userdate'])) echo $_POST['ltd_entry_userdate']; ?>" /></td>
</tr>
<tr>
<td></td>
<td><span class="sml_italics"><strong>Please enter as <strong>DD-MM-YYYY</strong></td>
</tr>
<tr>
<td><div align="right">Dealership <span class="red_light">*</span></div></td>
<td><input type="text" name="ltd_business_name" size="50" maxlength="60" value="<?php if (isset($_POST['ltd_business_name'])) echo $_POST['ltd_business_name']; ?>" /></td>
</tr>
<tr>
<td></td>
<td><p><input type="submit" name="submit" value="Submit" /></p><input type="hidden" name="submitted" value="TRUE" />
</td>
</tr>
</table>
</form>
<?php
include ('./includes/footer.html');
?>
if (empty($_POST['ltd_entry_amount']) < 199.99) {
You are comparing a boolean value with a float number
You must separate both conditions:
if(empty($_POST['ltd_entry_amount']) or $_POST['ldt_entry_amount'] < 199.99){
It looks like there is a problem with your if statement:
if (empty($_POST['ltd_entry_amount']) < 199.99)
should be
if (empty($_POST['ltd_entry_amount']) || $_POST['ltd_entry_amount'] < 199.99)

isset() not working properly on form

I have a registration form that user submits, data is sent using isset($_POST) to see if there is anything that was put into form input boxes. If not it is sent to an else which then sends it to a function that returns the user back to registration form to complete some missing forms. For some reason it is not working properly.
Here is my checking code -------
function returnBack(){
header("Location:register.php");
exit;
}
if(isset($_POST['myusername']))
{
$myusername = $_POST['myusername'];
}
else
{
returnBack();
}
if(isset($_POST['mypassword'])) {
$mypassword=$_POST['mypassword'];
}
else{
returnBack();
}
if(isset($_POST['myemail'])) {
$myemail=$_POST['myemail'];
}
else{
returnBack();
}
if(isset($_POST['myname'])) {
$myname=$_POST['myname'];
}
else{
returnBack();
}
if(isset($_POST['mylastname'])){
$mylastname=$_POST['mylastname'];
}
else{
returnBack();
}
/////////////////////////////////////////////////////////////*******CONNECT TO SERVER ******************************************************************/
try {
# MySQL with PDO_MYSQL
$DBH = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch(PDOException $e) {
echo "I'm sorry, I'm afraid I can't do that.";
file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}
////////////////////////////////////////////////////////////***********INSERT REGISTER DATA INTO DB ***************************************************************/
//$encrypt_password = md5($mypassword);
$insertdata = $DBH->prepare("INSERT INTO members (username, password, email, firstname, lastname ) VALUES ('$myusername','$mypassword','$myemail','$myname','$mylastname')");
$insertdata->execute();
echo "success";
$DBH = null;
Here is the form section ------------------------------
<table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form name="register" method="post" action="insertnewmem.php">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td colspan="3"><strong>Registration Form </strong></td>
</tr>
<tr>
<td width="78">Username</td>
<td width="6">:</td>
<td width="294"><input name="myusername" type="text" id="myusername" ></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input name="mypassword" type="text" id="mypassword"></td>
</tr>
<tr>
<td>Email</td>
<td>:</td>
<td><input name="myemail" type="text" id="myemail"></td>
</tr>
<tr>
<td>First Name</td>
<td>:</td>
<td><input name="myname" type="text" id="myname"></td>
</tr>
<tr>
<td>Last Name</td>
<td>:</td>
<td><input name="mylastname" type="text" id="mylastname"></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td><input type="submit" name="Submit" value="Register"></td>
</tr>
</table>
</td>
</form>
</tr>
</table>
UPDATED ----------------------------------------------
Sorry it skips the function returnBack() and just inserts it into db even if form not properly filled.
Try !empty() instead of isset(). This will evaluate to true only if there is something other than null, false, 0, or empty string ''. You probably have empty strings being submitted.
Others have posted answer, but let me explain why.
isset() checks to see if the value was set, not what the value is, but simply if it has a value. When you submit your form, you are passing an empty string as the value for each of the inputs.
Normally I check this using:
if(isset($_POST['variable']) && $_POST['variable'] !== "")
The first part makes sure the variable exists ( so that the second condition will not throw an error ) and the second condition makes sure that the string is not empty.

Categories