PHP/MySQL query isn't working - php

I'm trying to a add a tire to a database of tires from a form. If I use a var_dump, the query is right, but it isn't inserting anything into the database. Here is my code.
<?php
require('../includes/database_connection.php');
error_reporting(E_ALL);
ini_set('display_errors', 1);
$idtires = '';
$size = $_POST["size"];
$idbrand = $_POST["idbrand"];
$price = $_POST["price"];
$mileage = $_POST["mileage"];
$idterrain = $_POST["idterrain"];
$idvehicle = $_POST["idvehicle"];
$idtiremodel = $_POST["idtiremodel"];
function add_tire($idtires, $size, $idbrand, $price, $mileage, $idterrain, $idvehicle, $idtiremodel) {
global $db;
$query = "INSERT INTO tires
(idtires, size, idbrand, price, mileage, idterrain, idvehicle, idtiremodel)
VALUES
($idtires, '$size', '$idbrand','$price', '$mileage', '$idterrain', '$idvehicle', '$idtiremodel')";
var_dump($query);
// var_dump($db);
$db->exec($query);
}
add_tire($idtires, $size, $idbrand, $price, $mileage, $idterrain, $idvehicle, $idtiremodel);
include('add.php');
?>
HERE IS ADD.PHP form:
<table>
<form method='post' action='addatire.php' name='addform' id='addform'>
<tr>
<td>
<p>
<label for='size'>Size:</label><br />
</p>
</td>
<td>
<p>
<input type='text' name='size' required value="<?php echo(isset($size['size'])); ?>"/>
</p>
</td>
</tr>
<tr>
<td>
<p>
<label for='idbrand'>Brand ID:</label><br/>
</p>
</td>
<td>
<p>
<input type='text' name='idbrand' required value="<?php echo(isset($idbrand['idbrand'])); ?>"/>
</p>
</td>
</tr>
<tr>
<td>
<p>
<label for='price'>Price:</label><br/>
</p></td>
<td><p>
<input type='text' name='price' required value="<?php echo(isset($price['price'])); ?>"/>
</p></td>
</tr>
<tr>
<td>
<p>
<label for='mileage'>Mileage:</label><br/>
</p></td>
<td><p>
<input type='text' name='mileage' required value="<?php echo(isset($mileage['mileage'])); ?>"/>
</p></td>
</tr>
<tr>
<td>
<p>
<label for='idterrain'>Terrain ID:</label><br/>
</p></td>
<td><p>
<input type='text' name='idterrain' required value="<?php echo(isset($idterrain['idterrain'])); ?>"/>
</p></td>
</tr>
<tr>
<td>
<p>
<label for='idvehicle'>Vehicle ID:</label><br/>
</p></td>
<td><p>
<input type="text" name="idvehicle" required value="<?php echo(isset($idvehicle['idvehicle'])); ?>"/>
</p></td>
</tr>
<tr>
<td>
<p>
<label for='idtiremodel'>Tire Model ID:</label><br/>
</p></td>
<td><p>
<input type="text" name="idtiremodel" required value="<?php echo(isset($idtiremodel['idmodel'])); ?>"/>
</p></td>
</tr>
<tr>
<td><p>
<input type="submit" name="action" value="Add A Tire"/>
</p></td>
</tr>
</form>
</table>
<?php echo get_tires(); ?>
</div>
?>
HERE is the database connection:
<?php
if ($_SERVER['HTTP_HOST'] == "localhost" OR $_SERVER['HTTP_HOST'] == "127.0.0.1") {
// login locally
$dsn = 'mysql:host=localhost;dbname=?';
$username = ?;
$password = ?;
} else {
// login online
$dsn = 'mysql:host=localhost;dbname=?';
$username = '?';
$password = '?';
}
try {
$db = new PDO($dsn, $username, $password);
} catch (PDOException $e) {
$error_message = $e->getMessage();
include('database_error.php');
exit();
}
?>
My usernames and passwords aren't really ? though, I'm just using those here for the sake of privacy and safety.

You're probably getting an error on your insert and just not seeing it:
$db->exec($query) or die(print_r($db->errorInfo(), true));

Related

PHP form submission error showing unsucess

I created this form with PHP and MySQL. Whenever I submit the form and click update button it is showing unsucess. I don't know what is going wrong and I need help finding the problem. I've attached the code below.
<?php
error_reporting(E_ALL & ~E_NOTICE);
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
$con = mysqli_connect("localhost","root","") or die("unable to connect");
mysqli_select_db($con,'studentdb');
if(isset($_GET['registernumber']))
$registernumber = html_entity_decode($_GET['registernumber']);
$query= "SELECT * FROM studenttble WHERE registernumber='$registernumber'";
$query_run = mysqli_query($con,$query);
while($row = mysqli_fetch_array($query_run, MYSQL_ASSOC))
{
$IID = $row['IID'];
$studentname = $row['studentname'];
$fathername = $row['fathername'];
$registernumber = $row['registernumber'];
$year = $row['$year'];
$dept = $row['$dept'];
$section = $row['section'];
$gender = $row['gender'];
$password = $row['password'];
$email = $row['email'];
$dob = $row['dob'];
$raddress = $row['raddress'];
$mnumber = $row['mnumber'];
}
?>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post" id="form1" class="myform">
<table align="center">
<tr>
<td>
<input name="estudentname" type="text" id="studentname" class="wp-form-control wpcf7-text" value="<?php echo $studentname?>" />
</td>
</tr>
<br>
<tr>
<td>
<input name="efathername" type="text" id="fathername" class="wp-form-control wpcf7-text" value="<?php echo $fathername?>" />
</td>
</tr>
<tr>
<td>
<input type="hidden" name="registernumber" id="registernumber" class="wp-form-control wpcf7-text" value="<?php echo $registernumber?>" placeholder="Register Number" />
</td>
</tr>
<tr>
<td>
<input type="text" name="egender" id="gender" class="wp-form-control wpcf7-text" value="<?php echo $gender?>" />
</td>
</tr>
<tr>
<td><input type="text" name="eemail" type="email" id="email" class="wp-form-control wpcf7-text" value="<?php echo $email?>" />
</td>
</tr>
<tr>
<td>
<h3 class="table">Date Of Birth: <input type="text" name="edob" id="dob" type="date" class="dropdown-menu-left" value="<?php echo $dob?>" max="2017-02-08"/></td></tr>
</h3>
<tr>
<td> <input type="text" class="wp-form-control wpcf7-textarea" name="eraddress" cols="30" rows="10" value="<?php echo $raddress?>"></textarea>
</td>
</tr>
<tr>
<td> <input name="emnumber" type="text" id="mnumber" pattern="[789][0-9]{9}" class="wp-form-control wpcf7-text" max="10" value="<?php echo $mnumber?>" />
</td>
</tr>
<tr>
<td align="center">
<input type="submit" name="update" class="wpcf7-submit" value="update">
</td>
</tr>
</table>
</form>
<?php
if(isset($_POST['update']))
{
$con = mysqli_connect("localhost","root","") or die("unable to connect");
mysqli_select_db($con,'studentdb');
$estudentname = mysql_real_escape_string($_POST['estudentname']);
$efathername = mysql_real_escape_string($_POST['efathername']);
$egender = mysql_real_escape_string($_POST['egender']);
$eemail = mysql_real_escape_string($_POST['eemail']);
$edob = mysql_real_escape_string($_POST['edob']);
$eraddress = mysql_real_escape_string($_POST['eraddress']);
$emnumber = mysql_real_escape_string($_POST['emnumber']);
$targetid = mysqli_real_escape_string($_POST['registernumber']);
mysqli_select_db('studentdb');
$query = "UPDATE studenttble SET studentname ='$estudentname', fathername ='$efathername', gender ='$egender', email ='$eemail', dob ='$edob', raddress ='$eraddress', mnumber ='$emnumber' WHERE registernumber ='$targetid'";
$retval = mysqli_query( $query, $conn );
if($retval)
{
echo "sucess";
}
else
{
echo "unsucess";
}
}
?>

string as type of varchar in MySQL

i am inserting values iput by users that is two arrays ROOMTILTIE AND CAPACITY.. RoomTitle is varchar and capacity is intger type when i entered string such as "2s32" and capacity any integer value it does not insert it into the table but when both are integer then it works perfectly.. below is the code
<form name="venueform" method="post" >
<input type="hidden" name="check_submit" value="1" id="check_submit" />
<table width="450px">
</tr>
<tr>
<td valign="top"">
<label for="TotalRooms">Total Number of Rooms*</label>
</td>
<td valign="top">
<input type="text" name="TotalRooms" maxlength="50" size="10"id='sth'>
</td>
</tr>
<td colspan="2" style="text-align:left">
<input name="submit1 "type="submit" value="submit">
</td>
</tr>
</table>
</form>
mysql_connect("localhost","root","");//database connection
mysql_select_db("ossd");
for($i=0;$i<$_POST['TotalRooms'];$i++)
{
echo"<p>\n</p>";
?><form method="post">
<input type="text" name='RoomTitle[]' /><br />
<input type="text" name='Capacity[]' /><br />
echo"<input name='addvenue' type='submit'value='Submit me' />
</form>";
if (isset($_POST['addvenue'])) {
<div>
<?php echo "<pre>".print_r($_POST['RoomTitle'],true)."</pre>";
echo "<pre>".print_r($_POST['Capacity'],true)."</pre>";
mysql_connect("localhost","root","");//database connection
mysql_select_db("ossd");
foreach ($_POST['RoomTitle'] as $row=>$name)
{
$RoomTitle = $name;
$Capacity = $_POST['Capacity'][$row];
$RoomTitle= mysql_real_escape_string($name);
$Capacity = mysql_real_escape_string($_POST['Capacity'][$row]);
$order = "INSERT INTO wp_ossd_venue
(RoomTitle,Capacity)
VALUES
(".$RoomTitle.",".$Capacity.")";
$result = mysql_query($order);
}
if($result){
echo("<br>Succesfully Added");
} else{
echo("<br>Fail... Error");
}
}
Your Insert query should be :
$order = "INSERT INTO wp_ossd_venue
(RoomTitle,Capacity)
VALUES
('".$RoomTitle."',".$Capacity.")";

values not fetched in textboxes from database in php

I want all details of user to be fetched in textboxes to edit profile of user accordingly based on username stored in session I don't want which statement is wrong I am not able to fetch values in textboxes. Please help me.
Profile.php
<?php
include('connection.php');
//include('validation1.php');
session_start();
if( !empty($_SESSION['username']) && isset($_SESSION['username']))
{
$username=$_SESSION['username'];
$checkinfo = mysql_query("SELECT * FROM profile WHERE username=".'"$username"');
//$result=mysql_fetch_array($checkinfo);
while($result = mysql_fetch_array($checkinfo,MYSQL_ASSOC)){
$name =($result['name']);
$address =($result['address']);
$contact =($result['contact']);
$state =($result['state']);
$city = ($result['city']);
$username =($result['uname']);
$oldpass = ($result['opass']);
}
}
if (isset($_POST['submit']))
{
$name =($_POST['name_txt']);
$address =($_POST['address_txt']);
$contact =($_POST['contact_txt']);
$gender = ($_POST['gender']);
$country = ($_POST['country']);
$state =($_POST['state_txt']);
$city = ($_POST['city_txt']);
$username =($_POST['uname_txt']);
$oldpass = ($_POST['opass_txt']);
$newpass = ($_POST['npass_txt']);
$insquery="UPDATE INTO profile(name, address, contact,gender, country, state, city,username,opassword,npassword) VALUES ('$name','$address','$contact','$gender','$country','$state','$city','$username','$oldpass','$newpass')";
$result=mysql_query($insquery);
// header("location:display.php");
if(!$insquery)
{
echo "Error Save [".mysql_error()."]";
}
/*else
{
// header("location:display.php");
}*/
}
?>
<body>
<form id="form1" name="form1" method="post" action="">
<div align="center">
Registration Form
</div>
<div align="right">
<?php if(isset($_SESSION['username']))
{
$s="Hello,".$_SESSION["username"];
$r=$_SESSION["userrole"];
echo $s;
} ?><a href='logout.php' id='logout'>Logout</a>
</div>
<table>
<tr>
<td><label>Name:</label></td>
<td><input name="name_atxt" type="text" id="name_atxt" value="<?php echo $name; ?>" /></td>
</tr>
<tr>
<td><label>Address:</label></td>
<td><textarea name="address_txt" cols="40" rows="4" value="<?php echo $address; ?>"></textarea></td>
</tr>
<tr>
<td><label>Contact:</label></td>
<td><input name="contact_txt" type="text" id="contact_ntxt" value="<?php echo $contact; ?>" /></td>
</tr>
<tr>
<td><label>Gender:</label>
<td>
<input type=radio name=gender value="male" id=male >Male</br>
<input type=radio name=gender value="female" id=female >Female</br></td>
</td>
</tr>
<tr>
<td><label>Country:</label></td>
<td><select name="country_select" id="country_select">
<option value="0">--select a country--</option>
<option value="India">India</option>
<option value="USA">USA</option>
<option value="UK">UK</option>
<option value="Australia">Australia</option>
</select></td>
</tr>
<tr>
<td><label>State:</label></td>
<td><input name="state_atxt" type="text" id="state_atxt" value="<?php echo $state; ?>"/></td>
</tr>
<tr>
<td><label>City:</label></td>
<td><input name="city_atxt" type="text" id="city_atxt" value="<?php echo $city; ?>" /></td>
</tr>
<tr>
<td><label>Username:</label></td>
<td><input name="uname_txt" type="text" id="uname_txt" value="<?php echo $username; ?>" /></td>
</tr>
<tr>
<td><label>Old Password:</label></td>
<td><input name="opass_txt" type="password" id="opass_txt" value="<?php echo $oldpass; ?>" /></td>
</tr>
<tr>
<td><label>New Password:</label></td>
<td><input name="npass_txt" type="text" id="npass_txt" /></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="Submit" id="btn1" /></td>
<td><input name="reset_btn" type="reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>
I want values already stored in database should be fetched in textbox of particular user who is in session and it is not fetching values in textbox.
$checkinfo = mysql_query("SELECT * FROM profile WHERE username=".'"$username"');
should be
$checkinfo = mysql_query("SELECT * FROM profile WHERE username='$username'");
Also your UPDATE syntax is incorrect
SQL UPDATE Statement:
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value

PHP Class: Not inserting data: Second Query

I have a class called contacts. In this class I have a method called addContact(). The first statement execute correct, but it seems like it does not get the $db->lastInsertId(). Need some help please. Here is my code:
public function addContact($addcontactfirstname,$addcontactmiddlename,$addcontactlastname,$addcontactstreetnumber, $addcontactstreetname, $addcontactsuburb, $addcontactcity, $addcontactemailhome, $addcontactemailwork,$addcontacthomephone, $addcontactcellphone, $addcontactworkphone){
$addsuccessfully = true;
$addcontact_id = 0;
try {
$db = database::databaseConnect();
$stmt1 = $db->prepare('INSERT INTO personalinfo (firstname, middlename, lastname) VALUES (:addcontactfirstname, :addcontactmiddlename, :addcontactlastname)');
$stmt1->bindParam(':addcontactfirstname', $addcontactfirstname, PDO::PARAM_STR);
$stmt1->bindParam(':addcontactmiddlename', $addcontactmiddlename, PDO::PARAM_STR);
$stmt1->bindParam(':addcontactlastname', $addcontactlastname, PDO::PARAM_STR);
$successful1 = $stmt1->execute();
$addcontact_id = $db->lastInsertId();
if($successful1){
//$addcontact_id = $db->lastInsertId();
$successful1 = true;
$stmt2 = $db->prepare('INSERT INTO contactinfo (contact_id, streetnumber, streetname, suburbname, cityname, emailhome, emailwork, homephone, cellphone, workphone) VALUES (:addcontact_id, :addcontactstreetnumber, addcontactstreetname, :addcontactsuburb, :addcontactcity, :addcontactemailhome, :addcontactemailwork,:addcontacthomephone, :addcontactcellphone, :addcontactworkphone)');
$stmt2->bindParam(':addcontact_id', $addcontact_id, PDO::PARAM_INT);
$stmt2->bindParam(':addcontactstreetnumber', $addcontactstreetnumber, PDO::PARAM_STR);
$stmt2->bindParam(':addcontactstreetname', $addcontactstreetname, PDO::PARAM_STR);
$stmt2->bindParam(':addcontactsuburb', $addcontactsuburb, PDO::PARAM_STR);
$stmt2->bindParam(':addcontactcity', $addcontactcity, PDO::PARAM_STR);
$stmt2->bindParam(':addcontactemailhome', $addcontactemailhome, PDO::PARAM_STR);
$stmt2->bindParam(':addcontactemailwork', $addcontactemailwork, PDO::PARAM_STR);
$stmt2->bindParam(':addcontacthomephone', $addcontacthomephone, PDO::PARAM_STR);
$stmt2->bindParam(':addcontactcellphone', $addcontactcellphone, PDO::PARAM_STR);
$stmt2->bindParam(':addcontacthomephone', $addcontactworkphone, PDO::PARAM_STR);
$successful2 = $stmt2->execute();
if($successful2){
$successful2 = true;
}
if(!$successful1 && !$successful2){
$addsuccessfully = false;
}
}
if($successful1 === true && $successful2 === true){
$addsuccessfully = true;
}
}
catch (PDOException $e) {
$addsuccessfully = false;
}
return $addsuccessfully;
}
I have a function that I call from my view page. Here is my function:
function addContact($addcontactfirstname,$addcontactmiddlename,$addcontactlastname,$addcontactstreetnumber, $addcontactstreetname, $addcontactsuburb, $addcontactcity, $addcontactemailhome, $addcontactemailwork,$addcontacthomephone, $addcontactcellphone, $addcontactworkphone){
global $addsuccessfully;
contacts::addContact($addcontactfirstname,$addcontactmiddlename,$addcontactlastname,$addcontactstreetnumber, $addcontactstreetname, $addcontactsuburb, $addcontactcity, $addcontactemailhome, $addcontactemailwork,$addcontacthomephone, $addcontactcellphone, $addcontactworkphone);
return $addsuccessfully;
}
And here is my page where I call the function. The page do say that the contact could not be added. I know the first query works as it the contact shows in the database, but it does not add the second bit into the contactinfo table of the database. Here is my view page:
<?php
/*The first thing that need to take place on this page is to ensure that the $admin value = 1.
* If the value is not 1 the user will get redirected to the home page. If the value of
* $admin = null, it then indicates that the user is not logged in. The system will then tell the
* user that he need to logon first, but also warn the user that if he is not an admin user he won't be
* allowed access to this page. This is to ensure that the user don't type the url address in
* his browser to try and access this page. This means that only admin users will be able to
* view this page while logged on and will be able to add new users. This will be an admin
* protected page. Protcted so the user must be logged in and and admin user.
*/
ini_set('display_errors', 1);
error_reporting(E_ALL);
require_once 'functions/functions.php';
checkLoggedIn(page::ADDCONTACT);
echo $message;
if ($pageID == 1){
require_once 'includes/adminmenu.php';
if($_POST){
$addcontactfirstname = $_POST['addcontactfirstname'];
$addcontactmiddlename = $_POST['addcontactmiddlename'];
$addcontactlastname = $_POST['addcontactlastname'];
$addcontactstreetnumber = $_POST['addcontactstreetnumber'];
$addcontactstreetname = $_POST['addcontactstreetname'];
$addcontactsuburb = $_POST['addcontactsuburb'];
$addcontactcity = $_POST['addcontactcity'];
$addcontactemailhome = $_POST['addcontactemailhome'];
$addcontactemailwork = $_POST['addcontactemailwork'];
$addcontacthomephone = $_POST['addcontacthomephone'];
$addcontactcellphone = $_POST['addcontactcellphone'];
$addcontactworkphone = $_POST['addcontactworkphone'];
$errors = array();
$homephonelength = false;
$cellphonelength = false;
$workphonelength = false;
//$addsuccessfully = true;
stripUserInput($addcontactfirstname,$addcontactmiddlename,$addcontactlastname,$addcontactstreetnumber,$addcontactstreetname,$addcontactsuburb,$addcontactcity,$addcontactemailhome,$addcontactemailwork,$addcontacthomephone,$addcontactcellphone,$addcontactworkphone);
if(empty($addcontactfirstname)){
$errors[] = 'First name can\'t be empty!';
}
if(empty($addcontacthomephone) && empty($addcontactcellphone) && empty($addcontactworkphone)){
$errors[] = 'You must enter at least one telephone number!';
}
if(!empty($addcontacthomephone)){
//$phonenumber = $addcontacthomephone;
$homephonelength = chechPhoneLenght($addcontacthomephone);
if($homephonelength === true){
$errors[] = 'The home phone number you entered is too short!';
}
}
if(!empty($addcontactcellphone)){
//$phonenumber = $addcontactcellphone;
$cellphonelength = chechPhoneLenght($addcontactcellphone);
if($cellphonelength === true){
$errors[] = 'The mobile phone number you entered is too short!';
}
}
if(!empty($addcontactworkphone)){
//$phonenumber = $addcontactworkphone;
$workphonelength = chechPhoneLenght($addcontactworkphone);
if($workphonelength === true){
$errors[] = 'The work phone number you entered is too short!';
}
}
if(!empty($addcontactemailhome)){
$email = $addcontactemailhome;
is_valid_email($email);
if (is_valid_email($email) === false){
$errors[] = 'You have entered an invalid home email address!';
}
}
if(!empty($addcontactemailwork)){
$email = $addcontactemailwork;
is_valid_email($email);
if(is_valid_email($email) === false){
$errors[] = 'You have entered an invalid work email address!';
}
}
if(empty($errors)){
//Add the contact
$addsuccessfully = addContact($addcontactfirstname,$addcontactmiddlename,$addcontactlastname,$addcontactstreetnumber, $addcontactstreetname, $addcontactsuburb, $addcontactcity, $addcontactemailhome, $addcontactemailwork,$addcontacthomephone, $addcontactcellphone, $addcontactworkphone);
if($addsuccessfully === true){
echo 'New contact added successfully!';
}else{
echo 'New contact could not be add. Please go back and try again!';
}
}else{
echo '<b>Please fix the following errors and try again!</b><br>';
foreach ($errors as $key => $error_message){
echo '<font color="red"><em>' . $error_message . '</font></em><br>';
}
?>
<h1>Add new contact</h1>
<p><em>Fields marked with <font color="red">*</font> must be completed.</em></p>
<form action="addcontact.php" method="post">
<table cellpadding="5">
<tr>
<td>
<b>First name:</b> <font color="red">*</font>
</td>
<td>
<input type="text" name="addcontactfirstname" value="<?php echo $addcontactfirstname; ?>" />
</td>
</tr>
<tr>
<td>
<b>Middle name:</b>
</td>
<td>
<input type="text" name="addcontactmiddlename" value="<?php echo $addcontactmiddlename; ?>" />
</td>
</tr>
<tr>
<td>
<b>Last name:</b>
</td>
<td>
<input type="text" name="addcontactlastname" value="<?php echo $addcontactlastname; ?>" />
</td>
</tr>
<tr>
<td>
<b>Street number:</b>
</td>
<td>
<input type="text" name="addcontactstreetnumber" value="<?php echo $addcontactstreetnumber; ?>" />
</td>
</tr>
<tr>
<td>
<b>Street name:</b>
</td>
<td>
<input type="text" name="addcontactstreetname" value="<?php echo $addcontactstreetname; ?>" />
</td>
</tr>
<tr>
<td>
<b>Suburb:</b>
</td>
<td>
<input type="text" name="addcontactsuburb" value="<?php echo $addcontactsuburb; ?>" />
</td>
</tr>
<tr>
<td>
<b>City:</b>
</td>
<td>
<input type="text" name="addcontactcity" value="<?php echo $addcontactcity; ?>" />
</td>
</tr>
<tr>
<td>
<b>Email (H):</b>
</td>
<td>
<input type="text" name="addcontactemailhome" value="<?php echo $addcontactemailhome; ?>" />
</td>
</tr>
<tr>
<td>
<b>Email (W):</b>
</td>
<td>
<input type="text" name="addcontactemailwork" value="<?php echo $addcontactemailwork; ?>" />
</td>
</tr>
<tr>
<td colspan="2">
<font color="blue"><em><b>NOTE:</b> You must enter at least one telephone number.</em><br> The number must include the area code e.g 065553322!</font>
</td>
</tr>
<tr>
<td>
<b>Phone (H):</b>
</td>
<td>
<input type="text" name="addcontacthomephone" value="<?php echo $addcontacthomephone; ?>" />
</td>
</tr>
<tr>
<td>
<b>Mobile:</b>
</td>
<td>
<input type="text" name="addcontactcellphone" value="<?php echo $addcontactcellphone; ?>" />
</td>
</tr>
<tr>
<td>
<b>Phone (W):</b>
</td>
<td>
<input type="text" name="addcontactworkphone" value="<?php echo $addcontactworkphone; ?>" />
</td>
</tr>
<tr>
<td colspan="2" align="right">
<input type="submit" value="Add contact" value="<?php echo $addcontactfirstname; ?>" />
</td>
</tr>
</table>
</form>
<?php
}
}else{
?>
<h1>Add new contact</h1>
<p><em>Fields marked with <font color="red">*</font> must be completed.</em></p>
<form action="addcontact.php" method="post">
<table cellpadding="5">
<tr>
<td>
<b>First name:</b> <font color="red">*</font>
</td>
<td>
<input type="text" name="addcontactfirstname" />
</td>
</tr>
<tr>
<td>
<b>Middle name:</b>
</td>
<td>
<input type="text" name="addcontactmiddlename" />
</td>
</tr>
<tr>
<td>
<b>Last name:</b>
</td>
<td>
<input type="text" name="addcontactlastname" />
</td>
</tr>
<tr>
<td>
<b>Street number:</b>
</td>
<td>
<input type="text" name="addcontactstreetnumber" />
</td>
</tr>
<tr>
<td>
<b>Street name:</b>
</td>
<td>
<input type="text" name="addcontactstreetname" />
</td>
</tr>
<tr>
<td>
<b>Suburb:</b>
</td>
<td>
<input type="text" name="addcontactsuburb" />
</td>
</tr>
<tr>
<td>
<b>City:</b>
</td>
<td>
<input type="text" name="addcontactcity" />
</td>
</tr>
<tr>
<td>
<b>Email (H):</b>
</td>
<td>
<input type="text" name="addcontactemailhome" />
</td>
</tr>
<tr>
<td>
<b>Email (W):</b>
</td>
<td>
<input type="text" name="addcontactemailwork" />
</td>
</tr>
<tr>
<td colspan="2">
<font color="blue"><em><b>NOTE:</b> You must enter at least one telephone number.</em><br> The number must include the area code e.g 065553322!</font>
</td>
</tr>
<tr>
<td>
<b>Phone (H):</b>
</td>
<td>
<input type="text" name="addcontacthomephone" />
</td>
</tr>
<tr>
<td>
<b>Mobile:</b>
</td>
<td>
<input type="text" name="addcontactcellphone" />
</td>
</tr>
<tr>
<td>
<b>Phone (W):</b>
</td>
<td>
<input type="text" name="addcontactworkphone" />
</td>
</tr>
<tr>
<td colspan="2" align="right">
<input type="submit" value="Add contact" />
</td>
</tr>
</table>
</form>
<?php
}
}
if ($pageID == 0){
return header('Location: ./');
}
?>
From the docs on PDO
string PDO::lastInsertId ([ string $name = NULL ] ) Returns the ID of
the last inserted row, or the last value from a sequence object,
depending on the underlying driver. For example, PDO_PGSQL() requires
you to specify the name of a sequence object for the name parameter.
Note:
This method may not return a meaningful or consistent result across different PDO drivers, because the underlying database may not even
support the notion of auto-increment fields or sequences.
Without seeing the schema there is no way to know but it is possible that you don't have an auto increment field in your database so the insert ID isn't being returned. In that case your second block of code would fail but the first would succeed.

How to Insert form values into MySQL database without refreshing the form and losing the field values of the form?

Hi,
I have a form and I want to insert its values into a MySQL database without refreshing the form and losing its values.
By clicking on the 'print' button the user should be able to generate a report from the data they entered in the form, but the form keeps refreshing on submit. So I would like to know how I can store the data in the database without having the form refreshed (i.e. using Ajax)?
Below is my form code:
<div class="commentpost"></div>
<form name="entry" id="entry" method="POST" action="">
<table border="1" bgcolor="Silver">
<tr>
<td>
</td>
<td>
<h2><b>Candidate Entry</b><h2>
</td>
</tr>
<tr>
<td>
Code
</td>
<td>
<input type="text" name="vouchno" value="New" onkeypress="return isNumberKey(event)" readonly="readonly" size="8" maxlength="8">
Date
<input type="text" id="vouchdt" name="vouchdt" id="popupDatepicker" tabindex="1" value="<?php echo (isset($_POST['vouchdt']) ? $_POST['vouchdt'] : ''); ?>"></td>
<td>
<input type="text" id='councode' name="councode" size="1" maxlength="2" value="<?php echo (isset($_POST['councode']) ? $_POST['councode'] : ''); ?>"><input type="text" id="counvouch" name="counvouch" size="8" value="<?php echo (isset($_POST['counvouch']) ? $_POST['counvouch'] : ''); ?>" maxlength="8">
<div id="cam">
</div>
<input type=button value="Configure..." onClick="webcam.configure()">
<input type=button value="Take Snapshot" onClick="take_snapshot()">
<div id="upload_results" style="background-color:#eee;"></div>
</td>
</tr>
<tr>
<td>
Name
</td>
<td>
<input type="text" id="name" name="name" value="<?php echo (isset($_POST['name']) ? $_POST['name'] : ''); ?>" maxlength="40" size="45" tabindex="2">
</td>
</tr>
<tr>
<td>
Address
</td>
<td>
<textarea name="add" id="add" row="3" cols="40" tabindex="3">
<?php echo (isset($_POST['vouchdt']) ? $_POST['vouchdt'] : ''); ?>
</textarea>
</td>
</tr>
<tr>
<td>
City
</td>
<td>
<input type="text" id="city" name="city" size="20" maxlength="20" value="<?php echo (isset($_POST['city']) ? $_POST['city'] : ''); ?>" tabindex="4">
Pin
<input type="text" id="pin" name="pin" size="6" maxlength="6" value="<?php echo (isset($_POST['pin']) ? $_POST['pin'] : ''); ?>" tabindex="5">
</td>
</tr>
<tr>
<td>
Nationality
</td>
<td>
<input type="text" id="ntn" name="ntn" value="<?php echo (isset($_POST['ntn']) ? $_POST['ntn'] : ''); ?>" size="10" maxlength="10" tabindex="6">
</td>
</tr>
<tr>
<td>
Mobile No
</td>
<td>
<input type="text" id="mob" name="mob" value="<?php echo (isset($_POST['mob']) ? $_POST['mob'] : ''); ?>" tabindex="7">
</td>
</tr>
<tr>
<td>
Date of Birth
</td>
<td>
<input type="text" id="dob" name="dob" value="<?php echo (isset($_POST['dob']) ? $_POST['dob'] : ''); ?>" id="popupDatepicker2" tabindex="8">
</td>
<td>
Age
</td>
<td width="9px">
<input type="text" id="age" name="age" size="3" maxlength="3" value="<?php echo (isset($_POST['age']) ? $_POST['age'] : ''); ?>" tabindex="9">
</td>
<td width="10px">
Sex
</td>
<td>
<select id="sex" name="sex" tabindex="12">
<?php
if(isset($_POST[sex])==m){
?>
<option value="<?php echo (isset($_POST['sex']) ? $_POST['sex'] : ''); ?>">Male</option>":
<?php }else{?>
<option value="<?php echo (isset($_POST['sex']) ? $_POST['sex'] : ''); ?>">Female</option>":
<?php }?>
<option value="m">Male</option>
<option value="f">Female</option>
</select>
</td>
</tr>
<tr>
<td>
Religion
</td>
<td>
<input type="text" id="rel" name="rel" value="<?php echo (isset($_POST['rel']) ? $_POST['rel'] : ''); ?>" size="20" maxlength="20" tabindex="11">
</td>
<td>
Martial Status
</td>
<td>
<select id ="status" name="status" tabindex="12">
<option value="">--select--</option>
<option value="1">Married</option>
<option value="2">Unmarried</option>
</select>
</td>
</tr>
<tr>
<td>
Passport No.
</td>
<td>
<input type="text" id="pass" name="pass" value="" size="15" maxlength="15" tabindex="13">
</td>
<td>
Place of Issue
</td>
<td>
<input type="text" id="poi" name="poi" size="20" maxlenght-20 tabindex="14">
</td>
<td>
Date of Issue
</td>
<td>
<input type="text" id="doi" name="doi" id="popupDatepicker4" tabindex="15">
</td>
</tr>
<tr>
<td>
Profession
</td>
<td>
<input type="text" id="prof" name="prof" size="20" maxlenght="20" value="" tabindex="16">
</td>
<td>
Amount
</td>
<td>
<input type="text" id="amt" name="amt" value="" size ="8" onblur="calculateText()" style="background-color:transparent; color:blue; text-align:right" tabindex="17">
</td>
</tr>
<tr>
<td>
Payment
</td>
<td>
<select id="pay" name="pay" tabindex="12">
<option value="">--select--</option>
<option value="f">Full</option>
<option value="p">Part</option>
<option value="n">None</option>
</select>
</td>
<td>
Received
</td>
<td>
<input type="text" id="resc" name="resc" value="" size ="8" onblur="calculateText()" style="background-color:transparent; color:green; text-align:right" tabindex="18">
</td>
</tr>
<tr>
<td>
Agent
</td>
<td>
<input type="tetx" id="agnt" name="agnt" value="" size="40" maxlength="40" tabindex="21">
</td>
<td>
Balance
</td>
<td>
<input type="text" id="bal" name="bal" readonly="readonly" value="" size ="8" style="background-color:transparent; color:red; text-align:right" onblur="calculateText()" tabindex="19">
</td>
</tr>
<tr>
<td>
Mofa No.
</td>
<td>
<input type="text" id="mofa" name="mofa" value="" size="20" maxlength="20" tabindex="22">
</td>
</tr>
<tr>
<td>
Remarks
</td>
<td>
<input type="text" id="rem" name="rem" size="60" maxlength="60" value="" tabindex="23">
</td>
</tr>
<table border="0" align="center">
<tr>
<td>
<input type="submit" name="save" value="Save"><input type="hidden" name="task" value="addComments" />
<td>
<input type="submit" name="print" value="Print">
</td>
<td>
<input type="submit" name="close" value="Cancel">
</td>
<td>
<input type="reset" name="Add" value="Add">
</td>
</tr>
</table>
</table>
</form>
</body>
</html>
Here is my JavaScript code:
<script type="text/javascript">
jQuery(document).ready(function($){
$("#entry").submit(function(){
ctask = this.task.value;
cvouchdt = this.vouchdt.value;
ccouncde = this.councode.value;
ccounvouch = this.counvouch.value;
cname = this.name.value;
ccity = this.city.value;
cpin = this.pin.value;
cntn = this.ntn.value;
cmob = this.mob.value;
cdob = this.dob.value;
cage = this.age.value;
csex = this.sex.value;
crel = this.rel.value;
cstatus = this.status.value;
cpass = this.pass.value;
crel = this.rel.value;
cpoi = this.poi.value;
cdoi = this.doi.value;
cprof = this.prof.value;
camt = this.amt.value;
cpay = this.pay.value;
cpass = this.pass.value;
crecd = this.recd.value;
cagnt = this.agnt.value;
cbal = this.bal.value;
cmofa = this.mofa.value;
crem = this.rem.value;
save = this.save;
if(cname=="" || ccounvouch=="" || ccouncde=="") { $("#errAll").html('<p>Invalid Captcha. Please try again.</p>'); }
$.post("submit.php", {task: ctask, name: cname, email: cemail, url: curl, message: cmessage}, function(data){
if(data=='0') { $("#errAll").html('<p>Please don\'t leave the requierd fields.</p>'); }
else if(data=='1') { $("#errAll").html('<p>Invalid Email Address, Please try again.</p>'); }
else { submitter.value="Value Saved"; save.disabled=false;} //$(data).appendTo($(".commentpost")); }
});
return false;
});
});
</script>
Here is my PHP code:
<?php
//include_once( 'config.php' );
require("includes/dbconnect.php");
$getmaxvou = mysql_query("SELECT MAX(`vouchno`) as `maxid` FROM `candidate` ") or die(mysql_error());
$max = mysql_fetch_array($getmaxvou);
$maxv =$max["maxid"]+1;
if(isset($_POST['task']) && $_POST['task'] == 'addComments')
{
$a = 1;
$date = mysql_real_escape_string($_POST["vouchdt"]);
$date = strtotime($date);
$date = date('Y-m-d',$date);
$cname = trim($_POST["name"]);
$add = trim($_POST["add"]);
$city = trim($_POST["city"]);
$pin = trim($_POST["pin"]);
$nations = trim($_POST["ntn"]);
$mob = trim($_POST["mob"]);
$dob = mysql_real_escape_string($_POST["dob"]);
$dob = strtotime($dob);
$dob = date('Y-m-d',$dob);
$age = trim($_POST["age"]);
$sex = trim($_POST["sex"]);
$rel = trim($_POST["rel"]);
$pass = trim($_POST["pass"]);
$status = trim($_POST["status"]);
$poi = trim($_POST["poi"]);
$doi = mysql_real_escape_string($_POST["doi"]);
$doi = strtotime($doi);
$doi = date('Y-m-d',$doi);
$prof = trim($_POST["prof"]);
$amt = trim($_POST["amt"]);
$pay = trim($_POST["pay"]);
$bal = trim($_POST["bal"]);
$recd = trim($_POST["resc"]);
$agnt = trim($_POST["agnt"]);
$mofa = trim($_POST["mofa"]);
$rem = trim($_POST["rem"]);
$councode = trim($_POST["councode"]);
$counvouch = trim($_POST["counvouch"]);
{
if (isset($_POST["code"])) {
$sql_check = mysql_query("SELECT * FROM candiidate WHERE code ='$councode' AND counvouch='$counvouch'");
if (mysql_num_rows($sql_check) > 0) {
$a = 0;
print '<script type="text/javascript">';
print 'alert("Code Already Exist For the Country")';
PRINT '</script>';
}
}
if($a ==1){
mysql_query("INSERT INTO `candidate`(vouchno, vouchdt, `name`, `add`, `city`, `pin`, `nationality`, mobile, dob, `religion`, `passport`, `profession`, amt, recd, bal, payment, `agent`, `mofa`, `age`, `gender`, `martial`, `poi`, doi, councode, counvouch, `rem` )
Values
('$maxv', '$date', '$cname', '$add', '$city', '$pin', '$nations', '$mob', '$dob', '$rel', '$pass', '$prof', '$amt', '$recd', '$bal', '$pay', '$agnt', '$mofa', '$age', '$sex', '$status', '$poi', '$doi', '$councode', '$counvouch', '$rem' )") or die(mysql_error());
echo ' <div class="commentbox">
<div class="commentboxt">Value Inserted </div>
</div>';
}
}
}?>
Change form tag to
<form name="entry" id="entry" method="GET" action="javascript:">
that will stop the page from refreshing.
Then look into jquery ajax http://api.jquery.com/jQuery.ajax/
For example.
var string ="FORMVALUE1=" + $('#FORMVALUE1ID').val() + "FORMVALUE2=" + $('#FORMVALUE2ID').val() + "REAPEAT FOR ALL YOUR VALUES";
$.ajax({
type: "GET",
url: "YOURPHPFILE.php",
data: string,
});
Then just get the form values in the php file by using $_GET['FORMVALUE1'];
You first seperate your PHP file where you insert or do some action.
PHP Action File: YourPHPPostFile.php
HTML File: index.html or whatever name you have.
Then in PHP file write all your code but in the begining add check that is
if(isset($_POST['task']) && $_POST['task'] == 'addComments')
{//Your all PHP Code here}
On the other hand in your html file make a AJAX request to this file and use POST Method in AJAX request and include your data within Request Parameters.
One more thing if you don't want to lose your Form data which is filled you can use:
<form name="entry" id="entry" method="GET" onsubmit="calltoAjax();return false;">
Now whenever user submit form then it will not reset the form and data also stored in your database.
Thanks,

Categories