PHP Class: Not inserting data: Second Query - php

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.

Related

php - Inserted data was not saving in phpmyadmin database

I want to save my data in my phpmyadmin database.But it's not saving. So while saving my data, it refresh the page but data not showing in database
Here is my class by which i want to save data:
class User{
public function __construct(){
$host='localhost';
$user='root';
$password='';
$conn=mysql_connect($host,$user,$password);
if(!$conn){
die("Database Not Connected" . mysql_error());
}
mysql_select_db("db_sign_up");
echo "Database created! ";
}
public function save_user($data){
$sql="INSERT INTO tbl_user(first_name,last_name,email_address,password,mobile_number,address,
city_name,country_name,zip_code)
VALUES('$data[first_name]','$data[last_name]','$data[email_address]','$data[password]',
'$data[mobile_number]','$data[address]','$data[city_name]','$datacountry_name]','$data[zip_code]')";
if(!mysql_query($sql)){
die("sl Error". mysql_error());
}
echo "Saved Successfully!";
//mysql_close($conn);
}
}
here is UI
<?php
require_once './classes/user.php';
$obj=new User();
if(isset($_POST['btn'])){
$obj->save_user($_POST);
}
?>
<html>
<head><title> Database Basic</title></head>
<body>
<form action="sign_up.php" method="post">
<table border="1">
<tr><td>Personal Information</td><td></td></tr>
<tr>
<td> First Name</td>
<td>
<input type="name" name="first_name" value="<?php if(isset($_POST['first_number'])){ echo htmlentities($_POST['first_name']);} ?> "/>
</td>
</tr>
<tr>
<td> Last Name</td>
<td>
<input type="name" name="last_name" value="<?php if(isset($_POST['last_name'])){ echo htmlentities($_POST['last_name']);} ?> "/>
</td>
</tr>
<tr>
<td> Email Address</td>
<td>
<input type="name" name="email_address" value="<?php if(isset($_POST['email_address'])){ echo htmlentities($_POST['email_address']);} ?> "/>
</td>
</tr>
<tr>
<td> Password</td>
<td>
<input type="password" name="password" value="<?php if(isset($_POST['password'])){ echo htmlentities($_POST['password']);} ?> "/>
</td>
</tr>
<tr>
<td> Mobile Number</td>
<td>
<input type="name" name="mobile_number" value="<?php if(isset($_POST['mobile_number'])){ echo htmlentities($_POST['mobile_number']);} ?> "/>
</td>
</tr>
<tr>
<td> Address</td>
<td>
<textarea name="address" rows="4" cols="30"></textarea>
</td>
</tr>
<tr>
<td> City</td>
<td>
<input type="" name="city_name" value="<?php if(isset($_POST['city_name'])){ echo htmlentities($_POST['city_name']);} ?> "/>
</td>
</tr>
<tr>
<td> Country</td>
<td>
<select name="country_name">
<option value=" ">Select Country ...</option>
<option value="bangladesh">Bangladesh</option>
<option value="srilanka">Srilanka </option>
<option value="india">India</option>
</select>
</td>
</tr>
<tr>
<td> Zip Code</td>
<td>
<input type="name" name="zip_code" value="<?php if(isset($_POST['zip_code'])){ echo htmlentities($_POST['zip_code']);} ?> "/>
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" name="btn" value="Save">
</td>
</tr>
</table>
</form>
</body>
You have an error in your INSERT STATEMENT:
you are using countryname variable in your query as:
'$datacountry_name]'
I think this should be like this:
'$data[country_name]'
Side note:
You are using mysql_ its deprecated I suggest you to use mysqli_ or PDO.
secondly your code is open for SQL Injection, you need to prevent with sql injection.
its function receives an array, then check your array. The type fields in the db, and if are properly filled.
field int type = int value
if it is returned as a string, you can convert this:
$string = $data[mobile_number];
$int = (int)$string; // convert string type for int.
or use the type varchar to the field
if not the case, say more about the your code.

PHP/MySQL query isn't working

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));

avoiding duplicate entries and caching entered form values

i have some code that controls duplicate entries in particular the USER ID. it checks in the database at submit and if that USER ID exists already it gives that notification. now the problem is when i submit and if that USER ID entered already exists in the database, all the other entries on the form are cleared, prompting me to re_enter all the other details again. i find this annoying and retrogressive. i want some help on how better i can do it such that only the USER ID text box returns empty, keeping other details safe/unchanged or indeed alternatively keeping/buffering/caching all details previously entered so that i can also review the duplicate USER ID before changing it.
new_user.php
<h1 align="center">Create New User</h1>
<p align="center" style="color:#F00"><?php if(isset($_GET['dup'])){ echo "That User ID Already Exists!"; } ?> </p>
<form id="form1" method="post" action="add_user.php">
<table width="100%">
<tr>
<td width="204"><div align="right">User ID:</div></td>
<td width="286">
<input type="text" name="user_id" id="user_id" />
</td>
</tr>
<tr>
<td><div align="right">Full Names:</div></td>
<td>
<input type="text" name="fname" id="fname" />
</td>
</tr>
<tr>
<td><div align="right">Gender:</div></td>
<td><select id="sex" name="sex">
<option selected="selected" value="male">Male</option>
<option name="female">Female</option>
</select></td>
</tr>
<tr>
<td><div align="right">NRC Number:</div></td>
<td>
<input type="number" name="nrcno" id="nrcno" min="1" />
</td>
</tr>
<tr>
<td><div align="right">Phone Number:</div></td>
<td>
<input type="number" name="cellno" id="cellno" />
</td>
</tr>
<tr>
<td><div align="right">Email Address:</div></td>
<td>
<input type="email" name="emailad" id="emailad" />
</td>
</tr>
<tr>
<td><div align="right">Position Held:</div></td>
<td>
<input type="text" name="posh" id="posh" />
</td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="create" id="create" value="Add User" /></td>
</tr>
</table>
</form>
add_user.php
<?php
$user_id=$_POST['user_id'];
$fname = $_POST['fname'];
$sex= $_POST['sex'];
$name= $_POST['name'];
$nrcno = $_POST['nrcno'];
$cellno= $_POST['cellno'];
$emailad = $_POST['emailad'];
$posh = $_POST['posh'];
require("get_func.php");
checkID($id);
include("connect.php");
mysql_select_db("ceec", $con);
$query = "INSERT INTO user VALUES ('$user_id', '$fname', '$sex','$name', '$nrcno', '$cellno', '$emailad', '$posh')";
if (mysql_query($query)){
header("Location: success.php");
}
else {echo "Nada" . mysql_error(); }
mysql_close($con);
?>
get_func.php
<?php
function checkID($id){
include_once("connect.php");
mysql_select_db("ceec",$con);
$query = "SELECT * FROM user WHERE user_id = '$id'";
$result= mysql_query($query);
if($row = mysql_fetch_array($result))
{
header("Location: new_user.php?dup=true");
break;
}
else {}
}
?>
<input type="text" name="user_id" id="user_id"
<?php if(isset($_POST['user_id'])){echo htmlentities($_POST['user_id'];} ?>/>

My PHP form works on my godaddy hosted website, but will not work on a yahoo hosted website, how can I correct this?

This form is for a website hosted on yahoo. I know it accepts php because I ran and test.php and it went through. The form goes nowhere after hitting submit on the yahoo website. I uploaded to another site and got an error message that says " Parse error: syntax error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or '}' in /home/ecdo02/public_html/emag/validate.class.php on line 4". So I tried it on my own website hosted by godaddy and no errors, the form went through successfully and it showed up in my email. Does anyone have an idea what's going on? Its very strange.
This is my request.php
<?php
define("EMAIL", "xxxxxxx#xxxxx.com");
if(isset($_POST['submit'])) {
include('validate.class.php');
//assign post data to variables
$firstname = trim($_POST['firstname']);
$lastname = trim($_POST['lastname']);
$company = trim($_POST['company']);
$address = trim($_POST['address']);
$city = trim($_POST['city']);
$state = trim($_POST['state']);
$zip = trim($_POST['zip']);
$email = trim($_POST['email']);
$phone = trim($_POST['phone']);
$fax = trim($_POST['fax']);
$title = trim($_POST['title']);
$interest = trim($_POST['interest']);
$comment = trim($_POST['comment']);
//start validating our form
$v = new validate();
$v->validateStr($firstname, "firstname", 3, 75);
$v->validateStr($lastname, "lastname", 3, 75);
$v->validateEmail($email, "email");
$v->validateStr($phone, "phone");
$v->validateStr($comment, "comment", 10, 500);
//use php's mail function to send the email
#mail($email_to, $subject ,$message ,$header );
if(!$v->hasErrors()) {
$header = "From: $email\n" . "Reply-To: $email\n";
$subject = "Lead from Website";
$email_to = EMAIL;
$message = "A message was submitted.
From: $title $firstname $lastname
Company: $company
Address: $address
City: $city
State/ Province/ Region: $state
Postal/ Zip Code: $zip
E-mail: $email
Phone: $phone
Fax: $fax
What would you like? $interest
Comments:
$comment
-End of message
";
//grab the current url, append ?sent=yes to it and then redirect to that url
$url = "http". ((!empty($_SERVER['HTTPS'])) ? "s" : "") . "://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
header('Location: '.$url."?sent=yes");
} else {
//set the number of errors message
$message_text = $v->errorNumMessage();
//store the errors list in a variable
$errors = $v->displayErrors();
//get the individual error messages
$firstnameErr = $v->getError("firstname");
$lastnameErr = $v->getError("lastname");
$phoneErr = $v->getError("phone");
$emailErr = $v->getError("email");
$commentErr = $v->getError("comment");
}//end error check
}
// end isset
?>
This is my validate.class.php
<?php
class validate {
public $errors = array();
public function validateStr($postVal, $postName, $min = 1, $max = 500) {
if(strlen($postVal) < intval($min)) {
$this->setError($postName, ucfirst($postName)." field is required.");
} else if(strlen($postVal) > intval($max)) {
$this->setError($postName, ucfirst($postName)." must be less than {$max} characters long.");
}
}// end validateStr
public function validateEmail($emailVal, $emailName) {
if(strlen($emailVal) <= 0) {
$this->setError($emailName, "Please enter an e-mail address");
} else if (!preg_match('/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[#][a-zA-Z0-9_]+([.][a- zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/', $emailVal)) {
$this->setError($emailName, "Please enter a valid e-mail address");
}
}// end validateEmail
/* Validate phone no to allow numbers only */
public function validatePhone($phoneVal, $phoneName) {
if (strlen($phoneVal) <= 0) {
$this->setError($phoneName, "Please enter your phone number");
} else if (preg_match('/[^0-9]/', $phoneVal)) {
$this->setError($phoneName, "Please enter a valid phone number");
}
} // end validatephone
/* sets an error message for a form element*/
private function setError($element, $comment) {
$this->errors[$element] = $comment;
}
/* returns the error of a single form element*/
public function getError($elementName) {
if($this->errors[$elementName]) {
return $this->errors[$elementName];
} else {
return false;
}
}
/* displays the errors as an html un-ordered list*/
public function displayErrors() {
$errorsList = "<ul class=\"errors\">\n";
foreach($this->errors as $value) {
$errorsList .= "<li>". $value . "</li>\n";
}
$errorsList .= "</ul>\n";
return $errorsList;
}
/* returns whether the form has errors*/
public function hasErrors() {
if(count($this->errors) > 0) {
return true;
} else {
return false;
}
}
/* returns a string stating how many errors there were*/
public function errorNumMessage() {
if(count($this->errors) > 1) {
$message = "There were " . count($this->errors) . " errors sending your message!\n";
} else {
$message = "There was an error sending your message!\n";
}
return $message;
}// end hasErrors
}// end class
?>
Here is the form
<form id="contact_form" method="post" action="request.php">
<fieldset>
<legend>Thank You</legend>
<div style="padding-left:100px">
<?php if(isset($_GET['sent'])): ?><table width="590" border="0">
<tr>
<td width="590" colspan="2"></td>
</tr>
<tr>
<td colspan="2">
<div style="padding:30px; text-align:center"><span style="font-size:24px; font-weight:bold; ">Thank You!<br /><br /><span style="font-family:Arial, Helvetica, sans-serif; font-size:15px; background:; padding:20px; width:300px;text-align:center">Your submission has been submitted.</span></div>
</td>
</tr>
</table></div><?php endif; ?>
</fieldset>
<fieldset>
<legend>Request</legend>
<div style="padding-left:100px">
<table width="590" border="0">
<tr>
<td colspan="2"></td>
</tr>
<tr>
<td colspan="2"></td>
</tr>
<tr>
<td width="195"><label>What would you like? </label></td>
<td width="395"><select name="interest">
<option value=""> -- Please select -- </option>
<option>Add me to your mailing list.</option>
<option>Send me an information kit.</option>
<option>Call me to set up a meeting.</option>
</select></td>
</tr>
</table></div>
</fieldset>
<fieldset>
<legend>Personal Info</legend>
<div style="padding-left:100px;">
<table width="590" border="0" cellpadding="10" cellspacing="5">
<tr>
<td width="195" align="right"><label><b>Title</b></label></td>
<td width="395"><select name="title" style="width:183px">
<option value=""> - Select Your Title - </option>
<option>Mr.</option>
<option>Mrs.</option>
<option>Miss</option>
<option>Ms.</option>
<option>Dr.</option>
<option>Prof.</option>
<option>Rev.</option>
<option>Other</option>
</select>
</td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td align="right"><label><b>First Name</b><span style="color: red"> *</span></label></td>
<td><input type="text" name="firstname" value="<?php echo htmlentities($firstname); ?>" /> <br /></td>
</tr>
<tr>
<td> </td>
<td><span class="errors"><?php echo $firstnameErr; ?></span></td>
</tr>
<tr>
<td align="right"><label><b>Last Name<span style="color: red"> *</span></b></label></td>
<td><input type="text" name="lastname" value="<?php echo htmlentities($lastname); ?>" /> <br /></td>
</tr>
<tr>
<td> </td>
<td><span class="errors"><?php echo $lastnameErr; ?></span></td>
</tr>
<tr>
<td><label><b>Company</b></label></td>
<td><input type="text" name="company" value="<?php echo htmlentities($company); ?>" /></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td><label><b>Street Address</b><span style="color: red"> *</span> </label></td>
<td><input type="text" name="address" value="<?php echo htmlentities($address); ?>" /></td>
</tr>
<tr>
<td> </td>
<td><span class="errors"><?php echo $addressErr; ?></span></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td><label><b>City</b><span style="color: red"> *</span></label> </td>
<td><input type="text" name="city" value="<?php echo htmlentities($city); ?>" /></td>
</tr>
<tr>
<td> </td>
<td><span class="errors"><?php echo $cityErr; ?></span></td>
</tr>
<tr>
<td><label><b>State</b><span style="color: red"> *</span></label></td>
<td><input type="text" name="state" value="<?php echo htmlentities($state); ?>" /> <br /></td>
</tr>
<tr>
<td> </td>
<td><span class="errors"><?php echo $stateErr; ?></span></td>
</tr>
<tr>
<td><label><b>Postal/Zip Code</b><span style="color: red"> *</span> </label></td>
<td><input type="text" name="zip" value="<?php echo htmlentities($zip); ?>" /> <br /></td>
</tr>
<tr>
<td> </td>
<td><span class="errors"><?php echo $zipErr; ?></span></td>
</tr>
</table></div>
</fieldset>
<fieldset>
<legend>Contact Info</legend>
<div style="padding-left:100px;">
<table width="590" border="0" cellpadding="10" cellspacing="5">
<tr>
<td><label><b>E-mail</b><span style="color: red"> *</span></label></td>
<td><input type="text" name="email" value="<?php echo htmlentities($email); ?>" /></td>
</tr>
<tr>
<td> </td>
<td><span class="errors"><?php echo $emailErr; ?></span></td>
</tr>
<tr>
<td><label><b>Phone</b><span style="color: red"> *</span></label></td>
<td><input type="text" name="phone" value="<?php echo htmlentities($phone); ?>" /></td>
</tr>
<tr>
<td> </td>
<td><span class="errors"><?php echo $phoneErr; ?></span></td>
</tr>
<tr>
<td width="195"><label><b>Fax</b></label></td>
<td width="395"><input type="text" name="fax" value="<?php echo htmlentities($fax); ?>" />
</td>
</tr>
</table></div>
</fieldset>
<fieldset>
<legend>Additional Notes</legend>
<div style="padding-left:100px;">
<table width="590" border="0" cellpadding="10">
<tr valign="top">
<td width="195"><label><b>Your Comment:</b></label></td>
<td width="395"><textarea name="comment" rows="10" cols="50" style="width: 300px;"/>
<?php echo htmlentities($comment); ?></textarea><br />
<span class="errors"><?php echo $commentErr ?></span><br /></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td>
</td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="submit" name="submit" class="button" /></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
</div>
</form>
Have check phpinfo() on both Yahoo and GoDaddy servers? I'll expect your Yahoo server runs with PHP 4.x while your GoDaddy server runs with PHP 5.x.

simple upload of image in database for sign up user

using php and pdo i was able to make a sign up page but with out saving image
$firstname = trim($_POST['fn']); //at a minimus clear whitespace.
$lastname = trim($_POST['ln']);
$username = trim($_POST['un']);
$password = trim($_POST['pw']);
$confirmpassword= trim($_POST['cp']);
$stmt = $dbh->prepare("INSERT INTO registration (fname,lname,username,password) VALUES (?,?,?,?)");
$stmt->bindValue(1,$firstname,PDO::PARAM_STR);
$stmt->bindValue(2,$lastname,PDO::PARAM_STR);
$stmt->bindValue(3,$username,PDO::PARAM_STR);
$stmt->bindValue(4,$password,PDO::PARAM_STR);
if($stmt->execute()){
echo "YOUR REGISTRATION IS COMPLETED...";
}
i found this tutorial but its too complicated for me to understand and it was not explained clearly i am looking for ideas or tutorial that is easy to understand on how to upload image..any idea is appreaciated
form
<form method="POST" action="crud.php">
<tr>
<td>
</td>
<td>
<input type="file" name="image" />
</td>
</tr>
<tr>
<td>First Name</td>
<td>
<input type="text" name="fn">
</td>
</tr>
<tr>
<td>Last Name</td>
<td>
<input type="text" name="ln">
</td>
</tr>
<tr>
<td>User Name</td>
<td>
<input type="text" name="un">
</td>
</tr>
<tr>
<td>Password</td>
<td>
<input type="password" name="pw">
</td>
</tr>
<tr>
<td>Confirm Password</td>
<td>
<input type="password" name="cp">
</td>
</tr>
<tr>
<td>
<input id="button" type="submit" value="Back" name="back"/>
</td>
<td>
<input id="button" type="submit" value="SignUp" name="signup"/>
</td>
</tr>
<tr><td><div style="font-size:11px; color:#cc0000; margin-top:10px"><?php echo $error; ?></div></td></tr>
</form>
Here is a simple example of how to achieve that:
if(is_uploaded_file($_FILES['image']['tmp_name'])){
$folder = "upload/";
$file = basename( $_FILES['image']['name']);
$full_path = $folder.$file;
if(move_uploaded_file($_FILES['image']['tmp_name'], $full_path)) {
echo "succesful upload, we have an image!";
$firstname = trim($_POST['fn']);
$lastname = trim($_POST['ln']);
$username = trim($_POST['un']);
$password = trim($_POST['pw']);
$confirmpassword= trim($_POST['cp']);
$stmt = $dbh->prepare("INSERT INTO registration (fname,lname,username,password, img_url) VALUES (?,?,?,?,?)");
$stmt->bindValue(1,$firstname,PDO::PARAM_STR);
$stmt->bindValue(2,$lastname,PDO::PARAM_STR);
$stmt->bindValue(3,$username,PDO::PARAM_STR);
$stmt->bindValue(4,$password,PDO::PARAM_STR);
$stmt->bindValue(5,$full_path,PDO::PARAM_STR);
if($stmt->execute()){
echo "YOUR REGISTRATION IS COMPLETED...";
}else{
echo 'YOUR REGISTRATION COULD NOT BE COMPLETED...';
}
} else {
echo "upload received! but process failed";
}
}else{
echo "upload failure ! Nothing was uploaded";
}
In the query I have included a field called img_url.
The PDO insert query is executed once the image is uploaded successfully.
You could just use a simple PHP upload() function. Here's an example http://www.w3schools.com/php/php_file_upload.asp

Categories