php validation code format - php

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
}
?>

Related

my INSERT INTO is not working in PHP page but working in SQL

i have here a page for the registering a crew but i dont know what seems to be the problem. the query is working in phpmyadmin but not working in php page.
here is my code:
session_start();
require 'config.php';
if (#$_SESSION['username']) {
if (isset($_POST['first_name'])&&isset($_POST['middle_name'])&&isset($_POST['last_name'])&&isset($_POST['age'])&&isset($_POST['birth_date'])&&isset($_POST['birth_place'])&&isset($_POST['gender'])&&isset($_POST['martial_status'])&&isset($_POST['religion'])&&isset($_POST['nationality'])&&isset($_POST['email'])&&isset($_POST['address1'])&&isset($_POST['address2'])&&isset($_POST['course'])&&isset($_POST['school'])&&isset($_POST['remarks'])) {
$first_name = $_POST['first_name'];
$middle_name = $_POST['middle_name'];
$last_name = $_POST['last_name'];
$age = $_POST['age'];
$birth_date = $_POST['birth_date'];
$birth_place =$_POST['birth_place'];
$gender = $_POST['gender'];
$martial_status = $_POST['martial_status'];
$religion = $_POST['religion'];
$nationality = $_POST['nationality'];
$email = $_POST['email'];
$address1 = $_POST['address1'];
$address2 = $_POST['address2'];
$course = $_POST['course'];
$school = $_POST['school'];
$remarks = $_POST['remarks'];
$date_added = date('Y-m-d');
if (!empty($first_name)&&!empty($middle_name)&&!empty($last_name)&&!empty($age)&&!empty($birth_date)&&!empty($birth_place)&&!empty($gender)&&!empty($martial_status)&&!empty($religion)&&!empty($nationality)&&!empty($email)&&!empty($address1)&&!empty($course)&&!empty($school)) {
$query = "INSERT INTO `crew_info` (first_name,middle_name,last_name,age,birth_date,birth_place,gender,martial_status,religion,nationality,email_address,address_1,address_2,course,school_graduated,remarks,date_added,crew_status) VALUES ('$first_name','$middle_name','$last_name','$age','$birth_date','$birth_place','$gender','$martial_status','$religion','$nationality','$email','$address1','$address2','$course','$school','$remarks','$date_added','PENDING')";
echo 'Crew Successfuly Send to "PENDING PAGE"';
}
else {
echo 'Some field is empty';
}
}
echo '<!DOCTYPE html>
<html>
<head>
<title>Add New Crew</title>
</head>
<body>
<form action="add_crew.php" method="POST">
<table>
<tr>
<td>
First Name:
</td>
<td>
<input type="text" name="first_name" ></input>
</td>
</tr>
<tr>
<td>
Middle Name:
</td>
<td>
<input type="text" name="middle_name" ></input>
</td>
</tr>
<tr>
<td>
Last Name:
</td>
<td>
<input type="text" name="last_name" ></input>
</td>
</tr>
</table><br>
<table>
<tr>
<td>
Age:
</td>
<td>
<input type="text" name="age" ></input>
</td>
</tr>
<tr>
<td>
Birth Date:
</td>
<td>
<input type="text" name="birth_date" ></input>
</td>
</tr>
<tr>
<td>
Birth Place:
</td>
<td>
<input type="text" name="birth_place" ></input>
</td>
</tr>
</table><br>
<table>
<tr>
<td>
Gender:
</td>
<td>
<input type="text" name="gender" ></input>
</td>
</tr>
<tr>
<td>
Martial Status:
</td>
<td>
<input type="text" name="martial_status" ></input>
</td>
</tr>
<tr>
<td>
Religion:
</td>
<td>
<input type="text" name="religion" ></input>
</td>
</tr>
</table><br>
<table>
<tr>
<td>
Nationality:
</td>
<td>
<input type="text" name="nationality" ></input>
</td>
</tr>
<tr>
<td>
Email Address:
</td>
<td>
<input type="text" name="email" ></input>
</td>
</tr>
</table><br>
<table>
<tr>
<td>
Address 1:
</td>
<td>
<input type="text" name="address1" ></input>
</td>
</tr>
<tr>
<td>
Address 2:
</td>
<td>
<input type="text" name="address2"></input>
</td>
</tr>
</table><br>
<table>
<tr>
<td>
Course:
</td>
<td>
<input type="text" name="course" ></input>
</td>
</tr>
<tr>
<td>
School Graduated:
</td>
<td>
<input type="text" name="school" ></input>
</td>
</tr>
</table><br>
<table>
<tr>
<td>
Remarks:
</td>
<td>
<input type="text" name="remarks"></input>
</td>
</tr>
</table><br>
<input type="submit" value="Submit"></input>
</form>
</body>
</html>';
}
else { header('Location: /practice1/index.php');
}
?>
this is the entire page of php
Just like Saty say you forget to insert query
$conn->query($query); // PDO for new php7
mysql_query($query,$conn); // for old code but this is deprecated
//$conn is mysql_connect in config.php (it's may be in another variable up on your write)
<?php if (!empty($first_name)&&!empty($middle_name)&&!empty($last_name)&&!empty($age)&&!empty($birth_date)&&!empty($birth_place)&&!empty($gender)&&!empty($martial_status)&&!empty($religion)&&!empty($nationality)&&!empty($email)&&!empty($address1)&&!empty($course)&&!empty($school)) {
$query = "INSERT INTO `crew_info` (first_name,middle_name,last_name,age,birth_date,birth_place,gender,martial_status,religion,nationality,email_address,address_1,address_2,course,school_graduated,remarks,date_added,crew_status)
VALUES ('$first_name','$middle_name','$last_name','$age','$birth_date','$birth_place','$gender','$martial_status','$religion','$nationality','$email','$address1','$address2','$course','$school','$remarks','$date_added','PENDING')";
// for mysqli code starts
mysqli_query($con, $query);
// for mysqli code ends where $con is connection variable
echo 'Crew Successfuly Send to "PENDING PAGE"';
}
?>
you have to fire the query to insert in database , i think you forgot
add this code after your query to execute it
if (mysqli_query($conn,$query)) {
echo 'Your request is sent to queue';
}
else {
echo 'Something went wrong';
}
I think you missed Two points
1.connection between your php and mysql.
2.Firing the query.
Try with this snippet.
$username = "your_name";
$password = "your_password";
$dbhost = "localhost";
$conn = mysql_connect($dbhost, $username, $password);
//connection to the database
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
and then put
if (!empty($first_name)&&!empty($middle_name)&&!empty($last_name)&&!empty($age)&&!empty($birth_date)&&!empty($birth_place)&&!empty($gender)&&!empty($martial_status)&&!empty($religion)&&!empty($nationality)&&!empty($email)&&!empty($address1)&&!empty($course)&&!empty($school)) {
$query = "INSERT INTO `crew_info` (first_name,middle_name,last_name,age,birth_date,birth_place,gender,martial_status,religion,nationality,email_address,address_1,address_2,course,school_graduated,remarks,date_added,crew_status) VALUES ('$first_name','$middle_name','$last_name','$age','$birth_date','$birth_place','$gender','$martial_status','$religion','$nationality','$email','$address1','$address2','$course','$school','$remarks','$date_added','PENDING')";
After that fire your query
if (mysqli_query($conn,$query))
{
echo 'Crew Successfuly Send to "PENDING PAGE"';
}
else
{
echo 'Some Syntax is wrong';
}
}
else {
echo 'Some field is empty';
}
And close the connection after used by
mysql_close($conn);
#prakash above is the closest to correct...
however, i think, set all of your inputs on your html with value="", so that you do not have to do all of the if(!empty() garbage and get blanks later...
$username = "your_name";
$password = "your_password";
$dbhost = "localhost";
$dbname = "your_db";
// just good practice to specify the db, later you may have multiple on the same server..
// use mysqli as someone else above stated...
$conn = mysqli_connect($dbhost, $username, $password,$dbname);
if(!$conn){
die('Connect Error: ' . mysqli_connect_error());
//again.. mysqli.. not mysql
}
// dont kill yourself with manual entry errors for the query...
// move $_POST to a new variable and prep the array for a loop;
$data = $_POST;
// get rid of the submit variable
unset($data['submit']);
// assuming this db field is int not varchar
// and assuming birthdate field is DATE or varchar
$data['age'] = intval($data['age']);
$data['birthdate'] = date('Y-m-d',strtotime($date['birthdate']));
// would be easier to set default value NOW() for date_added column and DATETIME
// NOW() will set that field to the CURRENT_TIMESTAMP on every insert for you...
// but the way you have it, and assuming db field is DATE or varchar
$data['date_added'] = date('Y-m-d');
// Same for 'crew_status' .. field VARCHAR or ENUM... default value 'PENDING'
$data['crew_status'] = 'PENDING';
// make a string variable to fill with fields...
$fields = '';
// make a string variable to to fill with insert values....
$values = '';
// loop through $data, add each value followed by a comma to string
// no single quotes on integers where the db field is INT .... like age...
foreach($data as $key=>$val){
// this is looking for the value="" from when a user blanks an input field....
if($val == ''){
// handles blank user inputs.. db fields NOT set 'not null'..no quotes around NULL
$values .= 'NULL,';
// if the value is not blanked... look for strings and dates....
}elseif(!is_int($val)){
// real_escape_string will kill any characters that will error like ' or \
// and remove in sql injection risks .. single quotes on varchar db field vals
$values .="'".mysqli_real_escape_string($conn,$val)."',";
// if input is not blank and !is_int() must be INT...age
}else{
//no quotes on integers going into INT db fields....
$values .= $val.',';
}
// add the $key (field name) to the $fields same order as $values, comma after each
// backticks around field names...
$fields .= "`".$key."`,";
}
// we are dragging an extra comma on $fields and $values at the end of each string
// we will get them in the insert query string....splitting up the query to explain
$query = "INSERT INTO `crew_info`";
//substr off the comma $fields is dragging "," put it between ( and )
$query .= "(".substr($fields,0,-1).")";
//substr off the comma $values dragging "," put it between ( and )
$query .= " VALUES (".substr($values,0,-1).")";
//not split query might be confusing to read..query would look like...
//"INSERT INTO `crew_info`(".substr($fields,0,-1).") VALUES (".substr($values,0,-1).")"
//now insert
if(!mysqli_query($conn,$query)){
// if there is an error... let someone know!
die('ooops!...'.mysqli_error());
}else{
// if no error......
echo 'you just inserted data!!! id# = '. mysqli_insert_id($conn);
}
There is an error in your sql string. INSERT INTO table VALUES(..,..);
$query = "INSERT INTO `crew_info` VALUES (first_name,middle_name,last_name,age,birth_date,birth_place,gender,martial_status,religion,nationality,email_address,address_1,address_2,course,school_graduated,remarks,date_added,crew_status) VALUES ('$first_name','$middle_name','$last_name','$age','$birth_date','$birth_place','$gender','$martial_status','$religion','$nationality','$email','$address1','$address2','$course','$school','$remarks','$date_added','PENDING')";

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

How to post form data in mysql

At present I have set 4 variables, the values of which are then stored into mysql. This works fine. However, I don't want to set the values but write a line of code that takes these values from my form (on the same page). I have set the form method to POST and added specialchars to help security. Can someone pretty please show me one or two lines of code so I don't have to write ="John Doe". Please remember that I am very new all of this
<?php
// Connect to the Database
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "topsecretDontTell";
$dbname = "gaming";
$connection = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
// Show error if connection fails
if(mysqli_connect_errno()){
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() .")"
);
}
?>
<?php
// ordertbl
$customer_name = "John Doe";
$game_id = 3;
$reservation_start = "2015-01-05";
$requested_days = 1;
// removes single quotes (escapes strings)
$customer_name = mysqli_real_escape_string($connection, $customer_name);
//add into ordertbl
$query = "INSERT INTO ordertbl (customer_name,game_id,reservation_start,requested_days) VALUES ('{$customer_name}',{$game_id},'{$reservation_start}', {$requested_days})";
//Run query and test if there was a query error
$result = mysqli_query($connection, $query);
if (!$result) {
die("Database query failed.");
}
?>
<?php
//determine the name of the game via its id using a function
function GameTitle ($game_id){
$message = "";
if ($gameid ==1){
$message = "Fantasy World";
}
else if ($gameid ==2){
$message = "Sir Wags A Lot";
}
else if ($gameid ==3){
$message = "Take a Path";
}
else if ($gameid ==4){
$message = "River Clean Up";
}
else if ($gameid ==5){
$message = "PinBall";
}
else if ($gameid ==6){
$message = "Ghost girl";
}
else if ($gameid ==7){
$message = "Dress up";
}
else if ($gameid ==8){
$message = "Where is my hat?";
}
else {
$message = "Invalid ID";
}
return $message;
}
?>
</body>
</html>
<!--Link to the style sheet-->
<link href="styles.css" rel="stylesheet" type="text/css">
</head>
<!--Create Header (logo, title and navigation bar)-->
<body>
<div id='main'>
<div id='titleImage'><img title='Home' src='images/GLLogo.png' width='700' height='190' alt='Games Library Title' /></div>
<div id='menu-wrapper'>
<div id='menu'>
<ul>
<li><a href='index.html'>Home</a></li>
<li class='current_page_item'><a href='#'>Reservations</a></li>
</ul>
</div>
</div>
<!--Make the form-->
<div class="form">
<h1>Reservations</h1>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table width="755" border="3" cellpadding="6">
<tr>
<td width="195" align="right" bgcolor="#FF0000"><label for="customer_name">Name:</label></td>
<td width="370"><input name="customer_name" autofocus type="text" id="customer_name" size="35" maxlength="90" required autocomplete="off" /></td>
</tr>
<tr>
<td align="right" bgcolor="#FF0000"><label for="game_id">Game's ID:</label></td>
<td><input name="game_id" type="number" id="game_id" size="35" maxlength="50" min="1" /></td>
</tr>
<tr>
<td width="195" align="right" bgcolor="#FF0000"><button onClick="GameTitle(); return false">Search</button></td>
<td><input name="Result" type="text" id="demo" size="35" maxlength="50" /></td>
</tr>
<tr>
<td align="right" bgcolor="#FF0000"><label for="Loan">Number of Days you wish to borrow the Game</label></td>
<td><select name="requested_days" id="requested_days">
<option selected="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select></td>
</tr>
<tr> <!--put date into value field to get a calendar-->
<td align="right" bgcolor="#FF0000"><label for="reservation">Reservation Date:</label></td>
<td><input id="reservation_start" input name="reservation_start" type="" value="" placeholder="YYYY/MM/DD" pattern="(?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))" title="The date should be in the exact format: YYYY-MM-DD with leading zeros where necessary"/>
</tr>
<tr>
<td align="right" bgcolor="#FF0000"><label for="mysearch2">Enter your search string here : </label></td>
<td><input {background-colour: #E5F5EF;} id="mysearch2" type="search" placeholder="search"size="35" maxlength="50"/>
</tr>
<tr>
<td align="right" bgcolor="#FF0000"><input type="reset" name="Reset" id="button" value="Reset Form" /></td>
<td><input type="submit" name="button2" id="button2" value="Submit Form" /></td>
</tr>
</table>
</form>
</div>
</div>
</body>
</html>
<?php
// get rid of data in cache and close
mysqli_close($connection);
?>
Use the following, taking the POST variable from your form's <input name="customer_name"... element:
$customer_name=stripslashes($_POST['customer_name']);
$customer_name=mysqli_real_escape_string($connection,$_POST['customer_name']);
which will allow for names containing apostrophes like John O'Reilly.
Plus, you have function GameTitle ($game_id) therefore you most likely meant to use function GameTitle ($gameid)
You should use $_POST. In that array are post data. For example:
$customer_name = $_POST['name'];

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`.

How to update values to table fields in MySql from html form?

I am trying to update a table in my DB for the past two days. But I am unable to get it to work. Somebody please help me.
I could connect to my database, see my table fields perfectly. Posted values from the form could be read perfectly from the destined PHP file.
MySQL query doesn't seen to return any error.
But I dont understand why the values are not getting updated into the table.
//form.html
<form name="account" action="test.php" method="post">
<td align="left" valign="top" class="labelstyle" width="25%">First Name</td>
<td align="left" valign="top" class="labeltextstyle" width="75%"><input type="text" name="fname" value="" /></td>
<td align="left" valign="top" class="labelstyle" width="25%">Last Name</td>
<td align="left" valign="top" class="labeltextstyle" width="75%"><input type="text" name="lname" value="" /></td>
<td align="left" valign="top" class="labelstyle" width="25%">Email</td>
<td align="left" valign="top" class="labeltextstyle" width="75%"><input type="text" name="email" value="" /></td>
<td align="left" valign="top" class="labeltextstyle"><input type="submit" name="submit" value="Save" /></td>
</form>
// test.php
<?php
$dbhost = "localhost";
$dbname = "test";
$dbuser = "";
$dbpass = "";
mysql_connect ( $dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error());
mysql_select_db($dbname) or die(mysql_error());
session_start();
if(isset($_REQUEST['submit'])){
// $query = "select * from form";
// $result = mysql_query($query);
// $numcolumn = mysql_num_fields($result);
// for ( $i = 0; $i < $numcolumn; $i++ ) {
// $columnnames = mysql_field_name($result, $i);
// echo $columnnames;
// }
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
echo $fname ;
echo $lname ;
echo $email ;
$query = "update test set
fname = $fname,
lname = $lname,
email = $email
where 1 ";
$result = mysql_query($query);
if ($query = 1) {
echo "IT WORKED";
} else {
echo "DIDNT WORK";
}
}else{
echo "NOT SUBMITTED";
}
?>
//form.html
<form name="account" action="test.php" method="post">
<td align="left" valign="top" class="labelstyle" width="25%">First Name</td>
<td align="left" valign="top" class="labeltextstyle" width="75%"><input type="text" name="fname" value="" /></td>
<td align="left" valign="top" class="labelstyle" width="25%">Last Name</td>
<td align="left" valign="top" class="labeltextstyle" width="75%"><input type="text" name="lname" value="" /></td>
<td align="left" valign="top" class="labelstyle" width="25%">Email</td>
<td align="left" valign="top" class="labeltextstyle" width="75%"><input type="text" name="email" value="" /></td>
<td align="left" valign="top" class="labeltextstyle"><input type="submit" name="submit" value="Save" /></td>
</form>
When i fill the form with values A, B and C and submit the form, I get the following output.
fnamelnameemailABCIT WORKED
please help me soon.
There is no id in the where clause to indicate which row must be updated. This will update all the rows in the table. It should look like this:
$query = "update test set
fname = $fname,
lname = $lname,
email = $email
where id = 1";
I assume that a row is created beforehand so that you know which row to update. If not then rather use an INSERT statement should be used.
$query = "insert into test (fname,lname,email) VALUES ($fname,$lname,$email);
fname, lname and email are strings, which have to be escaped in the SQL query:
$query = "update test set
fname = '$fname',
lname = '$lname',
email = '$email'
where 1";
You probably can leave the where 1 as well.

Categories