Contact Form - Display items in body of email issues - php

I am having an issue with my contact form and need help with the code.
Here is an image of the "cart", user can add/remove items from the table.
Once they have selected all the products they want, in this example I have added 2 items, they then click the order form button and a form pops up to the left that displays both items.
My problem is that when the email comes through it only displays the last item and not both items from the form, this is what it looks like in the email
How do I make it so that it pulls through both items or all items from the form on the left into the body of my email.
Below is my code, if someone can look through and advise what I must change or what I am doing wrong.
<section class="order">
<?php
$id = isset($_GET['id']) ? (int) $_GET['id'] : 0;
$sql = $con->prepare("SELECT * FROM products WHERE product_id = ?");
$sql->bind_param("i", $id);
$sql->execute();
$result = $sql->get_result();
$rows = $result->num_rows;
{
while($row = $result->fetch_assoc())
{
?>
<div class="product-info">
<form method="post" action="cart.php?action=add&id=<?php echo $row["product_id"]; ?>">
<img src="images/<?php echo $row["image"]; ?>" class="image" /><br /><br>
<h3 class="name"><?php echo $row["productname"]; ?></h3><br>
<h5 class="desc"><?php echo $row["description"]; ?></h5><br>
<h4 class="code"><?php echo $row["code"]; ?></h4><br>
<input type="text" name="quantity" value="1" class="form-control" /><br>
<input type="hidden" name="hidden_name" value="<?php echo $row["productname"]; ?>" />
<input type="hidden" name="hidden_description" value="<?php echo $row["description"]; ?>" />
<input type="hidden" name="hidden_code" value="<?php echo $row["code"]; ?>" />
<input type="submit" name="add_to_cart" style="margin-top:5px;" class="addtocart" value="Add to Cart" />
</form>
</div>
<?php
}
}
?>
<?php
if(isset($_POST["add_to_cart"]))
{
if(isset($_SESSION["shopping_cart"]))
{
$item_array_id = array_column($_SESSION["shopping_cart"], "item_id");
if(!in_array($_GET["id"], $item_array_id))
{
$count = count($_SESSION["shopping_cart"]);
$item_array = array(
'item_id' => $_GET["id"],
'item_name' => $_POST["hidden_name"],
'item_description' => $_POST["hidden_description"],
'item_code' => $_POST["hidden_code"],
'item_quantity' => $_POST["quantity"]);
$_SESSION["shopping_cart"][$count] = $item_array;
}
else
{
echo ("<br><br><div class='alert alert-danger'>Item already added.</div>");
}
}
else
{
$item_array = array(
'item_id' => $_GET["id"],
'item_name' => $_POST["hidden_name"],
'item_description' => $_POST["hidden_description"],
'item_code' => $_POST["hidden_code"],
'item_quantity' => $_POST["quantity"]);
$_SESSION["shopping_cart"][0] = $item_array;
}
}
if(isset($_GET["action"]))
{
if($_GET["action"] == "delete")
{
foreach($_SESSION["shopping_cart"] as $keys => $values)
{
if($values["item_id"] == $_GET["id"])
{
unset($_SESSION["shopping_cart"][$keys]);
echo ("<br><br><div class='alert alert-success'>Successfully Removed Item</div>");
}
}
}
}
?>
<br />
<h2>Order Details</h2>
<div class="table-responsive">
<table class="table table-bordered">
<tr>
<th width="35%">Item Name</th>
<th width="45%">Description</th>
<th width="18%">Code</th>
<th width="2%">Qty</th>
<th width="5%">Action</th>
</tr>
<?php
if(!empty($_SESSION["shopping_cart"]))
{
foreach($_SESSION["shopping_cart"] as $keys => $values)
{
?>
<tr>
<td><?php echo $values["item_name"]; ?></td>
<td><?php echo $values["item_description"]; ?></td>
<td><?php echo $values["item_code"]; ?></td>
<td><?php echo $values["item_quantity"]; ?></td>
<td><span class="text-danger">Remove</span></td>
</tr>
<?php
}
?>
<?php
}
?>
</table>
</div>
<td><button class="open-button" onclick="openForm()">Open Form</button></td>
</section>
<section>
<div class="form-popup" id="myForm">
<form method="post" action="cart.php">
<input type="text" name="name" placeholder="Name"><br><br>
<input type="text" name="mail" placeholder="Your e-mail"><br><br>
<input type="text" name="number" placeholder="Your contact number"><br><br>
<input type="text" name="subject" placeholder="Subject"><br><br>
<h2>Order Details</h2>
<?php
if(!empty($_SESSION["shopping_cart"]))
{
foreach($_SESSION["shopping_cart"] as $keys => $values)
{
?>
<tr>
<td>Item Name:<input type="text" name="productname" value="<?php echo $values["item_name"]; ?>"></td><br>
<td>Description:<input type="text" name="description" value="<?php echo $values["item_description"]; ?>"></td><br>
<td>Code:<input type="text" name="code" value="<?php echo $values["item_code"]; ?>"></td><br>
<td>Qty:<input type="text" name="qty" value="<?php echo $values["item_quantity"]; ?>"></td><br><br>
</tr>
<?php
}
?>
<?php
}
?>
<button class="button" type="submit" name="submit">SEND</button><br>
<?php
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$subject = $_POST['subject'];
$mailFrom = $_POST['mail'];
$number = $_POST['number'];
$product = $_POST['productname'];
$description = $_POST['description'];
$code = $_POST['code'];
$qty = $_POST['qty'];
$mailTo = "email#example.co.za";
$headers = "From: ".$mailFrom;
$txt = "You have received an e-mail from ".$name.".\n\n"."Email address: ".$mailFrom.".\n\n"."Contact number: ".$number.".\n\n"."Order Details:\n\n".$product.".\n\n"."Description:".$description.".\n\n"."Product Code:".$code.".\n\n"."Quantity Ordered:".$qty;
mail($mailTo, $subject, $txt, $headers);
header("Location: cart.php?mailsend");
}
?>
</form>
</div>
</section>
Your help would be greatly appreciated :)

The fault lies here:
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$subject = $_POST['subject'];
$mailFrom = $_POST['mail'];
$number = $_POST['number'];
$product = $_POST['productname'];
$description = $_POST['description'];
$code = $_POST['code'];
$qty = $_POST['qty'];
$mailTo = "email#example.co.za";
$headers = "From: " . $mailFrom;
$txt = "You have received an e-mail from " . $name . ".\n\n" . "Email address: " . $mailFrom . ".\n\n" . "Contact number: " . $number . ".\n\n" . "Order Details:\n\n" . $product . ".\n\n" . "Description:" . $description . ".\n\n" . "Product Code:" . $code . ".\n\n" . "Quantity Ordered:" . $qty;
mail($mailTo, $subject, $txt, $headers);
header("Location: cart.php?mailsend");
}
The $txt variable is responsible for the text in the Email and you are setting its value to the last order posted via the form. You have to concatenate every order. So, you have to do something like $txt .= "You...." Use the (.) operator to concatenate product details every time

Related

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.

Populate form field with specific data row from database table for updating PHP MYSQL

What i have is an event table list that shows a list of events for a team. beside each row is an edit button that when clicked brings you to an edit page where you can edit that selected event. however when i click the button i get nothing but a blank page. iv included the connection file and the index file
Index.php
<?php
require('model/connection.php');
require('model/functions.php');
if (isset($_POST['action'])) {
$action = $_POST['action'];
} else if (isset($_GET['action'])) {
$action = $_GET['action'];
} else {
$action = 'root_menu';
}
if ($action == 'root_menu') {
include('homePage.php');
} else if ($action == 'add_user') {
$email = $_POST['email'];
$password = $_POST['password'];
$last_name = $_POST['last_name'];
$first_name = $_POST['first_name'];
$country = $_POST['country'];
$city_town = $_POST['city_town'];
$user_type_id = $_POST['user_type_id'];
add_user($email, $password, $last_name, $first_name, $country, $city_town, $user_type_id);
$team_manager = get_users();
include('homePage.php');
} else if ($action == 'add_team') {
$name = $_POST['name'];
$sport = $_POST['sport'];
$country = $_POST['country'];
$city_town = $_POST['city_town'];
$age_profile = $_POST['age_profile'];
$user_id = $_POST['user_id'];
add_team($name, $sport, $country, $city_town, $age_profile, $user_id);
$team_manager = get_teams();
include('userPage.php');
} else if ($action == 'add_player') {
$last_name = $_POST['last_name'];
$first_name = $_POST['first_name'];
$dob = $_POST['dob'];
$position = $_POST['position'];
$email = $_POST['email'];
$country = $_POST['country'];
$city_town = $_POST['city_town'];
$password = $_POST['password'];
$team_id = $_POST['team_id'];
$user_type_id = $_POST['user_type_id'];
add_player($last_name, $first_name, $dob, $position, $email, $country, $city_town, $password, $team_id, $user_type_id);
$team_manager = get_players();
$from = "teammanager0#outlook.com"; // this is the web app's Email address
$subject = "Welcome to Team Manager";
$message = "You have been added to a team on our web app TEAM MANAGER!" . "\n\n" . "In order to login to your team please use
the following details: " . "\n\n" . "Email: " . $email . "\n\n" . "Password: " . $password;
$headers = "From:" . $from;
mail($email, $subject, $message, $headers);
header("location: http://localhost/TeamManager/teamPage.php?id=$team_id");
} else if ($action == 'add_event') {
$event_type = $_POST['event_type'];
$event_desc = $_POST['event_desc'];
$event_date = $_POST['event_date'];
$event_start = $_POST['event_start'];
$event_end = $_POST['event_end'];
$team_name = $_POST['team_name'];
$age_profile = $_POST['age_profile'];
$user_id = $_POST['user_id'];
$team_id = $_POST['team_id'];
add_event($event_type, $event_desc, $event_date, $event_start, $event_end, $team_name, $age_profile, $user_id, $team_id);
$team_manager = get_events();
header("location: http://localhost/TeamManager/teamPage.php?id=$team_id");
} else if ($action == 'delete_event') {
$event_id = $_POST['event_id'];
delete_event($event_id);
header("location: http://localhost/TeamManager/userPage.php");
} else if ($action == 'edit_event_form') {
$event_id = $_POST('event_id');
$event = get_event($event_id);
$event_type = $event['event_type'];
$event_desc = $event['event_desc'];
$event_date = $event['event_date'];
$event_start = $event['event_start'];
$event_end = $event['event_end'];
$team_name = $event['team_name'];
$age_profile = $event['age_profile'];
$user_id = $event['user_id'];
$team_id = $event['team_id'];
include('editEvent.php');
}
?>
connection.php
<?php
$mysql_hostname = "localhost";
$mysql_user = "brendan";
$mysql_password = "admin";
$mysql_database = "team_manager";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");
mysql_select_db($mysql_database, $bd) or die("Could not select database");
?>
eventPage.php
<?php
require_once('auth.php');
session_start();
if (trim($_SESSION['SESS_USER_TYPE']) == '2') {
header("location: playerPage.php");
exit();
}
require_once('model/connection.php');
require_once('model/deleteEvent.php');
$query = "SELECT * FROM events WHERE user_id = '" . $_SESSION['SESS_USER_ID'] . "'";
$team_manager = mysql_query($query) or die(mysql_error());
?>
<div id="sectionLeft">
<div class="eventsTable">
<h3>Events</h3>
<table>
<tr>
<td>Team Name</td>
<td>Event</td>
<td>Description</td>
<td>Date</td>
<td>Start Time</td>
<td>End Time</td>
</tr>
<?php while ($row = mysql_fetch_assoc($team_manager)) { ?>
<tr>
<td><?php echo $row['team_name']; ?> <?php echo $row['age_profile']; ?></td>
<td><?php echo $row['event_type']; ?></td>
<td><?php echo $row['event_desc']; ?></td>
<td><?php echo $row['event_date']; ?></td>
<td><?php echo $row['event_start']; ?></td>
<td><?php echo $row['event_end']; ?></td>
<td>
<form action="index.php" method="post" id="delete_event_button" name="form">
<input type="hidden" name="action" value="delete_event"/>
<input type="hidden" name="event_id"
value="<?php echo $row['event_id']; ?>" />
<input type="submit" value="Delete" />
</form>
</td>
<td>
<form action="index.php" method="post" id="edit_event_button" name="form">
<input type="hidden" name="action" value="edit_event_form"/>
<input type="hidden" name="event_id"
value="<?php echo $row['event_id']; ?>" />
<input type="submit" value="Edit" />
</form>
</td>
</tr>
<?php } ?>
</table>
</div>
<br /><br />
</div>
editEvent.php
<?php
require_once('auth.php');
session_start();
if (trim($_SESSION['SESS_USER_TYPE']) == '2') {
header("location: playerPage.php");
exit();
}
require_once('model/connection.php');
require_once('model/deleteEvent.php');
$query = "SELECT * FROM events WHERE user_id = '" . $_SESSION['SESS_USER_ID'] . "'";
$team_manager = mysql_query($query) or die(mysql_error());
?>
<div id="sectionLeft">
<div class="eventsTable">
<h3>Events</h3>
<table>
<tr>
<td>Team Name</td>
<td>Event</td>
<td>Description</td>
<td>Date</td>
<td>Start Time</td>
<td>End Time</td>
</tr>
<?php while ($row = mysql_fetch_assoc($team_manager)) { ?>
<tr>
<td><?php echo $row['team_name']; ?> <?php echo $row['age_profile']; ?></td>
<td><?php echo $row['event_type']; ?></td>
<td><?php echo $row['event_desc']; ?></td>
<td><?php echo $row['event_date']; ?></td>
<td><?php echo $row['event_start']; ?></td>
<td><?php echo $row['event_end']; ?></td>
<td>
<form action="index.php" method="post" id="delete_event_button" name="form">
<input type="hidden" name="action" value="delete_event"/>
<input type="hidden" name="event_id"
value="<?php echo $row['event_id']; ?>" />
<input type="submit" value="Delete" />
</form>
</td>
<td>
<form action="index.php" method="post" id="edit_event_button" name="form">
<input type="hidden" name="action" value="edit_event_form"/>
<input type="hidden" name="event_id"
value="<?php echo $row['event_id']; ?>" />
<input type="submit" value="Edit" />
</form>
</td>
</tr>
<?php } ?>
</table>
</div>
<br /><br />
</div>
get event function from functions.php
function get_event($event_id) {
global $bd;
$query = "SELECT * FROM events
WHERE event_id = '$event_id'";
$events = $bd->query($query);
$event = $events->fetch();
return $event;
}
line 77 wrong paranthesis -> $event_id = $_POST('event_id');
need square ones

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