I have attempted to use $_SESSION in a form input I am creating however I cannot get it to work and do not know what I am doing wrong, it works with my previous part of the form when carrying data over to the next page - however the code does not seem to work for the main part of the form.
<?php
//This includes the variables, adjusted within the 'config.php file' and the functions from the 'functions.php' - the config variables are adjusted prior to anything else.
require('configs/config.php');
require('configs/functions.php');
//Check to see if the form has been submited, if it has we continue with the script.
if(isset($_POST['confirmation']) && isset($_POST['name']) && isset($_POST['email']) && isset($_POST['address1']) && isset($_POST['city']) && isset($_POST['postcode']) and $_POST['confirmation']=='true')
{
//Slashes are removed, depending on whether magic_quotes_gpc is on.
if(get_magic_quotes_gpc())
{
$_POST['name'] = stripslashes($_POST['name']);
$_POST['email'] = stripslashes($_POST['email']);
$_POST['address1'] = stripslashes($_POST['address1']);
$_POST['address2'] = stripslashes($_POST['address2']);
$_POST['city'] = stripslashes($_POST['city']);
$_POST['postcode'] = stripslashes($_POST['postcode']);
$_POST['phonenum'] = stripslashes($_POST['phonenum']);
}
//Create the future reference number of the repair.
$maxid = mysql_fetch_array(mysql_query('select max(id) as id from repairs'));
$id = intval($maxid['id'])+1;
//Create the future reference number of the repair.
$maxref = mysql_fetch_array(mysql_query('select max(reference) as reference from repairs'));
$reference = intval($maxref['reference'])+8;
//Here the session variables are converted back into standard variables.
$model = $_SESSION['model'];
$problem = $_SESSION['problem'];
$info = $_SESSION['info'];
$device = $_SESSION['device'];
$price = $_SESSION['price'];
$image = $_SESSION['image'];
//Here the variables are protected using mysql_real_escape_string.
$name = mysql_real_escape_string(substr($_POST['name'],0,150));
$email = mysql_real_escape_string(substr($_POST['email'],0,255));
$address1 = mysql_real_escape_string(substr($_POST['address1'],0,255));
$address2 = mysql_real_escape_string(substr($_POST['address2'],0,255));
$city = mysql_real_escape_string(substr($_POST['city'],0,100));
$postcode = mysql_real_escape_string(substr($_POST['postcode'],0,9));
$phonenum = mysql_real_escape_string(substr($_POST['phonenum'],0,11));
$date = date("r");
//Here the variables are protected using trim.
$name = trim($name);
$email = trim($email);
$address1 = trim($address1);
$address2 = trim($address2);
$city = trim($city);
$postcode = trim($postcode);
$phonenum = trim($phonenum);
//Here the variables are protected using htmlspecialchars.
$name = htmlspecialchars($name);
$email = htmlspecialchars($email);
$address1 = htmlspecialchars($address1);
$address2 = htmlspecialchars($address2);
$city = htmlspecialchars($city);
$postcode = htmlspecialchars($postcode);
$phonenum = htmlspecialchars($phonenum);
//Here the variables are protected using strip_tags.
$name = strip_tags($name);
$email = strip_tags($email);
$address1 = strip_tags($address1);
$address2 = strip_tags($address2);
$city = strip_tags($city);
$postcode = strip_tags($postcode);
$phonenum = strip_tags($phonenum);
//The details about the repair are entered into the database
$query = mysql_query("insert into repairs (id, model, problem, info, name, email, address1, address2, city, postcode, phonenum, price, date, reference) values ('$id', '$model', '$problem', '$info', '$name', '$email', '$address1', '$address2', '$city', '$postcode', '$phonenum', '$price', '$date', '$reference')") or die(header('Location: 404.php'));
?>
Some HTML is here.
<?
}
else {
header('Location: 404.php');
}
?>
Can anyone help me to get this to work?
You have to initiate your session in the beginning of your script with session_start()
set your error logging to the most verbose level. If your Paste is exact, you have some spaces in the beginning which cause, that you cant send headers anymore and so you cant initiate the session.
Related
I have the below code that should add user input into the db, I can't understand why its not adding to db, the email field in the table is a foreign key that references to another table, and I'm using session to store email in the $email and save it to db when user saves data, also I'm accepting date and time from user input which is exactly as per the db format but it still doesn't save, I have tried entering static data as well, not working either. Am I missing something ?
$server = "localhost";
$user = "root";
$pwd = "";
$sql_db = "cabcustomers";
$email = $_SESSION['sesName'];
$conn = #mysqli_connect($server,$user,$pwd,$sql_db);
if (isset ($_POST["name"]) && isset ($_POST["contact"]) && isset ($_POST["unitno"]) && isset ($_POST["streetno"]) && isset ($_POST["streetname"]) && isset ($_POST["suburb"]) && isset ($_POST["destsuburb"]) && isset ($_POST["pickdt"]) && isset ($_POST["picktime"]))
{
$name = $_POST["name"];
$contact = $_POST["contact"];
$unitno = $_POST["unitno"];
$streetno = $_POST["streetno"];
$streetname = $_POST["streetname"];
$suburb = $_POST["suburb"];
$destsuburb = $_POST["destsuburb"];
$pickdt = $_POST["pickdt"];
$picktime = $_POST["picktime"];
if(empty($name) || empty($contact) || empty($unitno) || empty($streetno) || empty($streetname) || empty($suburb) || empty($destsuburb) || empty($pickdt) || empty($picktime))
{
echo "<p>ONE OR MORE OF FIELDS HAVE MISSING INFORMATION, KINDLY CHECK AND TRY AGAIN!</p>";
}
elseif (!is_numeric($contact))
{
echo "<p>CONTACT NUMBER MUST BE NUMERIC!</p>";
}
else
{
$idlen = 7;
$bookingid = uniqid (rand(), true);
$bookingid = "BK" . substr($bookingid, 0, $idlen);
$status = "unassigned";
$pickdt = $pickdt . " " . $picktime;
$query = "insert into bookings (bookingid, pname, contact, unitno, streetno, streetname, suburb, destsuburb, pickupdt, bookingdt, status, email) values ('$bookingid', '$name', '$contact', '$unitno', '$streetno', '$streetname', '$suburb', '$destsuburb','$pickdt', 'NOW()','$status', '$email');";
echo $email;
$result = mysqli_query($conn, $query);
echo $result;
echo "<p>INFORMATION SAVED</p>";
}
mysqli_close($conn);
}
Based on the comments after your initial question, I don't think the connection is the problem, the problem is most likely happening during the INSERT query. Have you tried running the query from phpMyAdmin to troubleshoot the syntax of the query outside of PHP?
It's working, but when I add the data in to my database, the data will be twice. I don't know if my syntax is wrong or my code is wrong.
Here's the structure:
//if submit is clicked
$checkin = $_POST['text_checkin'];
while ($row = mysqli_fetch_array($reservation)) {
if (isset($_POST['submitBtn'])) {
if ($row['reservefrom'] == $checkin) {
echo "Same Date";
return;
}
else
{
$lastname = $_POST['text_lastname'];
$firstname = $_POST['text_firstname'];
$address = $_POST['text_address'];
$tnumber = $_POST['text_tnumber'];
$cnumber = $_POST['text_cnumber'];
$email = $_POST['text_email'];
$checkin = $_POST['text_checkin'];
$checkout = $_POST['text_checkout'];
$room = $_POST['text_room'];
$tour = $_POST['text_tour'];
$guest = $_POST['text_guest'];
$query = "INSERT INTO reservation
(lastname, firstname, homeaddress,
telephonenumber, cellphonenumber, email,
reservefrom, reserveto, room, tour,
guestnumber)
values ('$lastname', '$firstname', '$address',
'$tnumber', '$cnumber', '$email', '$checkin',
'$checkout', '$room', '$tour', '$guest')";
mysqli_query($db, $query);
echo "Data Submitted!";
}
}
}
You're getting multiple inserts because you are looping for each record in $reservations. You should first look into why you are getting multiple records if you expected just a single record reservation.
That aside, alter your code by replacing your while loop with:
if(isset($_POST['submitBtn']) && $row = mysqli_fetch_array($reservation)){
if($row['reservefrom'] == $checkin) die("Same Date");
$lastname = $_POST['text_lastname'];
$firstname = $_POST['text_firstname'];
// ... other values, then execute your query
}else{
// either submitBtn was not posted or no result were found in $reservation
}
I noticed also that you use return in your code, but the code doesn't seem to be within a function so that's confusing. If it is within a function, it's probably a bad idea to echo from within unless the function is specifically meant to send data directly to the browser.
I have a query to insert but idk how to insert function and session into my database.
Thanks for helping!!
<?php
if (isset($_POST['submit'])){
$address = $_POST['address'];
$poscode = $_POST['poscode'];
$city = $_POST['city'];
$state = $_POST['state'];
$tel_no = $_POST['tel_no'];
$recipient = $_POST['recipient'];
$date = $_POST['date'];
$image = $_FILES['image']['name'];
$image_tmp = $_FILES['image']['tmp_name'];
move_uploaded_file($image_tmp,"receipt/$image");
$insert_order = "insert into user_order(user_email,total_payment,address,poscode,city,state,tel_no,recipient,payment_status,image,date) values ('{$_SESSION['user_email']}','".total_price()."','$address','$poscode','$city','$state','$tel_no','$recipient','pending','$image','$date')";
$insert_order = mysqli_query($con, $insert_order);
if($insert_order){
echo "<script>alert('Order has been placed!')</script>";
echo "<script>window.open('user/my_account.php','_self')</script>";
}}
?>
Please add the this line after the php tag opening.
session_start();
Without starting the session you cant use the session variables in php.
This is works in my case. Please have a try.
I am having a problem of syntax my code correctly and i would like some help. I would like to use an if statement and if isset with multiple variables. My existing code is this.
$album_name = $_POST['album_name'];
$img = $_POST['image'];
$artist = $_POST['artist'];
$company = $_POST['company'];
$genre = $_POST['genre'];
$price = $_POST['price'];
$buy_now = $_POST['buy_now'];
if($album_name !='') && if (isset($artist, $company, $price, $buy_now)){
$sql = mysql_query ("INSERT INTO top_albums_info (album_name, image, artist,company,genre,price,buy_now) VALUES ('$album_name','$img','$artist','$company','$genre','$price','".$buy_now."') ");
echo'<meta http-equiv="refresh" content="0;url=../index.php?page=top_section&action=list">';
}else{
echo'<meta http-equiv="refresh" content="0;url=../index.php?page=top_section&action=add&msg=empty">';
}
?>
How can i combine them?
Thanks.
Personally, I handle form submissions completely differently.
BUT, given the structure you have provided, I would recommend doing things a bit differently for ease:
// create a list of fields to check in an array
$fields = array(
'album_name',
'image',
'artist',
'company',
'price',
'buy_now'
);
// iterate over the fields defined in your array
foreach ($fields AS $field) {
// assign the value to the variable ONLY IF the $_POST is set, otherwise empty string
${$field} = (isset($_POST[$field])) ? $_POST[$field] : '';
}
// Now you KNOW its set, so you just check if the field "is"
if ($album_name && $image && $artist && $company && $price && $buy_now) {
// Do stuff. Form submitted and complete
} else {
// Do other stuff. Form not submitted or incomplete
}
When you write `if ($album)`, it's essentially the same as `if ($album != '')`
Change this line
if($album_name !='') && if (isset($artist, $company, $price, $buy_now)){
to
if ($album_name!='' && isset($artist, $company, $price, $buy_now)) {
Change the line to
if (isset($artist, $company, $price, $buy_now)){
if($album_name !=''){
}
}
This will work for sure
Try to use like:
$album_name = $_POST['album_name'];
$img = $_POST['image'];
$artist = $_POST['artist'];
$company = $_POST['company'];
$genre = $_POST['genre'];
$price = $_POST['price'];
$buy_now = $_POST['buy_now'];
if(!empty($album_name) && isset($album_name,$artist,$company,$price,$buy_now)){
$sql = mysql_query ("INSERT INTO top_albums_info (album_name, image, artist,company,genre,price,buy_now) VALUES ('$album_name','$img','$artist','$company','$genre','$price','".$buy_now."') ");
echo'<meta http-equiv="refresh" content="0;url=../index.php?page=top_section&action=list">';
}else{
echo'<meta http-equiv="refresh" content="0;url=../index.php?page=top_section&action=add&msg=empty">';
}
For more detail about isset(): http://php.net/manual/en/function.isset.php
I'm trying to update the database using the ajax, but getting some error below error if if see in the console.
INSERT INTO customers(customerName,contactLastName,contactFirstName, phone, addressLine1,addressLine2, city, state, postalCode,country,salesRepEmployeeNumber,creditLimit) VALUES (,,,, ,,,,,,,)
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ',,, ,,,,,,,)' at line 1
I have hilighted the JS code which contains the prototype ajax code and then the php code which contains the insert details
can you guys help me out in this issue
My site link
http://localhost/fashionsite/customer.php
my js codeenter code here
$('submit_btn').observe('click', function(ev) {
$('customerdetails').request({
method: 'get',
onFailure: function() {
alert("failed");
},
onComplete: function(details){
console.log(details.responseText);
//alert("inserted success fully");
//$("content_updated").update(details.responseText);
}
});
ev.preventDefault();
});
my php code
<?php
include 'config.php';
include 'opendb.php';
//$sNO = $_POST["sNO"];
//$customerNumber = $_POST["customerNumber"];
$customerNames = $_POST["customerName"];
$contactLastName = $_POST["contactLastName"];
$contactFirstName = $_POST["contactFirstName"];
$phone = $_POST["phone"];
$addressLine1 = $_POST["addressLine1"];
$addressLine2 = $_POST["addressLine2"];
$city = $_POST["city"];
$state = $_POST["state"];
$postalCode = $_POST["postalCode"];
$country = $_POST["countryText"];
$salesRepEmployeeNumber = $_POST["salesRepEmployeeNumber"];
$creditLimit = $_POST["creditLimit"];
/*echo $customerNumber .'<br/>'. $customerName .'<br/>'. $contactLastName .'<br/>'. $contactFirstName .'<br/>'. $phone .'<br/>'. $addressLine1 .'<br/>'. $addressLine2 .'<br/>'. $city .'<br/>'. $state .'<br/>'. $postalCode .'<br/>'. $country .'<br/>'. $salesRepEmployeeNumber .'<br/>'. $creditLimit;*/
$sql = "INSERT INTO customers(customerName,contactLastName,contactFirstName, phone, addressLine1,addressLine2, city, state, postalCode,country,salesRepEmployeeNumber,creditLimit) VALUES ($customerNames,$contactLastName,$contactFirstName,$phone, $addressLine1,$addressLine2,$city,$state,$postalCode,$country,$salesRepEmployeeNumber,$creditLimit)";
print $sql;
//echo $sql .'<br/><br/><br/><br/>';
if (!mysql_query($sql,$conn))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
?>
I have hilighted the JS code which contains the prototype ajax code and then the php code which contains the insert details
You send GET request, but try in php get values from $_POST array. So then in sql you get 'VALUES (,,,, ,,,,,,,)' and it is cause of error.