How to post form data in mysql - php

At present I have set 4 variables, the values of which are then stored into mysql. This works fine. However, I don't want to set the values but write a line of code that takes these values from my form (on the same page). I have set the form method to POST and added specialchars to help security. Can someone pretty please show me one or two lines of code so I don't have to write ="John Doe". Please remember that I am very new all of this
<?php
// Connect to the Database
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "topsecretDontTell";
$dbname = "gaming";
$connection = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
// Show error if connection fails
if(mysqli_connect_errno()){
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() .")"
);
}
?>
<?php
// ordertbl
$customer_name = "John Doe";
$game_id = 3;
$reservation_start = "2015-01-05";
$requested_days = 1;
// removes single quotes (escapes strings)
$customer_name = mysqli_real_escape_string($connection, $customer_name);
//add into ordertbl
$query = "INSERT INTO ordertbl (customer_name,game_id,reservation_start,requested_days) VALUES ('{$customer_name}',{$game_id},'{$reservation_start}', {$requested_days})";
//Run query and test if there was a query error
$result = mysqli_query($connection, $query);
if (!$result) {
die("Database query failed.");
}
?>
<?php
//determine the name of the game via its id using a function
function GameTitle ($game_id){
$message = "";
if ($gameid ==1){
$message = "Fantasy World";
}
else if ($gameid ==2){
$message = "Sir Wags A Lot";
}
else if ($gameid ==3){
$message = "Take a Path";
}
else if ($gameid ==4){
$message = "River Clean Up";
}
else if ($gameid ==5){
$message = "PinBall";
}
else if ($gameid ==6){
$message = "Ghost girl";
}
else if ($gameid ==7){
$message = "Dress up";
}
else if ($gameid ==8){
$message = "Where is my hat?";
}
else {
$message = "Invalid ID";
}
return $message;
}
?>
</body>
</html>
<!--Link to the style sheet-->
<link href="styles.css" rel="stylesheet" type="text/css">
</head>
<!--Create Header (logo, title and navigation bar)-->
<body>
<div id='main'>
<div id='titleImage'><img title='Home' src='images/GLLogo.png' width='700' height='190' alt='Games Library Title' /></div>
<div id='menu-wrapper'>
<div id='menu'>
<ul>
<li><a href='index.html'>Home</a></li>
<li class='current_page_item'><a href='#'>Reservations</a></li>
</ul>
</div>
</div>
<!--Make the form-->
<div class="form">
<h1>Reservations</h1>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table width="755" border="3" cellpadding="6">
<tr>
<td width="195" align="right" bgcolor="#FF0000"><label for="customer_name">Name:</label></td>
<td width="370"><input name="customer_name" autofocus type="text" id="customer_name" size="35" maxlength="90" required autocomplete="off" /></td>
</tr>
<tr>
<td align="right" bgcolor="#FF0000"><label for="game_id">Game's ID:</label></td>
<td><input name="game_id" type="number" id="game_id" size="35" maxlength="50" min="1" /></td>
</tr>
<tr>
<td width="195" align="right" bgcolor="#FF0000"><button onClick="GameTitle(); return false">Search</button></td>
<td><input name="Result" type="text" id="demo" size="35" maxlength="50" /></td>
</tr>
<tr>
<td align="right" bgcolor="#FF0000"><label for="Loan">Number of Days you wish to borrow the Game</label></td>
<td><select name="requested_days" id="requested_days">
<option selected="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select></td>
</tr>
<tr> <!--put date into value field to get a calendar-->
<td align="right" bgcolor="#FF0000"><label for="reservation">Reservation Date:</label></td>
<td><input id="reservation_start" input name="reservation_start" type="" value="" placeholder="YYYY/MM/DD" pattern="(?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))" title="The date should be in the exact format: YYYY-MM-DD with leading zeros where necessary"/>
</tr>
<tr>
<td align="right" bgcolor="#FF0000"><label for="mysearch2">Enter your search string here : </label></td>
<td><input {background-colour: #E5F5EF;} id="mysearch2" type="search" placeholder="search"size="35" maxlength="50"/>
</tr>
<tr>
<td align="right" bgcolor="#FF0000"><input type="reset" name="Reset" id="button" value="Reset Form" /></td>
<td><input type="submit" name="button2" id="button2" value="Submit Form" /></td>
</tr>
</table>
</form>
</div>
</div>
</body>
</html>
<?php
// get rid of data in cache and close
mysqli_close($connection);
?>

Use the following, taking the POST variable from your form's <input name="customer_name"... element:
$customer_name=stripslashes($_POST['customer_name']);
$customer_name=mysqli_real_escape_string($connection,$_POST['customer_name']);
which will allow for names containing apostrophes like John O'Reilly.
Plus, you have function GameTitle ($game_id) therefore you most likely meant to use function GameTitle ($gameid)

You should use $_POST. In that array are post data. For example:
$customer_name = $_POST['name'];

Related

search page not displaying any results

please assist
I have created a search page to query the database, when the submit button is selected, no data is populated into the grid and there is no error message or notice that gives me an indication of where the issue is. Please assist.
Here is the code:
<?php
if(isset($_POST['submit']))
{
$txtLastName = $_POST['txtLastName'];
$txtidnumber = $_POST['txtidnumber'];
$txtMedicalAidNumber = $_POST['txtMedicalAidNumber'];
//connect to the database
$db = mysql_connect
("server", "username", "password") or die ('I cannot connect to the database because: ' . mysql_error());
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$mydb = mysql_select_db("mediouqp_login");
if($txtLastName != '' && $txtidnumber != '' && $txtMedicalAidNumber != '')
{
$sql = "SELECT last_name, id_number, medical_id_number FROM patient WHERE last_name LIKE '%" . $txtLastName . "%' OR id_number LIKE '%" . $txtidnumber ."%'";
}
else
{
$sql = "SELECT last_name FROM patient ORDER BY last_name DESC";
}
$result = mysql_query($sql);
}
if($result)
{
if(mysql_num_rows($result) > 0)
{
echo 'Total records found are- '.mysql_num_rows($result);
}
else
{
echo "No records found.";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style2.css">
</head>
<body>
<ul>
<li>PATIENT DETAILS
<li>REPORTS</li>
<li>ADMINISTRATOR</li>
<li>DOWNLOADS</li>
</ul>
<div class="headerTitle">
<h1 id="mainHeader">search patient details</h1>
</div>
<form action="search_patient.php" method="post" name="frm_search" id="frm_search">
<table>
<tr>
<td class="Label" id="lname">Last Name
</td>
<td class="Field">
<input type ="lastname" name ="txtLastName" ></input>
<span id="spnLastName"></span>
</td>
</tr>
<tr>
<td class="Label" id="lname">ID Number
</td>
<td class="Field">
<input type ="lastname" name ="txtidnumber" ></input>
<span id="spnIdNumber"></span>
</td>
</tr>
<tr>
<td class="Label" id="lname">Medical Aid Number
</td>
<td class="Field">
<input type ="medicalaidnumber" name ="txtMedicalAidNumber" ></input>
<span id="spnMedicalaidNumber"></span>
</td>
</tr>
<tr>
<td class="Label">
</td>
<td>
<input type="submit" id="btnSearchPatient" value="Submit"></input>
<input type = "button" onClick="window.location='create_patient.php';" value="Create Patient" /></input>
</td>
</tr>
</table>
</form>
<br/>
<br/>
<table id="tblpatient" class="Grid">
<tr class="Header">
<td> </td>
<td> </td>
<td> </td>
<td>Last Name</td>
<td>ID Number</td>
<td>Medical Aid</td>
</tr>
<?php
if($result)
{
while($row = mysql_fetch_array($result))
{
$last_name = $row['last_name'];
$id_number = $row['id_number'];
$medical_id_number = 0;//$row['medical_id_number'];
?>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td><?php echo $last_name;?></td>
<td><?php echo $id_number;?></td>
<td><?php echo $medical_id_number;?></td>
</tr>
<?php
}
}
?>
</table>
</body>
</html>
Note: This extension(mysql) was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used along with prepared statements.
As per the code you have written it will be submitting the data but what you have written under this statement will never Work.
if(isset($_POST['submit'])){// Codes Inside this}
Reason this code will not work
Your Submit button is not having the name which you have given in the isset($_POST['submit']).
You mist add the name to the submit button which you have in your code.
Replace your Submit button as i have provided by adding the name to it and changing the button code style.
Replace:
<input type="submit" id="btnSearchPatient" value="Submit"></input>
With:
<input type="submit" id="btnSearchPatient" name="submit" value="Submit" />
After all the above steps that has been provided ensure the note below in order the data comes as not expected.
Note: If you need to execute the statement perfect you first put echo to the select statement that you have coded and break the execution over there. You will find the SQL statement over to the browser and you copy that echoed statement into the SQL section of the DB created in the Phpmyadmin and check whether your code executed well. If so you got the required output that you can remove the echo and exit statement and you can proceed.

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

Cannot read my attributes in database

<?php
header("Content-type: text/html; charset=utf-8");
require('db_connect.php');
mysql_query("SET NAMES 'utf8'");
$food_name = $_POST['food_name'];
$restaurant_name = $_POST['restaurant_name'];
$food_type = $_POST['food_type'];
$food_price = $_POST['food_price'];
$food_description = $_POST['food_description'];
$uploadfile;
$dest_folder = "picture/";
$arr = array();
$count = 0;
if(!file_exists($dest_folder)){
mkdir($dest_folder);
}
foreach($_FILES["pictures"]["error"] as $key=> $error){
if($error == UPLOAD_ERR_OK){
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
$name = $_FILES["pictures"]["name"][$key];
$uploadfile = $dest_folder.$name;
move_uploaded_file($tmp_name,$uploadfile);
$arr[$count] = $uploadfile;
$count++;
}
}
$s2 = implode(',',$arr);
$sql = "insert into foodmenu
(food_name,restaurant_name,food_type,food_price,food_description,food_img)
values
('$food_name','$restaurant_name','$food_type','$food_price','$food_description','$s2',now())";
$result = mysql_query($sql);
if($result){
echo"<script>alert('Success')</script>";
echo"<script>location.href='admin.php'</script>";
} else {
echo"<script>alert('Failure')</script>";
echo"<script>history.back();</script>";
}
?>
May I know what is the error?
Because it cannot read my $food_name till $food_description.....and foreach($_FILES["pictures"]["error"] as &key=>$error).....
Can provide any solution for it?
<form action="add_action.php" method="post" name="send" onSubmit="return Check()" enctype="multipart/form-data">
Food Name :
Food Description :
Food Price :
$
Food Type :
---
appertizers
main courses
desserts
Restaurant Name :
Images :
<input name="btnSubmit" type="submit" class="inputButton" id="btnSubmit" value=" ADD " align="middle">
</form>
<div class="listbox">
<div class="menu">
<br><br>
<form action="add_action.php" method="post" name="send" onSubmit="return Check()" enctype="multipart/form-data">
<table border="0" cellpadding="2" cellspacing="0" width="100%">
<tr>
<td width="180" align="right">Food Name :</td>
<td width="150">
<input name="food_name" type="text" class="food_namelist" style="width:300px;">
</td>
</tr>
<tr>
<td width="100" align="right">Food Description :</td>
<td width="222">
<textarea name="food_description" class="food_namelist" rows="3" style="height:100px; width:500px;"></textarea>
</td>
</tr>
<tr>
<td width="100" align="right">Food Price :</td>
<td width="222">
$
<tr>
<td width="100" align="right">Food Type :</td>
<td width="222">
<select name="food_type">
<option value="" selected>---</option>
<option value="appertizers">appertizers</option>
<option value="main courses">main courses</option>
<option value="desserts">desserts</option>
</select>
</td>
</tr>
<tr>
<td width="180" align="right">Restaurant Name :</td>
<td width="222">
<input name="restaurant_name" type="text" class="food_namelist" style="width:300px;">
</td>
</tr>
<tr>
<td align="right">Images :</td>
<td style=" ">
<input type="uploadfile" name="pictures[]" />
</td>
</tr>
</table>
<input name="btnSubmit" type="submit" class="inputButton" id="btnSubmit" value=" ADD " align="middle">
</form>
</div>
</div>
There's lot of things that may happen wrong in your form.
First one is, It is possible that your form input name and your &_POST['xyz'] names are not matching.
Second one is, Please never forget to wrap your post values in htmlspecialchars like $food_name = htmlspecialchars($_POST['food_name']);
Neither your values are thrown for injection threats.
So after two above mentioned modifications, if you still face the problem, please attach your form html.
i'm excluding your db_connect.php. Please edit the details as your own.
sql code::'
<?php
define("DB_DSN","mysql:hostname=localhost;dbname=tumy");
define("DB_USR","root");
define("DB_PASS","");
$conn = new PDO(DB_DSN,DB_USR,DB_PASS);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$food_name = htmlspecialchars($_POST['food_name']);
$restaurant_name = htmlspecialchars($_POST['restaurant_name']);
$food_type = htmlspecialchars($_POST['food_type']);
$food_price = htmlspecialchars($_POST['food_price']);
$food_description = htmlspecialchars($_POST['food_description']);
$date = now();//create a column in your database named "date(or as wish)
$dest_folder = "picture/";
$arr = array();
$count = 0;
if(!file_exists($dest_folder)){
mkdir($dest_folder);
}
foreach($_FILES["pictures"]["error"] as $key=> $error){
if($error == UPLOAD_ERR_OK){
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
$name = $_FILES["pictures"]["name"][$key];
$uploadfile = $dest_folder.$name;
move_uploaded_file($tmp_name,$uploadfile);
$arr[$count] = $uploadfile;
$count++;
}
}
$s2 = implode(',',$arr);
$sql = "INSERT INTO foodmenu
(food_name,restaurant_name,food_type,food_price,food_description,food_img,date)
VALUES
('$food_name','$restaurant_name','$food_type','$food_price','$food_description','$s2','$date')";
$st = $conn->prepare($sql);
if($st->execute()){
echo"<script>alert('Success')</script>";
echo"<script>location.href='admin.php'</script>";
} else {
echo"<script>alert('Failure')</script>";
echo"<script>history.back();</script>";
}
$conn = null;
?>`

Form is not inserting entered data in the database, but doesn't show any errors

guys, I hope someone can help me find the problem in this code that is keeping it from inserting the entered data in the database.
I have seen similar threads around here, I corrected one or two things and still it doesn't seem to work, that's why I created this post.
Also, this code worked flawlessly when it had only three form fields/variables. Now that I have created a few more, it wont send any submitted values to the database.
If anyone should ask, the function that shows the result in the same page is working fine, since I have tried inserting values in the database manually and they show in the file, what leads me to think that the problem is really with the insert function.
Can anyone help me find why it's not going?
<?php
mysql_connect("localhost","root","");
mysql_select_db("activitytest1");
if(isset($_POST['type'])) { $type = $_POST['type']; }
if(isset($_POST['description'])){ $description = $_POST['description']; }
if(isset($_POST['author'])) { $author = $_POST['author']; }
if(isset($_POST['pre'])) { $pre = $_POST['pre']; }
if(isset($_POST['while'])) { $while = $_POST['while']; }
if(isset($_POST['postact'])) { $postact = $_POST['postact']; }
if(isset($_POST['outcome'])) { $outcome = $_POST['outcome']; }
if(isset($_POST['path'])) { $path = $_POST['path']; }
if(isset($_POST['books'])) { $books = $_POST['books']; }
if(isset($_POST['grouping'])) { $grouping = $_POST['grouping']; }
if(isset($_POST['time'])) { $time = $_POST['time']; }
if(isset($_POST['submit'])) { $submit = $_POST['submit']; }
$dbLink = mysql_connect("localhost", "root", "");
mysql_query("SET character_set_client=utf8", $dbLink);
mysql_query("SET character_set_connection=utf8", $dbLink);
if (!empty($_POST['submit']))
{
if($type&&$description&&$author&&$pre&&$while&&$postact&&$outcome&&$path&&$books&&$grouping&&$time) {
$insert=mysql_query("INSERT INTO activitytest1 (type, description, author, pre, while, postact, outcome, path, books, grouping, time) VALUES ('".$_POST['type']."','".$_POST['description']."','".$_POST['author']."','".$_POST['pre']."', '".$_POST['while']."','".$_POST['postact']."','".$_POST['outcome']."','".$_POST['path']."', '".$_POST['books']."','".$_POST['grouping']."','".$_POST['time']."',)");
} else {
die ("Failed to connect to mysql: " . mysql_error());
}
}
$dbLink = mysql_connect("localhost", "root", "");
mysql_query("SET character_set_results=utf8", $dbLink);
mb_language('uni');
mb_internal_encoding('UTF-8');
$getquery=mysql_query("SELECT * FROM activitytest1");
while($rows=mysql_fetch_assoc($getquery))
{
$type=$rows['type'];
$description=$rows['description'];
$author=$rows['author'];
$pre=$rows['pre'];
$while=$rows['while'];
$postact=$rows['postact'];
$outcome=$rows['outcome'];
$path=$rows['path'];
$books=$rows['books'];
$grouping=$rows['grouping'];
$time=$rows['time'];
echo '<br/>
<table width="909" border="1" align="center" cellpadding="5" cellspacing="0">
<tr>
<td width="125">' . $type . '</th>
<td width="680">' . $description . '</th>
<td width="120">' . $author . '</th>
</tr></table> <br/>' . $pre . '<br/>' . $while. '<br/>' . $postact . '<br/>' . $outcome . '<br/>' . $path . '<br/>' . $books . '<br/>' . $grouping . '<br/>' . $time . '
<hr size="1"/> ' ;}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test 1</title>
</head>
<body>
<br>
<table width="909" border="1" align="center" cellpadding="5" cellspacing="0">
<tr>
<th width="125" scope="col">Type</th>
<th width="680" scope="col">Description</th>
<th width="120" scope="col">Author</th>
</tr></table>
<br>
<form action="index.php" method="POST">
<table width="909" border="1" align="center" cellpadding="5" cellspacing="0">
<td width="125"><label>
</label>
<select name="type" id="type" onChange="display(this,'Task','Semi-task','Practice','Exercise','Lead-in');">
<option value="Unselected" selected="selected">Choose one:</option>
<option value="Task">Task</option>
<option value="Semi-task">Semi-task</option>
<option value="Practice">Practice</option>
<option value="Exercise">Exercise</option>
<option value="Lead-in">Lead-in</option>
<option value="Game">Game</option>
<option value="Video">Video</option>
<option value="Song">Song</option>
<option value="Mimio">Mimio</option>
<option value="Other">Other</option>
</select></td>
<td width="680"><div id="Semi-task" style="display: none;">
Pre:<br>
</div>
<div id="Exercise" style="display: none;">While:</div>
<br>
<div id="Practice" style="display: none;">
Post:<br>
<br>
</div>
<div id="Task" style="display: none;"> Outcome: <br />
<textarea name="description" cols="70" rows="2"></textarea>
<br />
</div>
<div id="Lead-in" style="display: none;">
Link/Path:<br>
<br>
</div></td>
<td width="120"><input name="author" type="text" size="12" maxlength="25" /></td>
</tr>
<tr>
<td colspan="3"> <textarea name="pre" id="Pre" cols="45" rows="5"></textarea>
<br /><textarea name="while" id="While" cols="45" rows="5"></textarea>
<br /><textarea name="postact" id="Post" cols="45" rows="5"></textarea>
<br /><textarea name="outcome" id="Outcome" cols="45" rows="5"></textarea>
<br /><input type="text" name="path" id="Path" />
<br /><input type="text" name="books" id="Books" />
<br /><input type="text" name="grouping" id="Grouping" />
<br /><input type="text" name="time" id="Time" />
</td>
</tr>
<tr>
<td colspan="3"><input type="submit" name="submit" value="Comment" /></td>
</tr>
</table>
</form>
</body>
</html>
Please be nice, guys, I am a total newbie at this. :)
You have an extra comma at the end of the mySQL code.
Try this: $insert=mysql_query("INSERT INTO activitytest1 (type, description, author, pre, while, postact, outcome, path, books, grouping, time) VALUES ('".$_POST['type']."','".$_POST['description']."','".$_POST['author']."','".$_POST['pre']."', '".$_POST['while']."','".$_POST['postact']."','".$_POST['outcome']."','".$_POST['path']."', '".$_POST['books']."','".$_POST['grouping']."','".$_POST['time']."')");
First check the data you are passing is valid. Your $_POST['description'] field is empty so pointer is not coming inside mysql_query() function.
Another think i saw in your code you have display : none; a div which has $_POST['description'] element. Remove that display : none OR remove the validation part for that element.

how to get value from the database

i want to get value from database..for exmaple,in the name field, it show the name that stored in the database. i want to show the value in the respective field.but it cannot retrieve the value..plz guys..help me
<?php
session_start();
$username = $_SESSION["username"];
$department = $_SESSION["department"];
?>
<html>
<head>
<title>Change Password</title>
</head>
<form method="post" action="changepassprocess.php">
<?php
$db = mysql_connect('localhost','root')
or die ("unable to connect");
mysql_select_db('fyp',$db) or die ("able to select");
$sql_select = "SELECT * FROM access WHERE username ='".$username."' ";
?>
<font face= "arial" size="2" font color="black">
<center>
<h3 align=center> Change Password </h3>
<table width="500" height="100" border="0" cellspacing="0" cellpadding="2">
<tr>
<tr>
<td align="left">User ID</td>
<td>: <input name="username" type="text" id="username" value="<? {echo "$username"; } ?>" size="20" maxlength="10" readonly='username'></td>
</tr>
<tr>
<td align="left">Name </td>
<td>: <input name="name" type="text" id="name" value="<? {echo "$name"; } ?>" size="50" readonly="name"></td>
</tr>
<tr>
<td align="left">Department </td>
<td>: <?php echo $row['department']; ?> </td>
</tr>
<tr>
<td align="left">New Password </td>
<td>:<input name="newpassword" type="password" id="newpassword" size="20" ></td>
</tr>
</table><br>
<align = center><input type="submit" name="send" value="Change Password">
</form>
</body>
</html>
Well, you forgot to run your query to the database. The $sql_select variable holds the query text, but you need to pass it to the database and retrieve the answer from it. Read http://php.net/manual/en/function.mysql-query.php and examples there.
You are missing:
$result = mysql_query($sql_select);
$row = mysql_fetch_array($result);
These will execute the query you've prepared and get the results as an array $row.
You might want to see how get fetch a value from Mysql DB using php from:
W3school: Select Data From a Database Table.
<?php
session_start();
include("../connect.php");
$user=$_SESSION['user'];
if(empty($user))
{
header("location:index.php");
}
else{
$query_display="SELECT * FROM user_login WHERE user_id_no='$user_id_no'";
$result=mysqli_query($bd,$query_display);
while($arr=mysqli_fetch_array($result))
{
$first_name=$arr['first_name'];
$last_name=$arr['last_name'];
$address=$arr['address'];
}
echo $first_name;
echo $last_name;
echo $address;
}
?>
connect.php
<?php
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password = "";
$mysql_database = "";
$bd=mysqli_connect($mysql_hostname,$mysql_user,$mysql_password,$mysql_database);
?>

Categories