php error :Trying to get property of non-object - php

i'm trying the example in php (just begining to learn)
employee.php :
<?php
class Employee {
private $id;
private $name;
private $age;
private $address;
private $tax;
private $salary;
public function __construct($name, $age, $address, $tax, $salary) {
$this->name = $name;
$this->age = $age;
$this->address = $address;
$this->tax = $tax;
$this->salary = $salary;
}
public function __get($param) {
return $this->$param;
}
public function calculateSalary()
{
return $this->salary - ($this->salary * $this->tax / 100);
}
}
index :
<?php
require_once 'db.php';
require_once 'employee.php';
if (isset($_POST['submit']))
{
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
$address = filter_input(INPUT_POST, 'address', FILTER_SANITIZE_STRING);
$age = filter_input(INPUT_POST, 'age', FILTER_SANITIZE_NUMBER_INT);
$salary = filter_input(INPUT_POST, 'salary', FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
$tax = filter_input(INPUT_POST, 'tax', FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
$params = array( ':name' => $name,
':address' => $address,
':age' => $age,
':salary' => $salary,
':tax' => $tax);
if(isset($_GET['action']) && $_GET['action'] == 'edit' && isset($_GET['id'])){
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
$sql = 'UPDATE employees SET name = :name ,address = :address , age = :age , salary = :salary, tax =:tax WHERE id = :id';
$params[':id'] = $id;
} else {
$sql = 'INSERT INTO employees SET name = :name ,address = :address , age = :age , salary = :salary, tax =:tax ';
}
$stmt = $connection->prepare($sql);
if($stmt->execute($params) === true
)
{
$message = 'Employee ' . $name . ' saved successfully';
header('Location: /advancedphp');
exit;
} else {
$error = true;
$message = 'Error saving employee ' . $name ;
}
}
if (isset($_GET['action']) && $_GET['action'] == 'edit' && isset($_GET['id'])) {
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
if ($id > 0) {
$sql = 'SELECT * FROM employees WHERE id = :id';
$result = $connection->prepare($sql);
$founduser = $result->execute(array(':id' => $id));
if($founduser === true){
$user = $result->fetchall(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, 'Employee', array('name', 'age', 'address', 'tax', 'salary'));
$user = array_shift($user);
}
}
}
//Reading from database back
$sql = 'SELECT * FROM employees';
$stmt = $connection->query($sql);
$result = $stmt->fetchAll(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, 'Employee', array('name', 'age', 'address', 'tax', 'salary'));
?>
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" href="main.css">
<link rel="stylesheet" href="css/font-awesome.css">
<title>PDO by example</title>
</head>
<body>
<div class="wrapper">
<div class="empform">
<form class="appform" method="post" enctype="application/x-www-form-urlencoded">
<fieldset>
<legend>Employee Information</legend>
<?php if(isset($message)) { ?>
<p class="message <?= isset($error) ? 'error' : ' ' ?>"><?= $message ?></p>
<?php } ?>
<table>
<tr>
<td>
<label for="name">Employee Name</label>
</td>
</tr>
<tr>
<td>
<input required type="text" name="name" id="name" placeholder="Write the employee name " maxlength="50" value="<?= isset($user) ? $user->name : ' ' ?>">
</td>
</tr>
<tr>
<td>
<label for="age">Employee Age</label>
</td>
</tr>
<tr>
<td>
<input required type="number" name="age" id="age" min="22" max="60" value="<?= isset($user) ? $user->age : ' ' ?>">
</td>
</tr>
<tr>
<td>
<label for="address">Employee Address</label>
</td>
</tr>
<tr>
<td>
<input required type="text" name="address" id="address" placeholder="Write the employee address " maxlength="100" value="<?= isset($user) ? $user->address : ' ' ?>">
</td>
</tr>
<tr>
<td>
<label for="salary">Employee Salary</label>
</td>
</tr>
<tr>
<td>
/*line 105*/ <input required type="number" step="0.01" name="salary" id="salary" min="1500" max="9000" value="<?= isset($user) ? $user->salary : ' ' ?>">
</td>
</tr>
<tr>
<td>
<label for="tax">Employee Tax (%)</label>
</td>
</tr>
<tr>
<td>
<input required type="number" step="0.01" name="tax" id="tax" min="1" max="5" value="<?= isset($user) ? $user->tax : ' ' ?>">
</td>
</tr>
<tr>
<td>
<input type="submit" name="submit" value="Save">
</td>
</tr>
</table>
</fieldset>
</form>
</div>
<div class="employees">
<table>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Address</th>
<th>Salary</th>
<th>Tax (%)</th>
<th>Control</th>
</tr>
</thead>
<tbody>
<?php
if(false !== $result){
foreach ($result as $employee) {
?>
<tr>
<td><?= $employee->name ?></td>
<td><?= $employee->age?></td>
<td><?= $employee->address ?></td>
<td><?= round($employee->calculateSalary()) ?> L.E</td>
<td><?= $employee->tax ?></td>
<td>
<i class="fa fa-edit"></i>
<i class="fa fa-times"></i>
</td>
</tr>
<?php
}
} else {
?>
<td colspan="5"><p>Sorry, no employees to list</p></td>
<?php
}
?>
</tbody>
</table>
</div>
</div>
</body>
</html>
the project works well .. but if i edit fields .. it updated with errors in name and address fields
"<br /><b>Notice</b>: Trying to get property of non-object in <b>C:\xampp\htdocs\PhpProject\advancedphp\index.php</b> on line <b>105</b><br />"
as shown :
I noticed that the error happen on windows but it gone on linux and it run without errors
I don't know where is the wrong ...
(Sorry i'm begginer)

I do not see where you are instantiating your class Employee
The references to $user are checked by isset() but your references to $employee are not. somewhere you must instantiate the class i.e.
$user = new Employee(stuff,here,as,required,by,constructor);
or
$employee = new Employee(stuff,here,as,required,by,constructor);

Related

Lost PHP variable, last seen in Chrome, answers to the name $quote_date

I can't seem to find my PHP variable $quote_date. I have a form that grabs job records from the database and displays a job's current progress in the form ready to be edited, submitted and updated to the database. All of the job's other records are being collected and displayed correctly but the $quote_date is missing in action. Yet when I echo the $quote_date after the renderForm() function is executed it appears to really exist, at least at that point. Why is the $quote_date not being displayed in the form?
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Allow the user to both create new records and edit existing records.
// Connect to the database.
$connect = mysqli_connect('localhost', 'username', 'password', 'database');
if ( !$connect ) {
die( 'connect error: '.mysqli_connect_error() );
}
// creates the new/edit record form.
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($error = '', $id = '', $start_date = '', $company = '', $stock_code = '', $card_quantity = '', $fiske_print = '', $carrier_quantity = '', $quoted = '', $quote_details = '', $quoted_date = '', $quote_accepted = '', $quote_accepted_date = '', $proof_sent = '', $proof_sent_date = '', $proof_approved = '', $proof_approved_date = '', $printed = '', $print_date = '', $closed_loop_allocated = '', $invoiced = '', $invoiced_date = '', $posted = '', $tracking_number = '', $postal_date = '', $paid = '', $is_bulk_load = '', $bulk_funds_recieved = '', $cards_loaded = '', $notes = '', $completed = '')
{
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<?php
$pageName = 'overview';
?>
<?php
include('header.php');
?>
<h1><?php
if ($id != '') {
echo "Edit Record";
} else {
echo "New Record";
}
?></h1>
<?php
if ($error != '') {
echo "<div style='padding:4px; border:1px solid red; color:red'>" . $error . "</div>";
}
?>
<form action="" method="post">
<div>
<table>
<tr>
<td colspan="2" style="text-align:center;"><strong>Job Details</strong></td>
<td colspan="2" style="text-align:center;"><strong>Job Progress</strong></td>
</tr>
<tr>
<td>ID: </td>
<td><input type="text" name="id" value="<?php echo $id; ?>" readonly></td>
<td>Quoted: </td>
<td><input type="checkbox" name="quoted" value="1" <?php if($quoted == 1){echo 'checked';} ?>></td>
</tr>
<tr>
<td>Start Date: </td>
<td><input type="date" name="start_date" value="<?php if($start_date !== ''){echo date('Y-m-d',strtotime($start_date));} ?>"></td>
<td>Quote Details: </td>
<td><input type="text" name="quote_details" size="40" value="<?php echo $quote_details; ?>"></td>
</tr>
<tr>
<td>Company: </td>
<td><input type="text" name="company" size="40" value="<?php echo $company; ?>"></td>
<td>Quote Date: </td>
// Here is where the mystery lies why is my $quote_date variable missing?
<td><input type="date" name="quote_date" value="<?php echo date('Y-m-d',strtotime($quote_date)); ?>"></td><?php echo '<script type="text/javascript">alert("'.$quote_date.'");</script>'; ?>
</tr>
<tr>
<td>Stock Code: </td>
<td>
<div id="billdesc">
<select id="test" name="stock_code">
<option class="non" value="GS01">GS01</option>
<option class="non" value="GS03">GS03</option>
<option class="non" value="SM01">SM01</option>
<option class="non" value="SM11">SM11</option>
<option class="non" value="CG01">CG01</option>
<option class="non" value="CG38">CG38</option>
<option class="editable" value="Other">Other</option>
</select>
<input class="editOption" style="display:none;" placeholder="Text juaj"></input>
</div>
</td>
<td>Quote Accepted: </td>
<td><input type="checkbox" name="quote_accepted" value="1" <?php if($quote_accepted == 1){echo 'checked';} ?>></td>
</tr>
<tr>
<td>Card Quantity: </td>
<td><input type="text" name="card_quantity" value="<?php echo $card_quantity; ?>"></td>
<td>Quote Accepted Date: </td>
<td><input type="date" name="quote_accepted_date" value="<?php if($quote_accepted_date !== ''){echo date('Y-m-d',strtotime($quote_accepted_date));} ?>"></td>
</tr>
<tr>
<td>Carrier Quantity: </td>
<td><input type="text" name="carrier_quantity" value="<?php echo $carrier_quantity; ?>"></td>
<td>Proof Sent: </td>
<td><input type="checkbox" name="proof_sent" value="1" <?php if($proof_sent == 1){echo 'checked';} ?>></td>
</tr>
<tr>
<td>Fiske Print: </td>
<td><input type="checkbox" name="fiske_print" value="1" <?php if($fiske_print == 1){echo 'checked';} ?>></td>
<td>Proof Sent Date: </td>
<td><input type="date" name="proof_sent_date" value="<?php if($proof_sent_date !== ''){echo date('Y-m-d',strtotime($proof_sent_date));} ?>"></td>
</tr>
<tr>
<td rowspan="6" colspan="2" style="text-align:center;">
Notes:<br>
<textarea name="notes" rows="8" cols="70"><?php echo $notes; ?></textarea>
</td>
<td style="text-align:right;">Proof Approved: </td>
<td style="text-align:left;"><input type="checkbox" name="proof_approved" value="1" <?php if($proof_approved == 1){echo 'checked';} ?>></td>
</tr>
<tr>
<td>Proof Approved Date: </td>
<td><input type="date" name="proof_approved_date" value="<?php if($proof_approved_date !== ''){echo date('Y-m-d',strtotime($proof_approved_date));} ?>"></td>
</tr>
<tr>
<td>Printed: </td>
<td><input type="checkbox" name="printed" value="1" <?php if($printed == 1){echo 'checked';} ?>></td>
</tr>
<tr>
<td>Print Date</td>
<td><input type="date" name="printed_date" value="<?php if($print_date !== ''){echo date('Y-m-d',strtotime($print_date));} ?>"></td>
</tr>
<tr>
<td>Closed Loop Allocated: </td>
<td><input type="checkbox" name="closed_loop_allocated" value="1" <?php if($closed_loop_allocated == 1){echo 'checked';} ?>></td>
</tr>
<tr>
<td>Invoiced: </td>
<td><input type="checkbox" name="invoiced" value="1" <?php if($invoiced == 1){echo 'checked';} ?>></td>
</tr>
<tr>
<td>Paid: </td>
<td><input type="checkbox" name="paid" value="1" <?php if($paid == 1){echo 'checked';} ?>></td>
<td>Invoice Date: </td>
<td><input type="date" name="invoice_date" value="<?php if($invoice_date !== ''){echo date('Y-m-d',strtotime($invoice_date));} ?>"></td>
</tr>
<tr>
<td>Is Bulk Load: </td>
<td><input type="checkbox" name="is_bulk_load" value="1" <?php if($is_bulk_load == 1){echo 'checked';} ?>></td>
<td>Posted: </td>
<td><input type="checkbox" name="posted" value="1" <?php if($posted == 1){echo 'checked';} ?>></td>
</tr>
<tr>
<td>Bulk Funds Recieved</td>
<td><input type="checkbox" name="bulk_funds_recieved" value="1" <?php if($bulk_funds_received == 1){echo 'checked';} ?> ></td>
<td>Postal Date: </td>
<td><input type="date" name="postal_date" value="<?php if($postal_date !== ''){echo date('Y-m-d',strtotime($postal_date));} ?>"></td>
</tr>
<tr>
<td>Cards Loaded: </td>
<td><input type="checkbox" name="cards_loaded" value="1" <?php if($cards_loaded == 1){echo 'checked';} ?>></td>
<td>Tracking Number: </td>
<td><input type="text" name="tracking_number" size="30" value="<?php echo $tracking_number; ?>"></td>
</tr>
<tr>
<td colspan="4" style="text-align:center;">
Completed: <input type="checkbox" name="completed" value="1" <?php if($completed == 1){echo 'checked';} ?>>
<input type="submit" name="submit" value="Save" style="width:90px" />
</td>
</tr>
</table>
<script type="text/javascript">
var initialText = $('.editable').val();
$('.editOption').val(initialText);
$('#test').change(function(){
var selected = $('option:selected', this).attr('class');
var optionText = $('.editable').text();
if(selected == "editable"){
$('.editOption').show();
$('.editOption').keyup(function(){
var editText = $('.editOption').val();
$('.editable').val(editText);
$('.editable').html(editText);
});
}else{
$('.editOption').hide();
}
});
</script>
</body>
</html>
<?php
}
/*
EDIT RECORD
*/
// if the 'id' variable is set in the URL, we know that we need to edit an existing record
if (isset($_GET['id'])) {
// if the form's submit button is clicked, we need to process the form
if (isset($_POST['submit'])) {
// make sure the 'id' in the URL is valid
if (is_numeric($_POST['id'])) {
// get the form data
// I'll get to this later... get form to display first...
echo 'We are saving a new edit of job ' . $id;
}
// if the 'id' variable is not valid, show an error message
else {
echo "Error!";
}
}
// if the form hasn't been submitted yet, get the info from the database and show the form
else {
// make sure the 'id' value is valid
if (is_numeric($_GET['id']) && $_GET['id'] > 0) {
// get 'id' from URL
$id = $_GET['id'];
// get the record from database
if ($stmt = $connect->prepare("SELECT id, start_date, company, stock_code, card_quantity, fiske_print, carrier_quantity, quoted, quote_details, quoted_date, quote_accepted, quote_accepted_date, proof_sent, proof_sent_date,proof_approved, proof_approved_date, printed, print_date, closed_loop_allocated, invoiced, invoiced_date, posted, tracking_number, postal_date, paid, is_bulk_load, bulk_funds_received, cards_loaded, notes, completed FROM jobs WHERE id = ?")) {
$stmt->bind_param("s", $id);
$stmt->execute();
$stmt->bind_result($id,$start_date,$company,$stock_code,$card_quantity,$fiske_print,$carrier_quantity,$quoted,$quote_details,$quote_date,$quote_accepted,$quote_accepted_date,$proof_sent,$proof_sent_date,$proof_approved,$proof_approved_date,$printed,$printed_date,$closed_loop_allocated,$invoiced,$invoice_date,$posted,$tracking_number,$postal_date,$paid,$is_bulk_load,$bulk_funds_received,$cards_loaded,$notes,$completed);
/* fetch values */
while ($stmt->fetch()) {
printf("%s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s\n", $id,$start_date,$company,$stock_code,$card_quantity,$fiske_print,$carrier_quantity,$quoted,$quote_details,$quote_date,$quote_accepted,$quote_accepted_date,$proof_sent,$proof_sent_date,$proof_approved,$proof_approved_date,$printed,$printed_date,$closed_loop_allocated,$invoiced,$invoice_date,$posted,$tracking_number,$postal_date,$paid,$is_bulk_load,$bulk_funds_received,$cards_loaded,$notes,$completed);
}
// show the form by executing renderForm()
renderForm(NULL, $id,$start_date,$company,$stock_code,$card_quantity,$fiske_print,$carrier_quantity,$quoted,$quote_details,$quote_date,$quote_accepted,$quote_accepted_date,$proof_sent,$proof_sent_date,$proof_approved,$proof_approved_date,$printed,$printed_date,$closed_loop_allocated,$invoiced,$invoice_date,$posted,$tracking_number,$postal_date,$paid,$is_bulk_load,$bulk_funds_received,$cards_loaded,$notes,$completed);
// check to see if we have a quote date..?
echo 'quote date: '.$quote_date;
$stmt->close();
}
// show an error if the query has an error
else {
echo "Error: could not prepare SQL statement";
}
}
// if the 'id' value is not valid, redirect the user back to the view.php page
else {
header("Location: addJob.php");
}
}
}
/*
NEW RECORD
*/
// if the 'id' variable is not set in the URL, we must be creating a new record
else {
// if the form's submit button is clicked, we need to process the form
if (isset($_POST['submit'])) {
// get the form data
$start_date = date("Y-m-d", strtotime($_POST['start_date']));
$company = $_POST['company'];
$stock_code = $_POST['stock_code'];
$card_quantity = $_POST['card_quantity'];
$carrier_quantity = $_POST['carrier_quantity'];
$fiske_print = $_POST['fiske_print'];
$quoted = $_POST['quoted'];
$quote_details = $_POST['quote_details'];
$quote_date = date("Y-m-d", strtotime($_POST['quote_date']));
$quote_accepted = $_POST['quote_accepted'];
$quote_accepted_date = date("Y-m-d", strtotime($_POST['quote_accepted_date']));
$proof_sent = $_POST['proof_sent'];
$proof_sent_date = date("Y-m-d", strtotime($_POST['proof_sent_date']));
$proof_approved = $_POST['proof_approved'];
$proof_approved_date = date("Y-m-d", strtotime($_POST['proof_approved_date']));
$printed = $_POST['printed'];
$printed_date = date("Y-m-d", strtotime($_POST['printed_date']));
$closed_loop_allocated = $_POST['closed_loop_allocated'];
$invoiced = $_POST['invoiced'];
$invoice_date = date("Y-m-d", strtotime($_POST['invoice_date']));
$posted = $_POST['posted'];
$postal_date = date("Y-m-d", strtotime($_POST['postal_date']));
$tracking_number = $_POST['tracking_number'];
$paid = $_POST['paid'];
$is_bulk_load = $_POST['is_bulk_load'];
$bulk_funds_received = $_POST['bulk_funds_received'];
$cards_loaded = $_POST['cards_loaded'];
$completed = $_POST['completed'];
/* Prepare an insert statement */
$query = "INSERT INTO jobs (start_date,company,stock_code,card_quantity,fiske_print,carrier_quantity,quoted,quote_details,quoted_date,quote_accepted,quote_accepted_date,proof_sent,proof_sent_date,proof_approved,proof_approved_date,printed,print_date,closed_loop_allocated,invoiced,invoiced_date,posted,tracking_number,postal_date,paid,is_bulk_load,bulk_funds_received,cards_loaded,notes,completed) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
$stmt = mysqli_prepare($connect, $query);
mysqli_stmt_bind_param($stmt, "sssssssssssssssssssssssssssss", $start_date,$company,$stock_code,$card_quantity,$fiske_print,$carrier_quantity,$quoted,$quote_details,$quote_date,$quote_accepted,$quote_accepted_date,$proof_sent,$proof_sent_date,$proof_approved,$proof_approved_date,$printed,$printed_date,$closed_loop_allocated,$invoiced,$invoice_date,$posted,$tracking_number,$postal_date,$paid,$is_bulk_load,$bulk_funds_received,$cards_loaded,$notes,$completed);
/* Execute the statement */
mysqli_stmt_execute($stmt);
/* close statement */
mysqli_stmt_close($stmt);
// redirect the user
header("Location: index.php");
}
// if the form hasn't been submitted yet, show the form
else {
error_log('SQL error ('.__FILE__.' line '.__LINE__.'): '. $connect->error);
renderForm();
}
}
// close the mysqli connection
$connect->close();
?>

PHP - clear cart from database after make the purchase

I am new in php, and the cart file is called wholesalecart.php
Every time, after I complete the order, and continue shopping, then add a new product into the cart, the previous product is still in the cart.
So I think I may need to clear the cart in the database after making the purchase, so that next time when I continue shopping, it will not keep the old items from the database.
The wholesalecart.php file code is below:
require_once("../login/protect.php");
//required for db connection
require_once '../includes/conn.php';
function updateDbCart(){
$userId = $_SESSION['id'];
//create our json cart if it exists ready to put in db
if (!empty($_SESSION['wholesalecart'])){
$jsonCart = json_encode($_SESSION['wholesalecart']);
} else {
$jsonCart = '';
}
//see if user already has a record in db for us else add it
$query = "SELECT count(*) as found FROM user_carts WHERE user_id='$userId'";
$result = mysql_query($query);
$data = mysql_fetch_assoc($result);
if($data['found']) {
$query = "UPDATE user_carts SET cart='$jsonCart' WHERE user_id='$userId'";
$result = mysql_query($query);
} else {
$query = "INSERT INTO user_carts (user_id, cart) VALUES ('$userId', '$jsonCart')";
$result = mysql_query($query);
}
}
if(!empty($_POST['sendwholesale']))
{
$i=0;
foreach ($_POST as $p => $q)
{
$i++;
if(ctype_digit($_POST['qty'.$i]))
{
$_SESSION['wholesalecart'][$_POST['prodid'.$i]] = $_POST['qty'.$i];
}
}
updateDbCart();
}
elseif (isset($_POST['update']))
{
$prod = $_POST['prodid'];
$qty = (ctype_digit($_POST['qty']) ? $_POST['qty'] : 1);
$_SESSION['wholesalecart'][$prod] = $qty;
updateDbCart();
}
elseif (isset($_POST['remove']))
{
$prod = $_POST['prodid'];
unset($_SESSION['wholesalecart'][$prod]);
updateDbCart();
}
elseif (isset($_POST['empty']))
{
unset($_SESSION['wholesalecart']);
updateDbCart();
}
$_SESSION['wholesaletotalItems'] = 0;
if (!empty($_SESSION['wholesalecart']))
{
foreach ($_SESSION['wholesalecart'] as $p => $q)
{
$_SESSION['wholesaletotalItems'] += $q;
}
}
$_SESSION['wholesaletotal'] = 0;
$cartTotal = 0;
//get the cart from db
$userId = $_SESSION['id'];
$query = "SELECT cart as cartDataFromDb FROM user_carts WHERE user_id='$userId'";
$result = mysql_query($query);
$data = mysql_fetch_assoc($result);
$_SESSION['wholesalecart'] = json_decode($data['cartDataFromDb'], true);
if (!empty($_SESSION['wholesalecart']))
{
$displayContent = '
<table id="shopCart">
<tr class="tableHead">
<td>Product Code</td>
<td>Product Name</td>
<td class="center small">Price</td>
<td class="center qtysmall">Qty</td>
<td class="center small">Subtotal</td>
<td class="center small"></td>
</tr>
';
$i=0;
foreach ($_SESSION['wholesalecart'] as $p => $q)
{
$query = "SELECT * FROM products WHERE prodid='$p'";
$result = mysql_query($query);
while ($data = mysql_fetch_array($result))
{
$i++;
$price = sprintf('%.2f',$data['wholesaleprice']);
$subTotal = ($price * $q);
$displayContent .= '
<tr class="cartRow">
<td>'.$data['prodid'].'</a></td>
<td>'.$data['prodname'].'</td>
<td class="center">$'.$price.'</td>
<td class="center">
<form action="wholesalecart.php" method="post">
<input type="hidden" name="prodid" value="'.$data['prodid'].'" />
<input type="text" class="qty" name="qty" size="3" maxlength="3" value="'.$q.'" />
<input type="submit" class="update" name="update" value="Update" />
</form>
</td>
<td class="center">$'.$subTotal.'</td>
<td class="center">
<form action="wholesalecart.php" method="post">
<input type="hidden" name="prodid" value="'.$data['prodid'].'" />
<input type="submit" class="remove" name="remove" value="Remove" />
</form>
</td>
</tr>';
$checkout .= '
<input type="hidden" value="'.$data['prodname'].' - '.$p.'" name="item_name_'.$i.'"/>
<input type="hidden" value="'.$q.'" name="quantity_'.$i.'"/>
<input type="hidden" value="'.$price.'" name="amount_'.$i.'"/>
<input type="hidden" value="'.$i.'" name="count"/>
';
$_SESSION['wholesaletotal'] += $subTotal;
$cartTotal += $subTotal;
} //end while
} //end foreach
$i++;
//add button to email the cart if logged in
if(isset($_SESSION['username']))
{
$emailIt = '
<tr class="cartRow">
<form action="wholesalemailcart.php" method="post">
<td colspan="6">Additional comments:<br /><textarea style="width:450px;height:80px;" name="cartMessage">'.$_SESSION['cartMessage'].'</textarea></td>
</tr>
<tr class="actionsRow">
<td colspan="4"></td>
<td colspan="2" class="left">
<input type="submit" class="checkout" name="mail" value="Continue With Order" />
</form>
</td>
</tr>
';
}
$displayContent .= '
<tr class="freightRow">
<td colspan="2" class="center">
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
'.$checkout.'
<input type="hidden" value="Shipping" name="item_name_'.$i.'"/>
<input type="hidden" value="1" name="quantity_'.$i.'"/>
<input type="hidden" value="'.$i.'" name="count"/>
</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr class="totalsRow">
<td></td>
<td></td>
<td class="subtotal">Subtotal</td>
<td class="subtotal">'.$_SESSION['wholesaletotalItems'].'</td>
<td class="subtotal">'.sprintf('%.2f',$_SESSION['wholesaletotal']).'</td>
<td></td>
</tr>
<tr class="actionsRow">
<td></td>
<td></td>
<td colspan="2" class="center">
<input type="hidden" value="_cart" name="cmd"/>
<input type="hidden" value="1" name="upload"/>
<input type="hidden" value="email#email.co.nz" name="business"/>
<input type="hidden" value="NZD" name="currency_code"/>
<!-- <input type="submit" class="checkout" name="Action" value="Checkout" /> -->
</form>
</td>
<td colspan="2" class="left">
<!-- old $emailIt -->
</td>
'.$emailIt.'
</tr>
</table>
';
}
else
{
$displayContent = '<p class="center">Sorry you have no items in your Shopping cart</p>
<p class="center">Continue Shopping?</p>';
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<!-- InstanceBegin template="/Templates/template.dwt" codeOutsideHTMLIsLocked="false" -->
<head>
<link href="../css/hbcl-styles.css" rel="stylesheet" type="text/css" media="screen" />
<link href="../css/menu.css" rel="stylesheet" type="text/css" media="screen" />
<link href="../css/shop.css" rel="stylesheet" type="text/css" media="screen" />
<link href="../css/map-styles.css" rel="stylesheet" type="text/css" media="screen" />
</head>
<body>
<div id="wrap">
<a name="top"></a>
<div id="header"></div>
<div id="main">
<div id="left-content">
<div id="left-menu">
<?php include('../includes/menu.php'); ?>
</div>
<?php include('../includes/left-sidebar.php'); ?>
</div>
<!-- InstanceBeginEditable name="content" -->
<div id="middle-content">
<h1>Wholesale Shopping Cart</h1>
<h3>Continue Shopping </h3>
<p>Select and add more products from the left hand dealer product menu to your shopping cart.
<br />
<br />
</p>
<h3>Shopping Cart Contents</h3>
<p>At any time you can select the <strong>Cart</strong> button at the bottom of the left hand menu to check the contents of your shopping cart.
<br />
<br />
</p>
<h3>Continue With Order</h3>
<p>Once your cart is complete, select <strong>Continue With Order</strong>.</p>
<p> </p>
<?php echo $displayContent ?>
</div>
<!-- InstanceEndEditable -->
<div id="right-content">
<?php include('../includes/right-sidebar.php'); ?>
</div>
<?php include('../includes/footer.php'); ?>
</div>
</div>
</body>
<!-- InstanceEnd -->
</html>
The Continue With Order button in the form tag, link to wholesalemailcart.php
<?php
session_start();
require_once("../login/protect.php");
//required for db connection
require_once '../includes/conn.php';
require_once '../classes/class.phpmailer.php';
if(isset($_POST['mail'])){
$_SESSION['cartMessage'] = $_POST['cartMessage'];
}
if (!empty($_SESSION['wholesalecart']))
{
$i=0;
$cartTotal=0;
foreach ($_SESSION['wholesalecart'] as $p => $q)
{
$query = "SELECT * FROM products WHERE prodid='$p'";
$result = mysql_query($query);
while ($data = mysql_fetch_array($result))
{
$i++;
$price = $data['wholesaleprice'];
$subTotal = ($price * $q);
$mailContent .= '
<tr class="cartRow">
<td>'.$data['prodname'].'</td>
<td>'.$data['prodid'].'</td>
<td class="center">$'.$price.'</td>
<td class="center">'.$q.'</td>
<td class="center">$'.sprintf('%.2f',$subTotal).'</td>
</tr>
';
$cartTotal += $subTotal;
} //end while
} //end foreach
$body = '<br />
<table id="shopCart">
<tr class="tableHead">
<td>Product Name</td>
<td>Code</td>
<td class="center">Price Per Item</td>
<td class="center qtysmall">Qty</td>
<td class="center small">Subtotal</td>
</tr>
'.$mailContent.'
<tr>
<td></td>
<td></td>
<td class="center"><strong>Subtotal</strong></td>
<td class="center">'.$_SESSION['totalItems'].'</td>
<td class="center">$'.sprintf('%.2f',$cartTotal).'</td>
</tr>
<tr class="totalsRow">
<td></td>
<td></td>
<td class="subtotal">Subtotal</td>
<td class="subtotal">'.$_SESSION['wholesaletotalItems'].'</td>
<td class="subtotal">'.sprintf('%.2f',$_SESSION['wholesaletotal']).'</td>
<td></td>
</tr>
<tr>
<td colspan="5" class="cartRow">Additional message: <strong>'.$_SESSION['cartMessage'].'</strong></td>
</tr>
</table>
';
}
if(!isset($_POST['confirmSend']))
{
$id = $_SESSION['id'];
$username = $_SESSION['username'];
$query = "SELECT * FROM logins WHERE id='$id' AND username='$username'";
$result = mysql_query($query);
while($data = mysql_fetch_array($result))
{
$name = $data['name'];
$email = $data['email'];
$address = $data['address'];
$address1 = $data['address1'];
$address2 = $data['address2'];
$address3 = $data['address3'];
$city = $data['city'];
}
$displayContent = '
<h1>Shopping Cart Completion</h1>
<p><strong>Your details.</strong></p><br/>
<form action="'.$_SERVER['SCRIPT_NAME'].'" method="post">
<table>
<tr>
<td class="mailform" width="150">Company Name:</td><td> <p>'.$name.'</p></td>
</tr>
<tr>
<td class="mailform">Email Address:</td><td><p>'.$email.'</p></td>
</tr>
<tr>
<td class="mailform">Address:</td><td><p>'.$address1.'</p></td>
</tr>
<tr>
<td class="mailform"></td><td><p>'.$address2.'</p></td>
</tr>
<tr>
<td class="mailform"></td><td><p>'.$address3.'</p></td>
</tr>
<tr>
<td class="mailform"></td><td><p>'.$city.'</p></td>
</tr>
<tr>
<td class="mailform"></td><td><p>'.$address.'</p></td>
</tr>
</table>
<p><strong>Your Order will be sent Hauraki Brewing containing the following selections.</strong></p>
'.$body.'
<br />
<p>Please select <strong>Send Order</strong> to complete your wholesale order.</p><br/>
<input type="submit" name="confirmSend" value="Send Order">
</form>
';
}
elseif(!empty($_SESSION['wholesalecart']) && (isset($_POST['confirmSend']) || isset($_POST['ReconfirmSend']) ))
{
$id = $_SESSION['id'];
$username = $_SESSION['username'];
$query = "SELECT * FROM logins WHERE id='$id' AND username='$username'";
$result = mysql_query($query);
while($data = mysql_fetch_array($result))
{
$name = $data['name'];
$email = $data['email'];
$address = $data['address'];
$address1 = $data['address1'];
$address2 = $data['address2'];
$address3 = $data['address3'];
$city = $data['city'];
}
if(isset($_POST['ReconfirmSend']))
{
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$location = $_POST['location'];
$address = $data['address'];
}
if(strlen($name) > 2 && strlen($email) > 2)
{
$mail = new PHPMailer();
$mail->From = $email;
$mail->FromName = $name;
$mail->AddAddress("XXXX");
$mail->AddReplyTo($email, $name);
$mail->WordWrap = 50;
//$mail->AddAttachment("/tmp/image.jpg", "new.jpg"); // optional attachemnt and name
$mail->IsHTML(true);
$mail->Subject = $name.' - Hauraki Brewing Wholesale Order';
$mail->Body = '
<br>
Order From: '.$name.' <br><br/>
Email: '.$email.'<br>
Address: '.$address1.'<br>
'.$address2.'<br>
'.$address3.'<br>
'.$city.'<br>
'.$address.'
<br><br>
<br><br>
'.$body.'
<br>
';
//$mail->AltBody = "$message";
if(!$mail->Send())
{
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
//send second email
$mail2 = new PHPMailer();
$mail2->From = $email;
$mail2->FromName = $name;
$mail2->AddAddress($email);
$mail2->AddReplyTo($email, $name);
$mail2->WordWrap = 50;
//$mail->AddAttachment("/tmp/image.jpg", "new.jpg"); // optional attachemnt and name
$mail2->IsHTML(true);
$mail2->Subject = $name.' - Hauraki Brewing Order Confirmation';
$mail2->Body = '
<br>
Thank you for your order.<br/><br/>A copy of the order you placed is included below. Please phone or email us immediately if you see any discrepancies in what you ordered.<br/>
'.$body.'
<br>
';
//$mail->AltBody = "$message";
if(!$mail2->Send())
{
echo "second Message could not be sent. <p>";
echo "Mailer Error: " . $mail2->ErrorInfo;
exit;
}
/**
*
* For debugging send a third email to david
*
*/
/*
* End debug section
*/
//header("Location: order-form.php?success=y");
//exit();
$displayContent .= '
<h1>Wholesale Order Completed</h1>
<p>Your wholesale order has been sent successfully. You should receive a confirmation email that your order has been sent.<br/><br/>
Thank you for your order, we appreciate your business. <br/><br/>
Continue shopping and place another order or logout.
</p>
';
}
else
{
$displayContent = '
<p class="error">Invalid Fields</p>
<p><strong>Please enter your details to continue.</strong></p><br/>
<form action="'.$_SERVER['SCRIPT_NAME'].'" method="post">
<table>
<tr>
<td class="mailform" width="150">Company Name:</td><td><input type="text" name="name" value="" maxlength="100" size="40"/></td>
</tr>
<td class="mailform">Phone:</td><td><input type="text" name="phone" value="" maxlength="100" size="40"/></td>
</tr>
<td class="mailform">Email Address:</td><td><input type="text" name="email" value=""maxlength="100" size="40" /></td>
</tr>
<td class="mailform">Location (Town/City):</td><td><input type="text" name="location" value="" maxlength="100" size="40" /></td>
</tr>
</table>
<p><strong>Your email will list these products.</strong></p>
'.$body.'
<p>This will email your Order Enquiry to Hauraki Brewing, click <strong>Send Enquiry</strong> to continue.</p><br/>
<input type="submit" name="ReconfirmSend" value="Confirm and send">
</form>
';
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<body>
<div id="wrap"><a name="top"></a>
<div id="header"></div>
<div id="main">
<div id="left-content">
<div id="left-menu">
<?php include('../includes/menu.php'); ?>
</div>
<?php include('../includes/left-sidebar.php'); ?>
</div>
<!-- InstanceBeginEditable name="content" -->
<div id="middle-content">
<?php echo $displayContent ?>
</div>
<!-- InstanceEndEditable -->
<div id="right-content">
<?php include('../includes/right-sidebar.php'); ?>
</div>
<?php include('../includes/footer.php'); ?>
</div>
</div>
</body>
<!-- InstanceEnd --></html>
Welcome to the fun and sometimes frustrating world of PHP programming!!
If I am scrolling through this correctly, your cart is kept in session variables which is not uncommon... I use them too for my carts. You mentioned database, but didn't see that referenced for the cart... unless I missed it. SESSION variables "keep" for a variable amount of time depending on a lot of different settings (PHPINFO, timeouts, etc) or unless you physically clear them out yourself using unset.
If what you are describing is right, it sounds like you hit the nail on the head and need to clear the cart out between orders.
I did notice some code that looks like it might have been written for that purpose, but I might be wrong...
elseif (isset($_POST['empty']))
{
unset($_SESSION['wholesalecart']);
updateDbCart();
}
But looking through the code you provided, I can't see this being called anywhere. Are you just missing the call to clear out the cart?
I solved this question.
Just deleted
function updateDbCart(){
$userId = $_SESSION['id'];
//create our json cart if it exists ready to put in db
if (!empty($_SESSION['wholesalecart'])){
$jsonCart = json_encode($_SESSION['wholesalecart']);
} else {
$jsonCart = '';
}
Create a logout link and inside the logout page put these:
unset($_SESSION["wholesalecart"]);

PHP delete/update only affects last MySQL row

Whether using the delete or update function, only the last row is updated/deleted. It doesn't matter what field I update/delete, only the last row is passed. I'm unable to find the issue other than the fact that a unique ID is not being passed. I'm new to PDO, so I'm not too familiar with debugging. Any help is appreciated.
<form action="" id="form" method="post">
<?php
function UserForm($customers = array())
{
ob_start(); ?>
<?php
$id = $customers['id'];
?>
<tr>
<td><input type="text" name="name" value="<?php echo $customers['name']; ?>"></td>
<td><input type="text" id="email" name="email" value="<?php echo $customers['email']; ?>"></td>
<td><input type="text" id="phone" name="phone" value="<?php echo $customers['phone']; ?>"></td>
<td><input type="text" id="address" name="address" value="<?php echo $customers['address']; ?>"></td>
<td><input type="text" id="proudct" name="product" value="<?php echo $customers['product']; ?>"></td>
<td><input type="text" id="firmware" name="firmware" value="<?php echo $customers['firmware']; ?>"></td>
<td><input type="text" id="datepicker" class="datepicker" name="purchase_date" value="<?php echo $customers['purchase_date']; ?>"></td>
<td align="center">
<input type="hidden" name="id" value="<?php echo $id; ?>">
<input type="submit" value="<?php echo $id; ?>" name="delete" value="X" onclick="return confirm('WARNING! \n\nAre you sure you want to DELETE?')" >
</td>
</tr>
<tr>
<td colspan="8">
<input type="hidden" name="id_update" value="<?php echo $id; ?>" />
<input type="submit" name="update" value="Update <?php echo $id; ?>" />
</td>
</tr>
<?php
$data = ob_get_contents();
ob_end_clean();
return $data;
} ?>
<?php
$pdo = new PDO("mysql:host=localhost;dbname=project", $username, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
//$query = $pdo->prepare("SELECT * FROM customers ORDER BY purchase_date ASC");
if (isset($_POST['desc'])){
$sort = "desc";
$query = $pdo->prepare("SELECT * FROM customers ORDER BY purchase_date DESC");
}
else {
$sort = "asc";
$query = $pdo->prepare("SELECT * FROM customers ORDER BY purchase_date ASC");
}
$query->execute();
?>
<table class="table table-striped table-bordered table-responsive">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>Address</th>
<th>Product</th>
<th>Firmware Version</th>
<th align="center">
Purchase Date
<?php
if ($sort == "asc") {
echo '<input type="hidden" value="Desc" name="desc" id="sort">';
echo '<a name="desc" href="javascript: submitform()">Desc</a>';
}
else {
echo '<input type="hidden" value="Asc" name="asc" id="sort">';
echo '<a name="asc" href="javascript: submitform()">Asc</a>';
}
?>
</th>
<th>Delete</th>
</tr>
</thead>
<?php
while($customers = $query->fetch(PDO::FETCH_ASSOC)){
echo UserForm($customers);
} //end of while
// Delete customer
if(isset($_POST['delete'])) {
try{
$id = $_POST['id'];
$query = $pdo->prepare("delete from customers where id = :id");
$query->bindParam(':id', $id);
$query->execute(array(':id' => $id));
echo "Customer successfully deleted." . $_POST['id'];
echo '<META http-equiv="refresh" content="1;URL=view_edit.php">';
}catch(PDOException $e){
echo "Failed to delete the MySQL database table ... :".$e->getMessage();
} //end of try
} //end of isset delete
// Edit customer
if(isset($_POST['update'])) {
try {
$name = $_POST['name'];
$id = $_POST['id'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$product = $_POST['product'];
$firmware = $_POST['firmware'];
$purchase_date = $_POST['purchase_date'];
$query = $pdo->prepare("UPDATE customers SET name = '$name', email = '$email', phone = '$phone', address = '$address', product = '$product', firmware = '$firmware', purchase_date = '$purchase_date' where id = '$id'");
$query -> execute( array(
':name' => $name,
':email' => $email,
':phone' => $phone,
':address' => $address,
':product' => $product,
':firmware' => $firmware,
':purchase_date' => $purchase_date
));
echo "Customer succesfully updated" . $id;
echo '<META http-equiv="refresh" content="1;URL=view_edit.php">';
}catch(PDOException $e){
echo "Error! Failed to update customers :".$e->getMessage();
}//end of try
} //end of isset update
?>
To debug your code, try using print_r($_POST); exit(); immediately after your if(isset($_POST['delete/update'])) { to see what's being passed in the array when you post.
I'm a bit of a noob myself, but I suspect the problem here could be you haven't defined where your form starts and ends, so you're submitting the whole table. Try adding a form for each of your records, with a form name the same as your customer id.
<form name="formname<?php echo $id; ?>"> ... your input fields and submit button... </form>, then when you submit, you'll only be submitting that particular form and the data it contains.
I hope that helps!
$query = $pdo->prepare("delete from customers where id = :id"
I bet this ID is unique..
Resolved the issue. Moved the <form> tag above the beginning of the table row.

trouble in submiting form in php

I'm doing a database project for university and I'm having a problem in here.
I receive from a previous page an id as $_POST['ids'] and in the form I send that same value in a hidden field so it can do a sort of a cicle.
But when I click the submit button I got a lot of errors on $service_info and no information is loaded on the page. I tried do var_dump() everything and I just can't find what is the problem in here.
<?php
//error_reporting();
require 'core/init.php';
require 'db/connect.php';
require 'functions/security.php';
?>
<html>
<head>
<title>Make a reservation</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="css/common.css">
</head>
<body>
<?php require 'parts/header.php'; ?>
<hr>
<?php
$query = "SELECT * FROM service WHERE id=" . $_POST['ids'];
if ($result = $db->query($query)) {
if ($result->num_rows) {
$service_info = $result->fetch_object();
$result->close();
}
}
$query = "SELECT name FROM tour WHERE id =" . $service_info->idtour;
if ($result = $db->query($query)) {
if ($result->num_rows) {
$tour_name = $result->fetch_object();
$result->close();
}
}
$query = "SELECT SUM(nrseats) AS res_seats FROM reservation_service WHERE idservice =" . $service_info->id;
$nr_reservations_info = $db->query($query);
$nr_reservations = $nr_reservations_info->fetch_row();
$nr_reservations_info->close();
$count = $service_info->nrseats - $nr_reservations[0];
if($count === 0){
echo "<script>alert('There are no more places available for this tour. You are being redirected for the main page!')</script>";
echo "<script>window.open('index.php','_self')</script>";
}
else{
$count = $service_info->nrseats;
}
?>
<form action="" method="POST">
<div class="registering">
<table>
<tbody>
<tr>
<td>
<label for="tname">Related tour</label>
</td>
<td>
<label for="splace"><br>Service name</label>
</td><p><br></p>
</tr>
<tr>
<td>
<input type="text" readonly="" name="tour" id="tour" required="" autofocus="" value="<?php echo $tour_name->name ?>">
</td>
<td>
<input type="text" readonly="" name="name" id="name" required="" value="<?php echo $service_info->name ?>">
</td>
</tr>
<tr>
<td>
<label for="sprice"><br>Price (€)</label>
</td>
<td>
<label for="sdescription"><br>Description</label>
</td>
</tr>
<tr>
<td>
<input type="number" name="price" id="price" readonly="" required="" value="<?php echo $service_info->price ?>">
</td>
<td>
<input type="text" name="description" id="description" required="" readonly="" value="<?php echo $service_info->description ?>">
</td>
</tr>
<tr>
<td>
<label for="sseats"><br>Seats left</label>
</td>
<td>
<label for="snreservations"><br>Number of reservations (people)</label>
</td>
</tr>
</tr>
<tr>
<td>
<input type="number" name="nrseats" id="nrseats" required="" value="<?php echo $count ?>" readonly="">
</td>
<td>
<input type="number" name="nrreservations" id="nrreservations" required="" value="1">
</td>
<td>
<input type="hidden" name="ids" required="" value="<?php $service_info->id ?>">
</td>
</tr>
</tr>
<tr>
<td colspan="2">
<label for="next"><br></label>
<input type="submit" value="Next">
</td>
</tr>
</tbody>
</table>
</div>
</form>
</body>
</html>
<?php
if (!empty($_POST)) {
if (isset($_POST['name'], $_POST['ids'], $_POST['tour'], $_POST['price'], $_POST['description'], $_POST['nrseats'], $_POST['nrreservations'])) {
$_POST = array_map("trim", $_POST);
$name = $_POST['name'];
$tour = $_POST['tour'];
$price = $_POST['price'];
$description = $_POST['description'];
$nrseats = $_POST['nrseats'];
$nrreservations = $_POST['nrreservations'];
$ids = $_POST['ids'];
if (!empty($name) && !empty($ids) && !empty($tour) && !empty($price) && !empty($description) && !empty($nrseats) && !empty($nrreservations)) {
$query = "SELECT id FROM customer WHERE email='" . $_SESSION['user_email'] . "'";
if ($result = $db->query($query)) {
$id_user = $result->fetch_object();
$result->close();
}
$query = "SELECT id FROM reservation WHERE idtour={$service_info->idtour} AND idcustomer={$id_user->id}";
if ($result = $db->query($query)) {
if ($result->num_rows) {
$id_reservation = $result->fetch_object();
$result->close();
}
}
$query = "SELECT * FROM reservation_service WHERE idservice=" . $service_info->id;
if ($result = $db->query($query)) {
if ($result->num_rows) {
$reservation_service_exists = $result->fetch_object();
if ($nrreservations < 1) {
echo "<script>alert('Your must make a reservation for, at least, one person!')</script>";
echo "<script>window.open('new_reservation_service.php','_self')</script>";
} else if ($count - $nrreservations < 0) {
echo "<script>alert('You can not make the reservation because there are only " . $count . " seats available in this tour!')</script>";
echo "<script>window.open('new_reservation_service.php','_self')</script>";
} else if ($result->num_rows) {
$query = "SELECT * FROM reservation WHERE idcustomer= '" . $id_user->id . "' AND idtour= '" . $service_info->idtour . "'";
if ($result = $db->query($query)) {
if ($result->num_rows) {
$reservation_exists = $result->fetch_object();
$result->close();
if ($reservation_exists->idcustomer === $id_user->id) {
if ($reservation_exists->id === $reservation_service_exists->idreservation) {
echo "<script>alert('You already made a reservation for this service. Please see your reservation panel!')</script>";
echo "<script>window.open('reservations.php','_self')</script>";
}
}
}
}
}
}else {
$query = "INSERT INTO reservation_service (idreservation, idservice, date, nrseats) VALUES (?, ?, NOW(), ?)";
$insert = $db->prepare($query);
$insert->bind_param('iii', $id_reservation->id, $service_info->id, $nrreservations);
$insert->execute();
echo "<script>alert('You successfully made a reservation! You are being redirected to your reservations page')</script>";
echo "<script>window.open('reservations.php','_self')</script>";
}
}
}
}
}
?>
change inside your form this input hidden you created:
<input type="hidden" name="ids" required="" value="<?php $service_info->id ?>">
to
<input type="hidden" name="ids" required="" value="<?php echo $service_info->id ?>">
If you don't echoing this value, $_POST['ids'] won't be get any value passed from form.

Form validates but won't submit data to database table

I'm working on this project and it's pretty much finished, it's a form that validates if the user submits invalid data, but for some reason the data won't store in the table and therefore won't get posted back to the screen, I'm just wondering if anybody could spot where I'm going wrong as I've been looking at it for over an hour. Thanks a lot.
Below is my code:
index.php
<!Doctype html public>
<body>
<table cellpadding="5">
<td>
<h1> Games Club Website</h1>
<form action="process.php" method = "post">
<tr>
<td class="label">
<label for="firstName">
First name
</label>
</td>
<td>
<input type="text"
name="firstName"
id="firstName"
value="<?php
if (isset($validator))
echo $validator->getValue('firstName');
?>"
/>
<span class="error">
<?php
if (isset($validator))
echo $validator->getError('firstName');
?>
</span>
</td>
</tr>
<tr>
<td class="label">
<label for="lastName">
Surname
</label>
</td>
<td>
<input type="text"
name="lastName"
id="lastName"
value="<?php
if (isset($validator))
echo $validator->getValue('lastName');
?>"
/>
<span class="error">
<?php
if (isset($validator))
echo $validator->getError('lastName');
?>
</span>
</td>
</tr>
<tr>
<td class="label">
<label for="email">
Email Address
</label>
</td>
<td>
<input type="text"
name="email"
id="email"
value="<?php
if (isset($validator))
echo $validator->getValue('email');
?>"
/>
<span class="error">
<?php
if (isset($validator))
echo $validator->getError('email');
?>
</span>
</td>
</tr>
<tr>
<td class="label">
<label for="age">
Age
</label>
</td>
<td>
<input type="text"
name="age"
id="age"
value="<?php
if (isset($validator))
echo $validator->getValue('age');
?>"
/>
<span class="error">
<?php
if (isset($validator))
echo $validator->getError('age');
?>
</span>
</td>
</tr>
<tr>
<td class="label">
<label>
Gender
</label>
</td>
<td>
<label for="genderMale">Male</label>
<input type="radio"
name="gender"
id="genderMale"
value="Male"
<?php
if (isset($validator))
echo $validator->isChecked("gender", "Male");
?>
/>
<label for="genderFemale">Female?</label>
<input type="radio"
name="gender"
id="genderFemale"
value="Female"
<?php
if (isset($validator))
echo $validator->isChecked("gender", "Female");
?>
/>
<span class="error">
<?php
if (isset($validator))
echo $validator->getError('gender');
?>
</span>
</td>
</tr>
<tr>
<td class="label">
<label>
What is your preferred gaming platform?
</label>
</td>
<td>
<label for="consoleXbox">Xbox 360</label>
<input type="radio"
name="console"
id="consoleXbox"
value="Xbox 360"
<?php
if (isset($validator))
echo $validator->isChecked("console", "Xbox 360");
?>
/>
<label for="consolePs3">Playstation 3</label>
<input type="radio"
name="console"
id="consolePs3"
value="PS3"
<?php
if (isset($validator))
echo $validator->isChecked("console", "PS3");
?>
<label for="consoleWii">Nintendo Wii</label>
<input type="radio"
name="Console"
id="consoleWii"
value="Wii"
<?php
if (isset($validator))
echo $validator->isChecked("console", "Wii");
?>
/>
<span class="error">
<?php
if (isset($validator))
echo $validator->getError('console');
?>
</span>
</td>
</tr>
<tr>
<td class="label">
<label for="password1">
Enter a password:
</label>
</td>
<td>
<input type="password"
name="p1"
id="p1"
value="<?php
if (isset($validator))
echo $validator->getValue('p1');
?>"
/>
<span class="error">
<?php
if (isset($validator))
echo $validator->getError('p1');
?>
</span>
</td>
</tr>
<tr>
<td class="label">
<label for="p2">
Confirm password:
</label>
</td>
<td>
<input type="password"
name="p2"
id="p2"
value="<?php
if (isset($validator))
echo $validator->getValue('p2');
?>"
/>
<span class="error">
<?php
if (isset($validator))
echo $validator->getError('p2');
?>
</span>
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit"
name="submitButton"
id="submitButton"
value="Confirm Registration" />
<input type="reset"
name="resetButton"
id="resetButton"
value="Clear Data"
style="margin-right: 20px;" />
</td>
</tr>
</form>
</td>
</table>
</body>
</html>
Process.php
<?php
require_once "FormValidator.php";
$validator = new FormValidator();
if ($validator->validate($_POST)) {
require 'dao.php';
}
else {
require 'index.php';
}
?>
FormValidator.php
<?php
class FormValidator {
private $valid;
private $errors;
private $data;
public function __construct() {
$this->valid = TRUE;
$this->errors = array();
$this->data = NULL;
}
public function validate($data) {
$this->data = $data;
if (empty($data['firstName'])) {
$this->valid = FALSE;
$this->errors['firstName'] = 'A <u>First Name</u> is required<br/>';
}
if (empty($data['lastName'])) {
$this->valid = FALSE;
$this->errors['lastName'] = 'A <u>Surname</u> is required.<br/>';
}
if (empty($data['p1'])) {
$this->valid = FALSE;
$this->errors['p1'] = 'A <u>Password</u> is required.<br/>';
}
if (empty($data['console'])) {
$this->valid = FALSE;
$this->errors['console'] = 'Please choose a <u>Console</u>.<br/>';
}
if (empty($data['p2'])) {
$this->valid = FALSE;
$this->errors['p2'] = 'Please <u>Confirm</u> password.<br/>';
}
if (empty($data['age'])) {
$this->valid = FALSE;
$this->errors['age'] = 'Please enter your <u>Age</u>.<br/>';
}
else if (!$this->isValidIntegerInRange($data['age'], 18, 100)) {
$this->valid = FALSE;
$this->errors['age'] = 'Invalid age. You also need to be at least 18 to sign up.<br/>';
}
if (empty($data['email'])) {
$this->valid = FALSE;
$this->errors['email'] = 'Please enter a valid <u>email address</u>.<br/>';
}
else if (!$this->isValidEmail($data['email'])) {
$this->valid = FALSE;
$this->errors['email'] = 'Incorrect format (name#website.something is required)<br/>';
}
if (empty($data['p2'])) {
$this->valid = FALSE;
$this->errors['p2'] = 'Please <u>Confirm</u> password.<br/>';
}
if (!empty($data['p1'])
&& !empty($data['p2'])
&& $data['p1'] !== $data['p2']) {
$this->valid = FALSE;
$this->errors['p2'] = 'Error, passwords <u>do not match</u> .<br/>';
}
if (empty($data['gender'])) {
$this->valid = FALSE;
$this->errors['gender'] = '<u>Please select a Gender.<u>';
}
return $this->valid;
}
public function getError($key) {
$error = "";
if (isset($this->errors[$key])) {
$error = $this->errors[$key];
}
return $error;
}
public function getValue($key) {
$value = "";
if (isset($this->data[$key])) {
$value = $this->data[$key];
}
return $value;
}
public function isChecked($key, $value) {
$checked = "";
if (isset($this->data[$key]) && $this->data[$key] === $value) {
$checked = ' checked="checked"';
}
return $checked;
}
public function isSelected($key, $value) {
$selected = "";
if (isset($this->data[$key]) && $this->data[$key] === $value) {
$selected = ' selected="selected"';
}
return $selected;
}
private function isValidEmail($email) {
return (filter_var($email, FILTER_VALIDATE_EMAIL) !== FALSE);
}
protected function isValidIntegerInRange($integer, $min, $max) {
$options = array(
'options' => array(
'min_range' => $min,
'max_range' => $max,
)
);
return (filter_var($integer, FILTER_VALIDATE_INT, $options) !== FALSE);
}
}
?>
dao.php
<html>
<body>
<?php
//Make connection to the database
$host = "localhost";
$username = "root";
$password = "";
$database = "my_db";
$dsn = "mysql:host=$host;dbname=$database";
TRY {
$conn = new PDO( $dsn, $username, $password );
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (isset($_POST['submit'])) {
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$age = $_POST['age'];
$gender = $_POST['gender'];
$console = $_POST['console'];
$p1 = $_POST['p1'];
$p2 = $_POST['p2'];
if (isset($_POST['id'])) {
//Updates the record
$id = $_POST['id'];
$sql = "UPDATE userprofile2 SET"
. "firstName=".$conn->quote($fname)
. "lastName=".$conn->quote($lastName)
. "email=".$conn->quote($email)
. "age=".$conn->quote($age)
. "gender=".$conn->quote($gender)
. "console=".$conn->quote($console)
. "p1=".$conn->quote($p1)
. "p2=".$conn->quote($p2)
. "WHERE id = ".$conn->quote($id);
$userprofile2 = $conn->query($sql);
} else {
// Inserts new values into table
$sql = "INSERT INTO userprofile2(firstName, lastName, email, age, gender, console, p1, p2"
. " ) VALUES ("
. $conn->quote($firstName).","
. $conn->quote($lastName).","
. $conn->quote($email).","
. $conn->quote($age).","
. $conn->quote($gender).","
. $conn->quote($console).","
. $conn->quote($p1).","
. $conn->quote($p2) . ")";
$userprofile2 = $conn->query($sql);
}
} elseif (isset($_GET['ID'])) {
// edit mode, allows user to change a selected parameter in the table (Not working)
$userEditDataRows = $conn->query('SELECT * FROM userprofile2 WHERE ID ='.$conn->quote($_GET['ID']));
if (sizeof($userEditDataRows)>0) {
// $row = $userEditDataRows[0];
$firstName = $row['firstName'];
$lastName = $row['lastName'];
$email = $row['email'];
$age = $row['age'];
$gender = $row['gender'];
$console = $row['console'];
$console = $row['p1'];
$console = $row['p2'];
$ID = $_GET['ID'];
}
} else {
//Set the empty values for fields that haven't been filled in
$firstName = '';
$lastName = '';
$email = '';
$age = '';
$gender = '';
$console = '';
$p1 = '';
$p2 = '';
$ID = false;
}
//construct the table
$sql = "SELECT * FROM userprofile2";
$userprofile2 = $conn->query($sql);
$table = '<table>';
$table .= '<tr>';
$table .= '<th> ID </th>
<th> First Name </th>
<th> Last Name </th>
<th> Email Address </th>
<th> Age </th>
<th> Gender </th>
<th> Console </th>
<th> Password </th>
<th> Password (Confirmed) </th>';
$table .= '</tr>';
foreach ($userprofile2 as $userprofile2) {
$table .= ' <tr>';
$table .= ' <td>' . $userprofile2['id'] ." ". '</td>';
$table .= ' <td>' . $userprofile2['firstName'] . '</td>';
$table .= ' <td>' . $userprofile2['lastName'] . '</td>';
$table .= ' <td>' . $userprofile2['email'] . '</td>';
$table .= ' <td>' . $userprofile2['age'] . '</td>';
$table .= ' <td>' . $userprofile2['gender'] . '</td>';
$table .= ' <td>' . $userprofile2['console'] . '</td>';
$table .= ' <td>' . $userprofile2['p1'] . '</td>';
$table .= ' <td>' . $userprofile2['p2'] . '</td>';
$table .= ' </tr> ';
}
$table .= '</table>';
} catch (PDOException $e) {
exit("Connection failed: " . $e->getMessage());
//catches errors and prints them to screen
}
?>
<h2>Thank you <?php echo $_POST["firstName"]; // confirmation of a successful
//entry ?>, your details have been stored!<br /></h2>
<u><h1>Here are the contents of your database:</h1></u>
<?php echo $table ?>
</br>
Click Here to go back to the form. </br>
<html>
<body>
I think the problem is $_POST['id']. It's not defined anywhere so it doesn't get the chance to insert because of the following code block:
if (isset($_POST['id'])) {
Try using $_GET['id'] instead:
if (isset($_GET['id'])) {

Categories