Pass value when form submitted to If function on another file - php

I have two different files.
Checkoutstep4.php
Checkoutstep5.php
When the first form is submitted, I want to take the value of 'country' which has been submitted and use it in an IF function:
This is what I have so far using session variable...
however I get an error saying undefined index and I am not sure why.
checkoutDeliveryInfo (file that runs when the delivery details form is submitted).
<?php
session_start();
require_once 'DatabaseConnection.php';
$_SESSION['customerid'];
if (isset($_POST['submit'])) {
$stmt = $pdo->prepare("INSERT INTO DeliveryDetails (customerid,firstname,lastname, addressline1, addressline2, city, county, country, postalcode)
VALUES ({$_SESSION['customerid']}, :firstname, :lastname, :addressline1, :addressline2, :city, :county, :country, :postalcode)");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':addressline1', $addressline1);
$stmt->bindParam(':addressline2', $addressline2);
$stmt->bindParam(':city', $city);
$stmt->bindParam(':county', $county);
$stmt->bindParam(':country', $country);
$stmt->bindParam(':postalcode', $postalcode);
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$addressline1 = $_POST['addressline1'];
$addressline2 = $_POST['addressline2'];
$city = $_POST['city'];
$county = $_POST['county'];
$country = $_POST['country'];
$postalcode = $_POST['postalcode'];
$stmt->execute();
$_SESSION['country'] = $country;
header('location:../View/php_shopping_cart/CheckoutStep5.php');
}
IF function in the Checkoutstep5.php file where the session variable is being used:
<?php
include '../../Model/ShoppingCart.php';
$shoppingCart = new ShoppingCart;
// redirect to home if cart is empty
if ($shoppingCart->total_items() <= 0) {
header("Location: ../index.php");
}
?>
<div class="shippingcost"><strong>Shipping Cost <?php
if ($_SESSION['country'] != 'GIB') {
$shippingcost = '10.00';
} else {
$shippingcost = 'FREE';
}
echo $shippingcost;
?></strong>
</div>
Any help is appreciated.
Update: Error Message:
Notice: Undefined index: country in /home/k1509759/www/barbarycoast/View/php_shopping_cart/CheckoutStep5.php on line 246

I've managed to do it by extracting all variables from the session and then using the individual one i wanted.
extract($_SESSION);
if ($country == 'GIB') {
$shippingcost = 'FREE';
} else if ($country == 'GBR') {
$shippingcost = '£10.00';
} else if ($country == 'ESP') {
$shippingcost = '£10.00';
}

Related

how to forbid to send data to sql

I'm using strlen to check my inputs values. I want to forbid to the users to send data to my database if the strlen is too long. I didn't find any way to forbid it, so anyone can send as long values as he wants right now. Here's my code:
if (isset($_POST['sub'])) {
$name = $_POST['name'];
$phone = $_POST['phone'];
$phone2 = $_POST['phone2'];
$email = $_POST['email'];
$zipcode = $_POST['zipcode'];
$address = $_POST['address'];
$job = $_POST['job'];
$description = $_POST['description'];
$userid = $_SESSION['id'];
$stmt = $mysqli -> prepare('UPDATE cards SET name=?, phone=?, phone2=?, email=?, zipcode=?, address=?, job=?, description=?, visibility=?, confirmed=? WHERE id = ?');
if (
$stmt &&
$stmt->bind_param('ssssisssiii', $name, $phone, $phone2, $email, $zipcode, $address, $job, $description, $visibility, $confirmed, $id) &&
$stmt -> execute()
) {
echo "Sikeres módosítás!";
} else {
echo $mysqli -> error;
}
}
$getstmt = $mysqli->prepare("SELECT * FROM cards WHERE id= ?");
if ($getstmt and
$getstmt->bind_param('i', $id) and
$getstmt->execute() and
$result = $getstmt->get_result() and
$row = $result->fetch_assoc()
) {
if($row['userid'] == $_SESSION['id']){
$name = $row['name'];
$phone = $row['phone'];
$phone2 = $row['phone2'];
$email = $row['email'];
$zipcode = $row['zipcode'];
$address = $row['address'];
$job = $row['job'];
$description = $row['description'];
}else{
header("Location: index.php");
}
I check the length of inputs here:
if(strlen($name) > 30)
{
echo "test";
exit();
}
if(strlen($job) > 50)
{
echo "test";
exit();
}
if(strlen($email) > 50)
{
echo "test";
exit();
}
//more of these strlen checks
//and html code under that
How can I modify the echo parts to forbid to send the datas?
Well, if you really have to do it your way, you can throw an exception.
However, more common way is to bind your data to model, validate the model checking any business constraints (using the validator) and then acting accordingly. There is plenty of web frameworks providing such an abstraction in any programming language, for PHP see Laravel for inspiration.

preventing duplicate row data entries

I had created a database which named student with ID, name, mat_number, specialty, age, and gender, in a PHP application.
I do not want the name or mat_number be taken in more than once.
I have done the connection to my database in a different page and called it in the add student page.
This following codes is for a faculty database collection
<?php
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$matNo = $_POST['mat_number'];
$age = $_POST['age'];
$specialty = $_POST['specialty'];
$gender = $_POST['gender'];
if(!empty($name) && !empty($matNo) && !empty($age) &&
!empty($specialty) && !empty($gender))
{
$sql = "INSERT INTO `student`(`name`, `UB_number`, `age`,
`sex`, `specialty`)
VALUES ('$name', '$matNo', '$age', '$gender', '$specialty')";
$conn->query($sql);
header("Location: index.php");
}
else{
echo "Error: Complete all records";
}
}
?>
I want to get an error message demanding for a change if the 2 fields already exist in the database.
first name to check in database if already exist the record.
if no record run sql insert command.
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$matNo = $_POST['mat_number'];
$age = $_POST['age'];
$specialty = $_POST['specialty'];
$gender = $_POST['gender'];
$sql = "SELECT * FROM `student` WHERE name = "'.$name.'" and UB_number = '".$matNo."'";
$conn->query($sql);
$cnt = $conn->rowCount();
if($cnt == 0){
$sql = "INSERT INTO `student`
(`name`, `UB_number`, `age`,`sex`, `specialty`)
VALUES
('$name', '$matNo', '$age', '$gender', '$specialty')";
$conn->query($sql);
header("Location: index.php");
}else{
echo "Error: Complete all records";
}
}
If you would like to insert a new record to DB only if one doesn't exist which has the same name or mat_number then you first need to execute SELECT statement to see if it exists.
Using MySQLi:
<?php
include 'mysqli.php';
$conn = $mysqli;
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$matNo = $_POST['mat_number'];
$age = $_POST['age'];
$specialty = $_POST['specialty'];
$gender = $_POST['gender'];
if ($name && $matNo && $age && $specialty && !$gender) {
$stmt = $conn->prepare('SELECT 1 FROM student WHERE name=? OR UB_number=?');
$stmt->bind_param('ss', $name, $matNo);
$stmt->execute();
$stmt->bind_result($exists);
$stmt->fetch();
if (!$exists) {
$stmt = $conn->prepare('INSERT INTO `student`(`name`, `UB_number`, `age`, `sex`, `specialty`) VALUES(?,?,?,?,?)');
$stmt->bind_param('sssss', $name, $matNo, $age, $gender, $specialty);
$stmt->execute();
exit(header("Location: index.php"));
} else {
echo 'A record with this name or material number already exists!';
}
} else {
echo "Error: Complete all records";
}
}
Using PDO:
<?php
include 'lib.php';
$conn = $pdo;
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$matNo = $_POST['mat_number'];
$age = $_POST['age'];
$specialty = $_POST['specialty'];
$gender = $_POST['gender'];
if ($name && $matNo && $age && $specialty && !$gender) {
$stmt = $conn->prepare('SELECT 1 FROM student WHERE name=? OR UB_number=?');
$stmt->execute([$name, $matNo]);
$exists = $stmt->fetchColumn();
if (!$exists) {
$stmt = $conn->prepare('INSERT INTO `student`(`name`, `UB_number`, `age`, `sex`, `specialty`) VALUES(?,?,?,?,?)')
->execute([$name, $matNo, $age, $gender, $specialty]);
exit(header("Location: index.php"));
} else {
echo 'A record with this name or material number already exists!';
}
} else {
echo "Error: Complete all records";
}
}
hope this may be helpfull to you. In here I asume that you are not using any framework. But if you use a framework there are plenty of easy methods to do this.In here I have checked only name field. You should update code as you wants. Also it it better if you could validate your inputs before check. Like trim(). Thanks
<?php
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$matNo = $_POST['mat_number'];
$age = $_POST['age'];
$specialty = $_POST['specialty'];
$gender = $_POST['gender'];
//after user click the submit button
$sql_Select_Stundets = "SELECT * FROM student WHERE name = '$name' ";
// query the sql with db connection
$result_sql_Select_Stundets = mysqli_query($conn,$sql_Select_Stundets);
//Now check the row count to verify the output if there is any match
$rowcount=mysqli_num_rows($result);
//Now write insert inside if condition
if( $rowcount >0 ) {
if(!empty($name) && !empty($matNo) && !empty($age) &&
!empty($specialty) && !empty($gender)) {
$sql = "INSERT INTO `student`(`name`, `UB_number`, `age`,
`sex`, `specialty`)
VALUES ('$name', '$matNo', '$age', '$gender', '$specialty')";
$conn->query($sql);
bheader("Location: index.php");
}else{
echo "Error: Complete all records";
}
}else{
echo "<script>
alert('sorry this name is already available');
</script>";
}
}
?>

Prepared Statement (PHP5, SQLite3) exceeds 30 seconds execution Time

I am trying to avoid duplicate entries of automatically generated random numbers in an SQLite3 DB through PHP. For that i have prepared Statements in a do while loop. The random numbers are generated and then a query checks if the number already exists. If Yes, generate again, if no, carry on.
Atleast, this is what i am trying to achieve...
But for some reason unknown to me, the PHP log keeps showing me that the maximum execution Time of 30 secs has been exeeded at the query line. Firstly, i tried doing the whole thing without prepared statements and it didn't work. I thought that was because i had php variables in the query. So i switched to Prepared Statements without success.
I checked all the POST Variables via Firebug and everything seems to be fine there. It is the Prepared Statement which is giving me diarrhea!!
Can you guys please help me ?
The PHP Code:
<?php
$adate = $_POST['adate'];
$ddate = $_POST['ddate'];
$ad = $_POST['ad'];
$dd = $_POST['dd'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$address = $_POST['address'];
$postal = $_POST['postal'];
$city = $_POST['city'];
$country = $_POST['country'];
$tel = $_POST['tel'];
$message = $_POST['message'];
$price = $_POST['price'];
$bkfst = $_POST['bkfst'];
$rnum = $_POST['rnum'];
$rtype = $_POST['rtype'];
$robotest = $_POST['blnk'];
$bid = 0;
$cid = 0;
$adate = $adate . " 20:00:00";
$ddate = $ddate . " 13:00:00";
if ($robotest)
$error = "You are a gutless robot.";
else {
function bid()
{
$bid = mt_rand(111111, 999999);
if (($bid % 10) == 0) {
$bid = $bid + 123;
}
}
function cid()
{
$cid = mt_rand(11111, 99999);
if (($cid % 10) == 0) {
$cid = $cid + 123;
}
}
include 'connect.php';
do {
cid();
--> $sth = $db->prepare("SELECT COUNT (CustomerID) from Customer WHERE CustomerID = ?");
$sth->execute(array($cid));
} while ($sth->fetchColumn() > 0);
$sth = $db->prepare("INSERT INTO Customer (CustomerID, FirstName, LastName, Address, PostalCode, City, Country, EMail, Phone) VALUES ('$cid', '$fname', '$lname', '$address', '$postal', '$city', '$country', '$email', '$tel')");
$sth->execute();
do {
bid();
--> $sth = $db->prepare("SELECT COUNT (BookingID) from Booking WHERE BookingID = ?");
$sth->execute(array($bid));
} while ($sth->fetchColumn() > 0);
$sth = $db->prepare("INSERT INTO Booking (BookingID, Arrival, Checkout, RoomNumber, CustomerID, Breakfast, Comment, Paid) VALUES ('$bid', '$adate', '$ddate', '$rnum', '$cid', '$bkfst', '$message', 'N')");
$sth->execute();
$subject = "Your Booking";
$message = "Hi $fname,\n\nA $rtype from $ad to $dd has been booked for you.\n\nYour Booking Code is $bid.\n\nRegards.";
mail($email, $subject, $message);
echo 'The Booking completed successfully! Check your E-Mail for further Information.';
}
?>
Lines beginning with --> in the code are the problematic lines.
And Yes, I am a Newbie who is learning by doing and also learning by annoying people in the Stack Overflow Forums :)
Thanks.
EDIT:
This is how my Code looks now. All the errors are gone but php is not inserting anything to the DB. The Email is sent correctly with the generated number.
<?php
$adate = $_POST['adate'];
$ddate = $_POST['ddate'];
$ad = $_POST['ad'];
$dd = $_POST['dd'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$address = $_POST['address'];
$postal = $_POST['postal'];
$city = $_POST['city'];
$country = $_POST['country'];
$tel = $_POST['tel'];
$message = $_POST['message'];
$price = $_POST['price'];
$bkfst = $_POST['bkfst'];
$rnum = $_POST['rnum'];
$rtype = $_POST['rtype'];
$robotest = $_POST['blnk'];
$adate = $adate . " 20:00:00";
$ddate = $ddate . " 13:00:00";
$cid;
$bid;
if ($robotest)
$error = "You are a gutless robot.";
else {
function bid()
{
global $bid;
$bid = mt_rand(111111, 999999);
if (($bid % 10) == 0) {
$bid = $bid + 123;
}
}
function cid()
{
global $cid;
$cid = mt_rand(11111, 99999);
if (($cid % 10) == 0) {
$cid = $cid + 123;
}
}
include 'connect.php';
do {
global $cid;
cid();
$sth = $db->prepare('SELECT COUNT (CustomerID) from Customer WHERE CustomerID = ?');
$sth->execute(array($cid));
} while ($sth->fetchColumn() > 0);
global $cid;
$sth = $db->prepare('INSERT INTO Customer (CustomerID, FirstName, LastName, Address, PostalCode, City, Country, EMail, Phone) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)');
$sth->execute(array($cid, $fname, $lname, $address, $postal, $city, $country, $email, $tel));
do {
global $bid;
bid();
$sth = $db->prepare('SELECT COUNT (BookingID) from Booking WHERE BookingID = ?');
} while ($sth->fetchColumn() > 0);
global $bid;
global $cid;
$sth = $db->prepare('INSERT INTO Booking (BookingID, Arrival, Checkout, RoomNumber, CustomerID, Breakfast, Comment, Paid) VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
$sth->execute(array($bid, $adate, $ddate, $rnum, $cid, $bkfst, $message, 'N'));
$subject = "Your Booking";
global $bid;
$message = "Hi $fname,\n\nA $rtype from $ad to $dd has been booked for you.\n\nYour Booking Code is $bid.\n\nRegards.";
mail($email, $subject, $message);
echo 'The Booking completed successfully! Check your E-Mail for further Information.';
}
?>
hhmmm...
This is an infinite loop:
do {
cid();
$sth = $db->prepare("SELECT COUNT (CustomerID) from Customer WHERE CustomerID = ?");
$sth->execute(array($cid));
} while ($sth->fetchColumn() > 0);
Since your cid/bid() functions are badly constructed, the $cid you're using inside this do() loop will NEVER change from the $cid = 0 you did at the top of the script.
So the loop starts, you prepare/execute the query with CustomerID = 0, get back one of row of data with the count() results, which you fetch.
Then the loop rolls around again, and you RE-EXECUTE the query, with the exact same $cid = 0 value, so you continue reset the loop termination condition - you never end up with a value, because you keep query with the same bad/invalid cid=0.
It's pretty much the same like the good old BASIC program: 10 GOTO 10.
It's working now:
<?php
$adate = $_POST['adate'];
$ddate = $_POST['ddate'];
$ad = $_POST['ad'];
$dd = $_POST['dd'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$address = $_POST['address'];
$postal = $_POST['postal'];
$city = $_POST['city'];
$country = $_POST['country'];
$tel = $_POST['tel'];
$message = $_POST['message'];
$price = $_POST['price'];
$bkfst = $_POST['bkfst'];
$rnum = $_POST['rnum'];
$rtype = $_POST['rtype'];
$robotest = $_POST['blnk'];
$adate = $adate . " 20:00:00";
$ddate = $ddate . " 13:00:00";
$cid;
$bid;
if ($robotest)
$error = "You are a gutless robot.";
else {
function bid()
{
global $bid;
$bid = mt_rand(111111, 999999);
if (($bid % 10) == 0) {
$bid = $bid + 123;
}
}
function cid()
{
global $cid;
$cid = mt_rand(11111, 99999);
if (($cid % 10) == 0) {
$cid = $cid + 123;
}
}
include 'connect.php';
$sth = $db->prepare('SELECT COUNT (EMail) from Customer WHERE EMail = ?');
$sth->execute(array($email));
if($sth->fetchColumn() < 1){
do {
global $cid;
cid();
$sth = $db->prepare('SELECT COUNT (CustomerID) from Customer WHERE CustomerID = ?');
$sth->execute(array($cid));
} while ($sth->fetchColumn() > 0);
global $cid;
$sth = $db->prepare('INSERT INTO Customer (CustomerID, FirstName, LastName, Address, PostalCode, City, Country, EMail, Phone) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)');
$sth->execute(array($cid, $fname, $lname, $address, $postal, $city, $country, $email, $tel));
}else{
global $cid;
$sth = $db->prepare('SELECT CustomerID from Customer WHERE EMail = ?');
$sth->execute(array($email));
$id = $sth->fetch(PDO::FETCH_ASSOC);
$cid = $id['CustomerID'];
}
do {
global $bid;
bid();
$sth = $db->prepare('SELECT COUNT (BookingID) from Booking WHERE BookingID = ?');
} while ($sth->fetchColumn() > 0);
global $bid;
global $cid;
$booktime = date('Y-m-d H:i:s');
$sth = $db->prepare('INSERT INTO Booking (BookingID, Arrival, Checkout, RoomNumber, CustomerID, Breakfast, Comment, Paid, BookTime, Invoice) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
$sth->execute(array($bid, $adate, $ddate, $rnum, $cid, $bkfst, $message, 'N', $booktime, NULL));
$subject = "Your Booking";
global $bid;
$message = "Hi $fname,\n\nA $rtype from $ad to $dd has been booked for you.\n\nYour Booking Code is $bid.\n\nMention this Code if you need to get in touch with us.\n\nRegards.";
mail($email, $subject, $message);
echo 'The Booking completed successfully! Check your E-Mail for further Information.';
}
?>
No Clue, if this is the best way to do it but it is working perfectly.
Thanks for all the hints.

Problems with sessions and mysql

i'm creating a site for a client and i get an error message saying "undefined index". I'm trying to upload data to a database from 3 multi form pages and they are handled by cv.php.
The form details are stored on page 2
<?php
session_start();
if(isset($_SESSION['FirstName'])){
$_SESSION['FirstName'] = $_POST['FirstName'];}
if(isset($_SESSION['LastName'])){
$_SESSION['LastName'] = $_POST['LastName'];}
if(isset($_SESSION['dob'])){
$_SESSION['dob'] = $_POST['dob'];}
if(isset($_SESSION['Age'])){
$_SESSION['Age'] = $_POST['Age'];}
if(isset($_SESSION['AddressLine1'])){
$_SESSION['AddressLine1'] = $_POST['AddressLine1'];}
if(isset($_SESSION['AddressLine2'])){
$_SESSION['AddressLine2'] = $_POST['AddressLine2'];}
if(isset($_SESSION['City'])){
$_SESSION['City'] = $_POST['City'];}
if(isset($_SESSION['County'])){
$_SESSION['County'] = $_POST['County'];}
if(isset($_SESSION['PostCode'])){
$_SESSION['PostCode'] = $_POST['PostCode'];}
if(isset($_SESSION['Country'])){
$_SESSION['Country'] = $_POST['Country'];}
if(isset($_SESSION['Telephone'])){
$_SESSION['Telephone'] = $_POST['Telephone'];}
if(isset($_SESSION['Mobile'])){
$_SESSION['Mobile'] = $_POST['Mobile'];}
if(isset($_SESSION['Email'])){
$_SESSION['Email'] = $_POST['Email'];}
?>
Page 3
<?php
session_start();
if(isset($_SESSION['Skills'])) {
$_SESSION['Skills'] = $_POST['Skills'];}
if(isset($_SESSION['ReasonApp'])){
$_SESSION['ReasonApp'] = $_POST['ReasonApp'];}
if(isset($_SESSION['WorkName'])){
$_SESSION['WorkName'] = $_POST['WorkName'];}
if(isset($_SESSION['WorkDesc'])){
$_SESSION['WorkDesc'] = $_POST['WorkDesc'];}
if(isset($_SESSION['W_AddressLine1'])){
$_SESSION['W_AddressLine1'] = $_POST['W_AddressLine1'];}
if(isset($_SESSION['W_AddressLine2'])){
$_SESSION['W_AddressLine2'] = $_POST['W_AddressLine2'];}
if(isset($_SESSION['W_City'])){
$_SESSION['W_City'] = $_POST['W_City'];}
if(isset($_SESSION['W_Telephone'])){
$_SESSION['W_Telephone'] = $_POST['W_Telephone'];}
?>
And my CV.php
<?
session_start();
ini_set('display_errors',1);
error_reporting(E_ALL);
//include connection profile
require_once("Sql/con.php");
include("config.php");
//declare variables with sessions
$FirstName = $_SESSION['FirstName'];
$LastName = $_SESSION['LastName'];
$dob = $_SESSION['dob'];
$Age = $_SESSION['Age'];
$AddressLine1 = $_SESSION['AddressLine1'];
$AddressLine2 = $_SESSION['AddressLine2'];
$PostCode = $_SESSION['PostCode'];
$City = $_SESSION['City'];
$County = $_SESSION['County'];
$Country = $_SESSION['Country'];
$Mobile = $_SESSION['Mobile'];
$Telephone = $_SESSION['Telephone'];
$Email = $_SESSION['Email'];
$Skills = $_SESSION['Skills'];
$ReasonApp = $_SESSION['ReasonApp'];
$SchoolName = $_SESSION['SchoolName'];
$Course = $_SESSION['Course'];
$Certificate = $_SESSION['Certificate'];
$DateFrom = $_SESSION['DateFrom'];
$DateTo = $_SESSION['DateTo'];
$CollName = $_SESSION['CollName'];
$CollQualification = $_SESSION['CollQualification'];
$CollYear = $_SESSION['CollYear'];
$WorkName = $_SESSION['WorkName'];
$WorkDesc = $_SESSION['WorkDesc'];
$W_AddressLine1 = $_SESSION['W_AddressLine1'];
$W_AddressLine2 = $_SESSION['W_AddressLine2'];
$W_PostCode = $_SESSION['PostCode'];
$W_City = $_SESSION['City'];
$W_Telephone = $_SESSION['Telephone'];
//database connection
$dblink = mysqli_connect($mysql_host,$mysql_user,$mysql_pw,$mysql_db) OR DIE ("Unable to
connect to database! Please try again later.");
//inserting information into tables
$order = "INSERT INTO CV_personal
(FirstName,LastName,dob,Age,AddressLine1,AddressLine2,PostCode,City,County,Country,Mobile,Telephone,Email,Skills,ReasonApp,SchoolName,Course,Certificate,DateFrom,DateTo,CollName,CollQualification,CollYear,WorkName,WorkDesc,W_AddressLine1,W_AddressLine2,W_City,W_Telephone)
VALUES
('$FirstName',
'$LastName',
'$dob',
'$Age',
'$AddressLine1',
'$AddressLine2',
'$PostCode',
'$City',
'$County',
'$Country',
'$Mobile',
'$Telephone',
'$Email',
'$Skills',
'$ReasonApp',
'$SchoolName',
'$Course',
'$Certificate',
'$DateFrom',
'$DateTo',
'$CollName',
'$$CollQualification',
'$ColYear',
'$WorkName',
'$WorkDesc',
'$W_AddressLine1',
'$W_AddressLine2',
'$W_PostCode',
'$W_City',
'$W_Telephone',)";
//declare in the order variable
$result = mysqli_query($dblink, $order); //order executes
?>
On my final page do i need to had my form into the session because i declared a variable for them on Cv.php ?
Thank you
In your first two blocks of code, you should be checking if the $_POST[...] is set, not the $_SESSION[...] because that it what you are assigning, so it won't cause an error.
On CV.php you should check whether the $_SESSION[...] exists before assigning it to a variable or else it WILL cause an error.
Tip:
If you are going to name your variables exactly the name of all your keys in the $_SESSION array. You can just substitute you many lines with this single line:
extract($_SESSION);
More on extract: http://www.php.net/extract

SQL Real Escape String not showing in database

I have a registration form on my site and I figured I should protect from SQL injection. I can't have that table being dropped maliciously.
Using POST, I collect the input from the form, check it, and then add it to the database. My code is below. I've been testing the form, and though the form is submitted successfully, the table is filled with an empty row...not the data from the form.
What's going on here?
<?php
$type = $_POST['type']; // a dropdown
$color = $_POST['color']; // a dropdown
$name = mysql_real_escape_string($_POST['name']);
$address = mysql_real_escape_string($_POST['address']);
$city = mysql_real_escape_string($_POST['city']);
$state = $_POST['state']; // a dropdown
$zip = mysql_real_escape_string($_POST['zip']);
$phone = mysql_real_escape_string($_POST['phone']);
$email = mysql_real_escape_string($_POST['email']);
$where = mysql_real_escape_string($_POST['where']);
$price = mysql_real_escape_string($_POST['price']);
$use = mysql_real_escape_string($_POST['use']);
include 'php/Connect.php';
$ct = new Connect();
$con = $ct->connect();
if(check($email, $con)) {
if(register($type, $color, $name, $address, $city, $state, $zip, $phone, $email, $where, $price, $use, $con)) {
echo '<h1>Success!</h1><p>Thanks for registering your product. A confirmation email has been sent to '.$email.'.</p>';
}
else {
echo '<h1>Error!</h1><p>There were errors processing your registration. Please try again.</p>';
}
}
else {
echo '<h1>Error!</h1><p>This product has already been registered.</p>';
}
function check($email, $con) {
$query = "SELECT * FROM registrations WHERE email='$email'";
$res = mysql_query($query, $con);
if ($con) {
$row = mysql_fetch_assoc($res);
if($row) {
return false; // product registration exists
}
else {
return true; // product registration does not exist
}
}
else {
return false;
}
}
function register($type, $color, $name, $address, $city, $state, $zip, $phone, $email, $where, $price, $use, $con) {
$query = "INSERT INTO registrations VALUES ('$type', '$color', '$name', '$address', '$city', '$state', '$zip', '$phone', '$email', '$where', '$price', '$use')";
$res = mysql_query($query, $con);
if (!$con) {
return false;
}
else {
mysql_close($con);
return true;
}
}
?>
Connect to database before using mysql_real_escape_string
However it is better to use the newer version
$connect=mysqli_connect(.......);
mysqli_real_escape_string($connect,$string);
Fixed it with PeeHaa's help. Here's the corrected code:
<?php
include 'php/Connect.php';
$ct = new Connect();
$db = $ct->connect();
$type = $_POST['type'];
$color = $_POST['color'];
$name = $_POST['name'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$where = $_POST['where'];
$price = $_POST['price'];
$use = $_POST['use'];
if(check($email, $db)) {
if(register($type, $color, $name, $address, $city, $state, $zip, $phone, $email, $where, $price, $use, $db)) {
echo '<h1>Success!</h1><p>Thanks for registering your product. A confirmation email has been sent to '.$email.'.</p>';
}
else {
echo '<h1>Error!</h1><p>There were errors processing your registration. Please try again.</p>';
}
}
else {
echo '<h1>Error!</h1><p>This product has already been registered.</p>';
}
function check($email, $db) {
$stmt = $db->prepare("SELECT * FROM registrations WHERE email=?");
$stmt->execute(array($email));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ($db) {
if($rows) {
return false; // product registration exists
}
else {
return true; // product registration does not exist
}
}
else {
return false;
}
}
function register($type, $color, $name, $address, $city, $state, $zip, $phone, $email, $where, $price, $use, $db) {
$stmt = $db->prepare("INSERT INTO registrations VALUES(?,?,?,?,?,?,?,?,?,?,?,?)");
$stmt->execute(array($type, $color, $name, $address, $city, $state, $zip, $phone, $email, $where, $price, $use));
if (!$db) {
return false;
}
else {
mysql_close($db);
return true;
}
}
?>

Categories