PHP SQL Insert text value into database - php

I am working on an online shopping cart project, which requires me to be able to add a custom text input field to each item that is added to the shopping cart. However, when I attempt to insert the information for each item in the card into a database, I cannot figure out how to pass the itemtext value into my INSERT statement. How would I go about being able to pass the itemtext value from the initial item list into my database for Orderitems? The itemtext input is on line 170, and I want to pass it into the INSERT statement seen on line 83.
<?php
session_start();
$user = $_SESSION['user'];
if(!isset($user)) {
header("Location:userlogin.php");
}
$cart = $_COOKIE['WSC'];
if(isset($_POST['clear'])) {
$expire = time() -60*60*24*7*365;
setcookie("WSC", $cart, $expire);
header("Location:order.php");
}
if($cart && $_GET['id']) {
$cart .= ',' . $_GET['id'];
$expire = time() +60*60*24*7*365;
setcookie("WSC", $cart, $expire);
header("Location:order.php");
}
if(!$cart && $_GET['id']) {
$cart = $_GET['id'];
$expire = time() +60*60*24*7*365;
setcookie("WSC", $cart, $expire);
header("Location:order.php");
}
if($cart && $_GET['remove_id']) {
$removed_item = $_GET['remove_id'];
$arr = explode(",", $cart);
unset($arr[$removed_item-1]);
$new_cart = implode(",", $arr);
$new_cart = rtrim($new_cart, ",");
$expire = time() +60*60*24*7*365;
setcookie("WSC", $new_cart, $expire);
header("Location:order.php");
}
if(isset($_POST['PlaceOrder'])) {
$email = $user;
$orderdate = date('m/d/Y');
$ordercost = $_POST['ordercost'];
$ordertype = $_POST['ordertype'];
$downcost = $_POST['downcost'];
$cardtype = $_POST['cardtype'];
$cardnumber = $_POST['cardnumber'];
$cardsec = $_POST['cardsec'];
$cardexpdate = $_POST['cardexpdate'];
$orderstatus = "Pending";
if($ordertype=="") {
$ordertypeMsg = "<br><span style='color:red;'>You must enter an order type.</span>";
}
if($cardtype=="") {
$cardtypeMsg = "<br><span style='color:red;'>You must enter a card type.</span>";
}
if($cardnumber=="") {
$cardnumberMsg = "<br><span style='color:red;'>You must enter a card number.</span>";
}
if($cardsec=="") {
$cardsecMsg = "<br><span style='color:red;'>You must enter a security code.</span>";
}
if($cardexpdate=="") {
$cardexpdateMsg = "<br><span style='color:red;'>You must enter an expiration date.</span>";
}
else {
include ('includes/dbc_admin.php');
$sql = "INSERT INTO Orders (email, orderdate, ordercost, ordertype, downcost, cardtype, cardnumber, cardsec, cardexpdate, orderstatus)
VALUES ('$email', '$orderdate', '$ordercost', '$ordertype', '$downcost', '$cardtype', '$cardnumber', '$cardsec', '$cardexpdate', '$orderstatus')";
mysql_query($sql) or trigger_error("WHOA! ".mysql_error());
$sql = "SELECT orderid FROM Orders";
$result = mysql_query($sql) or die("Invalid query: " . mysql_error());
while($row=mysql_fetch_assoc($result)) {
$myid = $row[orderid];
}
$itemnumber = 1;
$items = explode(',', $cart);
foreach($items AS $item) {
$sql = "SELECT * FROM Catalog where id = '$item'";
$result = mysql_query($sql) or die("Invalid query: " . mysql_error());
while($row=mysql_fetch_assoc($result)) {
$itemtext = $_POST['itemtext'];
$sql= "INSERT INTO OrderItems (orderid, itemnumber, itemid, itemtype, media, itemtext, price)
VALUE ('$myid', '$itemnumber', '$row[itemid]', '$row[itemtype]', '$row[media]', '$itemtext[itemnumber]', '$row[price]')";
mysql_query($sql) or trigger_error("WHOA! ".mysql_error());
}
$itemnumber++;
}
$inserted = "<h2>Thank You!</h2> <h3>Your order has been placed.</h3>";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Williams Specialty Company</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function validateForm() {
var ordercost = document.form1.ordercost.value;
var downcost = document.form1.downcost.value;
var ordertype = document.form1.ordertype.value;
var cardtype = document.form1.cardtype.value;
var cardnumber = document.form1.cardnumber.value;
var cardsec = document.form1.cardsec.value;
var cardexpdate = document.form1.cardexpdate.value;
var ordertypeMsg = document.getElementById('ordertypeMsg');
var cardtypeMsg = document.getElementById('cardtypeMsg');
var cardnumberMsg = document.getElementById('cardnumberMsg');
var cardsecMsg = document.getElementById('cardsecMsg');
var cardexpdateMsg = document.getElementById('cardexpdateMsg');
if(ordertype == ""){ordertypeMsg.innerHTML = "You must enter an order type."; return false;}
if(cardtype == ""){cardtypeMsg.innerHTML = "You must enter a card type."; return false;}
if(cardnumber == ""){cardnumberMsg.innerHTML = "You must enter a card number."; return false;}
if(cardsec == ""){cardsecMsg.innerHTML = "You must enter a security code."; return false;}
if(cardexpdate == ""){cardexpdateMsg.innerHTML = "You must enter an expiration date."; return false;}
}
</script>
</head>
<body>
<?php include('includes/header.inc'); ?>
<?php include('includes/nav.inc'); ?>
<div id="wrapper">
<?php include('includes/aside.inc'); ?>
<section>
<h2>My Cart</h2>
<table width="100%">
<tr>
<th>Catalog ID</th>
<th>Item Name</th>
<th>Price</th>
<th>Item Text</th>
<th>Actions</th>
</tr>
<?php
$cart = $_COOKIE['WSC'];
if ($cart) {
$i = 1;
$ordercost;
include('includes/dbc.php');
$items = explode(',', $cart);
foreach($items AS $item) {
$sql = "SELECT * FROM Catalog where id = '$item'";
$result = mysql_query($sql) or die("Invalid query: " . mysql_error());
while($row=mysql_fetch_assoc($result)) {
echo '<tr>';
echo '<td align="left">';
echo $row['itemid'];
echo '</td>';
echo '<td align="left">';
echo $row['itemname'];
echo '</td>';
echo '<td align="left">';
echo $row['price'];
$ordercost+=$row['price'];
$downcost = $ordercost / 10;
echo '</td>';
echo '<td align="left">';
echo '<p><input type="text" id= "itemtext" name="itemtext"></p>';
echo '</td>';
echo '<td align="left">';
echo 'Remove From Cart';
echo '</td>';
echo '</tr>';
}
$i++;
}
}
?>
</table><br />
<form method="POST" action="<?php $_SERVER['PHP_SELF'];?>">
<input type="submit" name="clear" value="Empty Shopping Cart">
</form>
<?php if(isset($inserted)) {echo $inserted;} else{ ?>
<form method="post" action="<?php echo $SERVER['PHP_SELF'] ?>" name="form1" onSubmit="return validateForm()">
<p>Total Price: <?php echo $ordercost;?> <input type="hidden" id="ordercost" name="ordercost" value="<?php echo $ordercost;?>"> </p>
<p>Down Cost: <?php echo number_format((float)$downcost, 2, '.', '');?> <input type="hidden" id="downcost" name="downcost" value="<?php echo number_format((float)$downcost, 2, '.', '');?>"> </p>
<p><label>Order Type:</label><br> <input type="text" id="ordertype" name="ordertype">
<?php if(isset($ordertypeMsg)) {echo $ordertypeMsg;} ?>
<br /><span id="ordertypeMsg" style="color:red"></span>
</p>
<p><label>Card Type:</label><br> <input type="text" id="cardtype" name="cardtype">
<?php if(isset($cardtypeMsg)) {echo $cardtypeMsg;} ?>
<br /><span id="cardtypeMsg" style="color:red"></span>
</p>
<p><label>Card Number:</label><br> <input type="text" id="cardnumber" name="cardnumber">
<?php if(isset($cardnumberMsg)) {echo $cardnumberMsg;} ?>
<br /><span id="cardnumberMsg" style="color:red"></span>
</p>
<p><label>Card Security Code:</label><br> <input type="text" id="cardsec" name="cardsec">
<?php if(isset($cardsecMsg)) {echo $cardsecMsg;} ?>
<br /><span id="cardsecMsg" style="color:red"></span>
</p>
<p><label>Card Expiration Date:</label><br> <input type="text" id="cardexpdate" name="cardexpdate">
<?php if(isset($cardexpdateMsg)) {echo $cardexpdateMsg;} ?>
<br /><span id="cardexpdateMsg" style="color:red"></span>
</p>
<p><input type="submit" name="PlaceOrder" value="Place Order"></p>
</form><?php }?>
</section>
</div>
<?php include('includes/footer.inc'); ?>
</body>
</html>

Update: This is your answer: change '$itemtext[itemnumber]' into '$itemtext'
This is going wrong because of the way you use quotes. (not the answer but you might want to think about it ;-) )
$sql = "INSERT INTO Orders (email, orderdate, ordercost, ordertype, downcost, cardtype, cardnumber, cardsec, cardexpdate, orderstatus)
VALUES ('$email', '$orderdate', '$ordercost', '$ordertype', '$downcost', '$cardtype', '$cardnumber', '$cardsec', '$cardexpdate', '$orderstatus')";
You should not use '$email' but -for example- ...VALUES ('".$email."',...
Learn more about this here: What is the difference between single-quoted and double-quoted strings in PHP?
On another note, your code is not safe. Please use: http://php.net/manual/en/function.mysql-real-escape-string.php
Example:
...VALUES ('".mysql_real_escape_string($email)."',...

Related

How to show comments on specific posts

I have an application that where users can post announcements and comment on posts. My problem is that whenever a comment is posted, It shows up on every announcement post. How can I post comments so that they show up on that specific post?
I have 2 database tables: "announcement: id, name, announcementTitle, announcement, image" and "comment: id, post_id, name, comment" with foreign key attached to comment.
Here is my home.php where the announcements and comments are echoed
<div class="container">
<div class="mx-auto">
<?php
if (isset($_SESSION['username'])) {
echo'
<h1 style="text-decoration:underline">Post an announcement</h1>
<form method="post" action="announcement.php" enctype="multipart/form-data">
<input type="text" name="announcementTitle" placeholder="Enter Subject"><br>
<textarea name="announcementBox" rows="5" cols="40" placeholder="Enter Announcement"></textarea><br>
<input type="file" name="image" accept="image/jpeg">
<button name="announcement">Submit</button>
</form>';
}
$query = "SELECT * FROM announcement ORDER BY id DESC";
$result = mysqli_query($con,$query);
while ($row = mysqli_fetch_array($result)) {
echo '<div class="row" style="color:black;background-color:white;border-radius:5px;padding:10px;margin-top:10px;margin-bottom:70px">';
echo '<div class="column" style="width:100%;border:5px">';
if (isset($_SESSION['username'])) {
echo '<form method="post" action="announcement.php">';
echo "Posted by " .$row["name"]. " click X to delete:";
echo '<input type="hidden" name="postID" value="'.$row['id'].'">';
echo '<button name="delete" style="float:right">X</button>';
echo '</form>';
}
echo $row['announcementTitle'].'<br>';
echo $row['announcement'].'<br>';
echo '<img width="20%" src="data:image;base64,'.$row['image'].'"alt="Image" style="padding-top:10px">';
echo'
<form method="post" action="comment.php">
<textarea name="commentbox" rows="2" cols="50" placeholder="Leave a Comment"></textarea><br>
<button name="comment">Submit</button>
</form>';
echo "Comments:<p><p>";
echo " <p>";
$find_comment = "SELECT * FROM comment ORDER BY id DESC";
$res = mysqli_query($con,$find_comment);
while ($row = mysqli_fetch_array($res)) {
echo '<input type="hidden" name="postID" value="'.$row['post_id'].'">';
$comment_name = $row['name'];
$comment = $row['comment'];
echo "$comment_name: $comment<p>";
}
if(isset($_GET['error'])) {
echo "<p>100 Character Limit";
}
echo '</div></div>';
}
?>
</div>
</div>
Here is comment.php where comments are put in the database
<?php
session_start();
$con = mysqli_connect('localhost', 'root', 'Arv5n321');
mysqli_select_db($con, 'userregistration');
$namee = '';
$comment = '';
$comment_length = strlen($comment);
if($comment_length > 100) {
header("location: home.php?error=1");
}else {
$que = "SELECT * FROM announcement";
$res = mysqli_query($con,$que);
while ($row = mysqli_fetch_array($res)) {
$post_id = $row['id'];
}
$namee = $_SESSION['username'];
$comment = $_POST['commentbox'];
$query = "INSERT INTO comment(post_id,name,comment) VALUES('$post_id','$namee','$comment')";
$result = mysqli_query($con, $query);
if ($result) {
header("location:home.php?success=submitted");
} else {
header("location:home.php?error=couldnotsubmit");
}
}
?>
Here is announcement.php where announcements are put in the database
<?php
session_start();
//$con = mysqli_connect('freedb.tech', 'freedbtech_arvindra', 'Arv5n321', 'freedbtech_remote') or die(mysqli_error($con));
$con = mysqli_connect('localhost', 'root', 'Arv5n321', 'userregistration') or die(mysqli_error($con));
if (isset($_POST['announcement'])) {
$image = $_FILES['image']['tmp_name'];
$name = $_FILES['image']['name'];
$image = base64_encode(file_get_contents(addslashes($image)));
date_default_timezone_set("America/New_York");
$title = $_POST['announcementTitle']." (<b>".date("m/d/Y")." ".date("h:i:sa")."</b>)";
$paragraph = $_POST['announcementBox'];
if (empty($paragraph)||empty($title)) {
header('location:home.php?error=fillintheblanks');
}else{
$nam = $_SESSION['username'];
$query = "insert into announcement(name,announcementTitle,announcement,image) values('$nam','$title','$paragraph','$image')";
$result = mysqli_query($con, $query);
if ($result) {
header("location:home.php?success=submitted");
} else {
header("location:home.php?error=couldnotsubmit");
}
}
}else if (isset($_POST['delete'])){
$query = "delete from announcement where id='".$_POST['postID']."';";
$result = mysqli_query($con,$query);
if ($result) {
header('location:home.php?success=deleted');
} else {
header('location:home.php?error=couldnotdelete');
}
}
else {
header('location:home.php');
}
I am a little new to PHP so any help is good.

Not Able to save data to Mysql database

I am developing a simple attendance system in which the attendance is taken by the a teacher and then saved to the database. However, I am having a problem with saving the data to the database. when i click on "submit attendance" the data won't be submitted to the database. i use register.php to register students but take the attendance in different file.
Below is the code i use to submit. Can someone help me? Thanks.
sorry the file i shared was supposed to save data to mysql database. Below is the file which takes the data and am still having the problem for saving it.
this is the teacher file to take the attendance
teacher.php
<?php
$pageTitle = 'Take Attendance';
include('header.php');
require("db-connect.php");
if(!(isset($_COOKIE['teacher']) && $_COOKIE['teacher']==1)){
echo 'Only teachers can create new teachers and students.';
$conn->close();
include('footer.php');
exit;
}
//get session count
$query = "SELECT * FROM attendance";
$result = $conn->query($query);
$sessionCount=0;
setcookie('sessionCount', ++$sessionCount);
if(mysqli_num_rows($result)>0){
while($row = $result->fetch_assoc()){
$sessionCount = $row['session'];
setcookie('sessionCount', ++$sessionCount);
}
}
if(isset($_GET['class']) && !empty($_GET['class'])){
$whichClass = $_GET['class'];
$whichClassSQL = "AND class='" . $_GET['class'] . "'";
} else {
$whichClass = '';
$whichClassSQL = 'ORDER BY class';
}
echo '
<div class="row">
<div class="col-md-4">
<div class="input-group">
<input type="number" id="session" name="sessionVal" class="form-control" placeholder="Session Value i.e 1" required>
<span class="input-group-btn">
<input id="submitAttendance" type="button" class="btn btn-success" value="Submit Attendance" name="submitAttendance">
</span>
</div>
</div>
<div class="col-md-8">
<form method="get" action="' . $_SERVER['PHP_SELF'] . '" class="col-md-4">
<select name="class" id="class" class="form-control" onchange="if (this.value) window.location.href=this.value">
';
// Generate list of classes.
$query = "SELECT DISTINCT class FROM user ORDER BY class;";
$classes = $classes = mysqli_query($conn, $query);
if($classes && mysqli_num_rows($classes)){
// Get list of available classes.
echo ' <option value="">Filter: Select a class</option>';
echo ' <option value="?class=">All classes</option>';
while($class = $classes->fetch_assoc()){
echo ' <option value="?class=' . $class['class'] . '">' . $class['class'] . '</option>';
}
} else {
echo ' <option value="?class=" disabled>No classes defined.</option>';
}
echo '
</select>
</form>
</div>
</div>
';
$query = "SELECT * FROM user WHERE role='student' $whichClassSQL;";
$result = $conn->query($query);
?>
<table class="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Class</th>
<th>Present</th>
<th>Absent</th>
</tr>
</thead>
<tbody>
<form method="post" action="save-attendance.php" id="attendanceForm">
<?php
if(mysqli_num_rows($result) > 0){
$i=0;
while($row = $result->fetch_assoc()){
?>
<tr>
<td><input type="hidden" value="<?php echo($row['id']);?>" form="attendanceForm"><input type="text" readonly="readonly" name="name[<?php echo $i; ?>]" value="<?php echo $row['fullname'];?>" form="attendanceForm"></td>
<td><input type="text" readonly="readonly" name="email[<?php echo $i; ?>]" value="<?php echo $row['email'];?>" form="attendanceForm"></td>
<td><input type="text" readonly="readonly" name="class[<?php echo $i; ?>]" value="<?php echo $row['class'];?>" form="attendanceForm"></td>
<td><input type="radio" value="present" name="present[<?php echo $i; ?>]" checked form="attendanceForm"></td>
<td><input type="radio" value="absent" name="present[<?php echo $i; ?>]" form="attendanceForm"></td>
</tr>
<?php $i++;
}
}
?>
</form>
</tbody>
</table>
<script>
$("#submitAttendance").click(function(){
if($("#session").val().length==0){
alert("session is required");
} else {
$.cookie("sessionVal", $("#session").val());
var data = $('form#attendanceForm').serialize();
$.ajax({
url: 'save-attendance.php',
method: 'post',
data: {formData: data},
success: function (data) {
console.log(data);
if (data != null && data.success) {
alert('Success');
} else {
alert(data.status);
}
},
error: function () {
alert('Error');
}
});
}
});
</script>
<?php
$conn->close();
include('footer.php');
save-attendance.
<?php
//include ("nav.php");
require("db-connect.php");
$query = "SELECT * FROM user WHERE role='student'";
$result = $conn->query($query);
$nameArray = Array();
$count = mysqli_num_rows($result);
if(isset($_COOKIE['sessionCount'])){
$sessionCount = $_COOKIE['sessionCount'];
}
//save record to db
if(isset($_POST['formData'])) {
//increment the session count
if(isset($_COOKIE['sessionCount'])){
$sessionCount = $_COOKIE['sessionCount'];
setcookie('sessionCount', ++$sessionCount);
}
parse_str($_POST['formData'], $searcharray);
//print_r($searcharray);die;
//print_r($_POST);
for ($i = 0 ; $i < sizeof($searcharray) ; $i++){
// setcookie("checkloop", $i);;
$name = $searcharray['name'][$i];
$email= $searcharray['email'][$i];
$class = $searcharray['class'][$i];
$present= $searcharray['present'][$i];
if(isset($_COOKIE['sessionVal'])){
$sessionVal = $_COOKIE['sessionVal'];
}
//get class id
$class_query = "SELECT * FROM class WHERE name='".$class."'";
$class_id = mysqli_query($conn, $class_query);
if($class_id){
echo "I am here";
while($class_id1 = $class_id->fetch_assoc()){
$class_id_fin = $class_id1['id'];
echo $class_id['id'];
}
}
else{
echo "Error: " . $class_query . "<br>" . mysqli_error($conn);
}
//get student id
$student_query = "SELECT * FROM user WHERE email='".$email."'";
$student_id = $conn->query($student_query);
if($student_id) {
while ($student_id1 = $student_id->fetch_assoc()) {
$student_id_fin = $student_id1['id'];
}
}
//insert or update the record
$query = "INSERT INTO attendance VALUES ( '".$class_id_fin."', '".$student_id_fin."' , '".$present."','".$sessionVal."','comment')
ON DUPLICATE KEY UPDATE isPresent='".$present."'";
print_r($query);
if(mysqli_query($conn, $query)){
echo json_encode(array('status' => 'success', 'message' => 'Attendance added!'));
} else{
echo json_encode(array('status' => 'error', 'message' => 'Error: ' . $query . '<br>' . mysqli_error($conn)));
}
}
$conn->close();
}
You did not provide a lot of information, but I understand from the comments that the error is $sessionVal is undefined.
if $_COOKIE['sessionVal'] is not set, try:
1- print_r($_COOKIE) and check if [sessionVal] is set;
2- Try to add a fallback to:
if(isset($_COOKIE['sessionVal'])){
$sessionVal = $_COOKIE['sessionVal'];
}
else {
$sessionVal = 0;
}
or
$sessionVal = (isset($_COOKIE['sessionVal'])) ? $_COOKIE['sessionVal'] : 0;
Bottom line, there is not point to check if a variable is set and not having a fallback in case it is not set.

The query reverts back to being unfiltered when i click page 2 in my pagination in php

The pagination works well when the results are unfiltered. But once you check something in the check box then go to page 2 for example, the query will change back to the original and redirects to the page with the unfiltered query.
Here is my code:
<?php
require("functions.php");
require_once './class.PaginationLinks.php';
$dbconn = dbconn();
$printTable = true;
$page = 1;
if(isset($_POST["submit"])){
if(isset($_POST["Kitchen"])){
$arguments1[] = "Kitchen";
}
if (isset($_POST["Common_CR"])) {
$arguments1[] = "Common CR";
}
if (isset($_POST["CR_per_room"])) {
$arguments1[] = "CR per room";
}
if (isset($_POST["WiFi"])) {
$arguments1[] = "WiFi";
}
if (isset($_POST["Lobby"])) {
$arguments1[] = "Lobby";
}
if (isset($_POST["Laundry_Area"])) {
$arguments1[] = "Laundry Area ";
}
if (isset($_POST["Fire_Extinguisher"])) {
$arguments1[] = "Fire Extinguisher";
}
if (isset($_POST["Water_Pump"])) {
$arguments1[] = "Water Pump";
}
if (isset($_POST["Dirty_Kitchen"])) {
$arguments1[] = "Dirty Kitchen";
}
if (isset($_POST["Television"])) {
$arguments1[] = "Television";
}
if (isset($_POST["Emergency_Lights"])) {
$arguments1[] = "Emergency Lights";
}
if (isset($_POST["Canteen"])) {
$arguments1[] = "Canteen";
}
if (isset($_POST["Water_Dispenser"])) {
$arguments1[] = "Water Cooler";
}
if (isset($_POST["Rooftop_Gazebo"])) {
$arguments1[] = "Rooftop Gazebo";
}
if(!empty($_POST['loc'])){
$selectedRadio = $_POST['loc'];
if($selectedRadio == "dorm"){
$area = "dorm.location = 'dormArea'";
}
elseif($selectedRadio=="banwa"){
$area = "dorm.location = 'banwa'";
}
else{}
}
if(!empty($arguments1) && empty($selectedRadio)) {
$size = count($arguments1);
$query = "SELECT dorm.DormId, dorm.DormName, CONCAT(address.StreetName,', ', address.Barangay),owner.Name, dorm.HousingType, dorm.thumbnailpic
FROM dorm, address,owner
WHERE dorm.AddressId = address.AddressId
AND dorm.OwnerId = owner.OwnerId
AND dorm.DormId IN (SELECT all_facilities.DormId
FROM all_facilities
WHERE all_facilities.facilityName IN ('".implode("','",$arguments1)."')
GROUP BY all_facilities.DormId
HAVING COUNT(all_facilities.facilityNo)>= $size)";
unset($arguments1);
}
elseif (!empty($arguments1) && !empty($selectedRadio)) {
echo "both checkbox and radio are not empty";
$size = count($arguments1);
$query = "SELECT dorm.DormId, dorm.DormName, CONCAT(address.StreetName,', ', address.Barangay),owner.Name, dorm.HousingType, dorm.thumbnailpic
FROM dorm, address,owner
WHERE dorm.AddressId = address.AddressId
AND dorm.OwnerId = owner.OwnerId
AND $area
AND dorm.DormId IN (SELECT all_facilities.DormId
FROM all_facilities
WHERE all_facilities.facilityName IN ('".implode("','",$arguments1)."')
GROUP BY all_facilities.DormId
HAVING COUNT(all_facilities.facilityNo)>= $size)";
$selectedRadio='';
unset($arguments1);
}
elseif(empty($arguments1) && !empty($selectedRadio)){
echo "empty checkbox but RADIO IS ON!";
$query = "SELECT dorm.DormId,dorm.DormName, CONCAT(address.streetName,', ',address.Barangay), owner.Name, dorm.HousingType, dorm.thumbnailpic
FROM dorm, address, owner
WHERE dorm.AddressId = address.AddressId AND dorm.OwnerId = owner.OwnerId AND $area";
$selectedRadio='';
}
else{
echo "both empty";
$query = "SELECT dorm.DormID, dorm.DormName, CONCAT(address.streetName,', ',address.Barangay), owner.Name, dorm.HousingType, dorm.thumbnailpic
FROM dorm, address, owner
WHERE dorm.AddressId = address.AddressId AND dorm.OwnerId = owner.OwnerId";
}
}
else{
$query = "SELECT dorm.DormId,dorm.DormName, CONCAT(address.streetName,', ',address.Barangay), owner.Name, dorm.HousingType, dorm.thumbnailpic
FROM dorm, address, owner
WHERE dorm.AddressId = address.AddressId AND dorm.OwnerId = owner.OwnerId";
}
if(isset($_POST['find'])){
$key = $_POST['keyword'];
$query = "SELECT dorm.DormId,dorm.DormName, CONCAT(address.streetName,', ',address.Barangay), owner.Name, dorm.HousingType, dorm.thumbnailpic
FROM dorm, address, owner
WHERE dorm.AddressId = address.AddressId AND dorm.OwnerId = owner.OwnerId AND dorm.DormId in (SELECT dorm.DormId
FROM dorm
WHERE dorm.DormName LIKE '%$key%') ";
}
$result = mysqli_query($dbconn,$query);
if(mysqli_num_rows($result)==0){
$printTable = false;
}
?>
<!DOCTYPE html>
<html>
<head> <title>DorMe</title> </head>
<style type="text/css">
#pagination > li{
display: inline-block;
}
</style>
<body>
<form method="post">
<input type="text" name="keyword">
<input type="submit" name="find" value="SEARCH">
</form>
<div id="header">
<h1>Welcome to DorMe!</h1>
</div>
<?php
$start = 0;
$lim = 4;
if(isset($_GET['page'])){
$page = $_GET['page'];
$start = ($page-1) * $lim;
}
else{
$page = 1;
}
$countQuery = mysqli_affected_rows($dbconn);
$countQuery = ceil($countQuery/$lim);
$query = $query . " LIMIT $start, $lim";
$res = mysqli_query($dbconn, $query);
?>
<div id="content">
<div id="filter">
<form method="post">
<fieldset>
<legend>Filter:</legend>
<input type="checkbox" name="Kitchen">Kitchen
<input type="checkbox" name="Common_CR">Common CR
<input type="checkbox" name="CR_per_room">CR per room
<input type="checkbox" name="WiFi">WiFi
<input type="checkbox" name="Lobby">Lobby
<input type="checkbox" name="Laundry_Area">Laundry Area
<input type="checkbox" name="Fire_Extinguisher">Fire Extinguisher
<input type="checkbox" name="Water_Pump">Water Pump
<input type="checkbox" name="Dirty_Kitchen">Dirty Kitchen
<input type="checkbox" name="Television">Television
<input type="checkbox" name="Emergency_Lights">Emergency Lights
<input type="checkbox" name="Canteen">Canteen
<input type="checkbox" name="Water_Dispenser">Water Dispenser
<input type="checkbox" name="Rooftop_Gazebo">Rooftop Gazebo
<input type="radio" name="loc" value="dorm">Dorm Area
<input type="radio" name="loc" value="banwa"> Banwa
<input type="submit" name="submit" value="Filter">
</fieldset>
</form>
</div>
<div id="table">
<?php
if(!$printTable){
?>
<p>No results in database found!</p>
<?php
}else{
?>
<table border="1">
<thead>
<th>Picture</th>
<th>Information</th>
</thead>
<?php
while(list($DormId, $estName, $address,$owner,$housingType, $thumbnailpic)=mysqli_fetch_row($res)){
?>
<tr>
<td rowspan="4"><img src="<?=$thumbnailpic?>" style="max-width: 50%; max-height: 50%;"></td>
<td><label>Establishment Name: </label><?=$estName?></td>
</tr>
<tr>
<td><label>Address: </label><?=$address?></td>
</tr>
<tr>
<td><label>Owner: </label><?=$owner?></td>
</tr>
<tr>
<td><label>Housing Type: </label><?=determine($housingType)?></td>
</tr>
<?php
}
} ?>
</table>
</div>
<!-- PAGINATION QUERY -->
<ul id = "pagination">
<?php
// if($filt != 1){
if($countQuery > 1){
if($page>1){ ?>
<li>«</li>
<?php }
for($x = 1; $x <= $countQuery; $x++){
if($x == $page){ ?>
<li><a class="current" href="?page=<?php echo $x?>"><?=$x?></a></li>
<?php
}
else{ ?>
<li><?=$x?></li>
<?php }
}
if($page!=$countQuery){ ?>
<li>»</li>
<?php }
} elseif ($countQuery < 1) {
?>
<p> No match found! </p>
<?php } ?>
</ul>
</div>
<?php
mysqli_close($dbconn);
?>
</body>
</html>
... once you check something in the check box then go to page 2 for example, the query will change back to the original and redirects to the page with the unfiltered query.
The problem is because of the post method. See here,
<form method="post">
^^^^ <== see the post method here
<fieldset>
<legend>Filter:</legend>
<input type="checkbox" name="Kitchen">Kitchen
...
</fieldset>
</form>
When you hit the pagination link and goes to page 2, the $_POST data will not be retained. Better, use GET method for your form, like this:
<form method="get">
...
</form>
Subsequently, instead of $_POST, you have to process the form elements using $_GET superglobal, like this:
if(isset($_GET["submit"])){
if(isset($_GET["Kitchen"])){
$arguments1[] = "Kitchen";
}
if (isset($_GET["Common_CR"])) {
$arguments1[] = "Common CR";
}
...
}
And finally, you have to use the query part of the URL to correctly display the pagination links. So your pagination-links code should be like this:
<ul id = "pagination">
<?php
parse_str($_SERVER["QUERY_STRING"], $url_array);
unset($url_array['page']);
$url = http_build_query($url_array);
// if($filt != 1){
if($countQuery > 1){
if($page > 1){ ?>
<li>«</li>
<?php
}
for($x = 1; $x <= $countQuery; $x++){
if($x == $page){ ?>
<li><a class="current" href="?page=<?php echo $x; ?><?php echo isset($url) && !empty($url) ? "&" . $url : ""; ?>"><?=$x?></a></li>
<?php
}else{ ?>
<li><?=$x?></li>
<?php
}
}
if($page!=$countQuery){ ?>
<li>»</li>
<?php
}
} elseif ($countQuery < 1) { ?>
<p> No match found! </p>
<?php
}
?>
</ul>

Counter increasing in refresh and in reload in php

I have set a counter in php code to increment the id value in mysql on every next click but when I refresh or reload the page the value is increasing automatically is there any solution for this problem or any other substitute.
<?php
$db = mysqli_connect('localhost','root','root','rahul');
$questions ="";
$msg2 ="";
$o1 ="" ;
$o2 ="" ;
$o3 ="" ;
$o4 ="" ;
$disable = "";
$disable2 = "";
session_start();
if(empty($_SESSION['count']))
$_SESSION['count'] = 0;
if(isset($_POST['sub1'])){
$ans = $_POST['ans'];
$email = "rahul#gmail.com";
$order = $_SESSION['count']+1;
echo $order;
$_SESSION['count'] = $order;
$sql = (" SELECT * FROM qna WHERE id = $order ");
$query = mysqli_query($db, $sql);
$row=mysqli_fetch_array($query, MYSQLI_ASSOC);
$questions = $row['questions'];
$o1 = $row['o1'];
$o2 = $row['o2'];
$o3 = $row['o3'];
$o4 = $row['o4'];
$disable="";
if($_SESSION['count']>5)
{
$disable = "disabled";
}
$disable2 = "";
if($_SESSION['count']<=1)
{
$disable2 = "disabled";
}
//$sql2 = "INSERT INTO result (id, answer, email) VALUES ('', '$ans', '$email') ".mysqli_error();
/*
$sql3 = mysqli_query($db, "INSERT INTO result (answer, email) VALUES ('$ans', '$email')");
if(mysqli_affected_rows($sql3)== true)
{
echo "inserted";
}
else
{
echo "not inserted";
}
*/
echo $ans. $email;
}
$sql4 = mysqli_query("select * from result");
$row = mysqli_fetch_array($db, $sql4);
// while()
echo $row['id'];
for($i=1;$i<=5;$i++)
{
}
?>
<?php
if(isset($_POST['sub2'])){
$result2 = $_SESSION['count']-1;
$_SESSION['count'] = $result2;
$sql = (" SELECT * FROM qna WHERE id = $result2 ");
$query = mysqli_query($db, $sql);
$row=mysqli_fetch_array($query, MYSQLI_ASSOC);
$questions = $row['questions'];
$o1 = $row['o1'];
$o2 = $row['o2'];
$o3 = $row['o3'];
$o4 = $row['o4'];
if($_SESSION['count']<=1){
$disable2 = "disabled";
}
}
session_write_close();
?>
<?php
if(isset($_POST['start'])){
$order = $_SESSION['count']+1;
echo $order;
$_SESSION['count'] = $order;
$sql = (" SELECT * FROM qna WHERE id = 1 ");
$query = mysqli_query($db, $sql);
$row = mysqli_fetch_array($query, MYSQLI_ASSOC);
$questions = $row['questions'];
$o1 = $row['o1'];
$o2 = $row['o2'];
$o3 = $row['o3'];
$o4 = $row['o4'];
$disable="";
if($_SESSION['count']>=5)
{
$disable = "disabled";
}
$disable2 = "";
if($_SESSION['count']<=1){
$disable2 = "disabled";
}
session_write_close();
}
?>
<center><br><br><br>
<form method="post">
<input type="submit" name="start" value="start">
</form>
Log out
<form action="" method="post" >
<table border="1" height="300px" width="500px">
<tr>
<th colspan="2"><?php echo $questions; ?></th>
</tr>
<tr>
<td><input type="radio" name="ans" id="ans" value="<?php echo $o1; ?>"><?php echo $o1; ?></td>
<td><input type="radio" name="ans" value="<?php echo $o2; ?>"><?php echo $o2; ?></td>
</tr>
<tr>
<td><input type="radio" name="ans" value="<?php echo $o3; ?>"><?php echo $o3; ?></td>
<td><input type="radio" name="ans" value="<?php echo $o4; ?>"><?php echo $o4; ?></td>
</tr>
<tr colspan="2">
<td><center><input type="submit" name="sub1" value="next" <?php echo $disable ?>> </td>
<td><center><input type="submit" name="sub2" value="previous" <?php echo $disable2 ?>>
<input type="submit" name="submit3" value="submit" > </td>
</tr>
</form>
</table>
<?php
if(isset($_POST['submit3']))
{
$ans = $_POST['ans'];
$email = "dummy";
//$sql2 = "INSERT INTO result (id, answer, email) VALUES ('', '$ans', '$email') ".mysqli_error();
$sql3 = mysqli_query($db, "INSERT INTO result (answer, email) VALUES ('$ans', '$email')");
if(mysqli_affected_rows($sql3)== true)
{
echo "inserted";
}
else
{
echo "not inserted";
}
echo $ans. $email;
}
?>
when you are reloading a web-page, you are reloading its POST (and also GET) data as well if it's there. if you are submitting a form then the target page contains POST data in its header. so if you reload this page it's like you would have clicked the button again.
since you are already using a session there is a workaround:
add a hidden field with a micro-timestamp in your form. this micro-timestamp will be different every time your page gets loaded (per user) - but this "new" timestamp only get's posted when you use the button. when you just refresh the page, you are reloading with the old timestamp.
so you just need to save compare the last timestamp (saved in a session variable) with the currently posted timestamp. if they are equal - the page just got refreshed - if they are not equal, then you got a new timestamp which was sent by your form:
<?php
session_start();
if(!isset($_SESSION["timestamp"]))
$_SESSION["timestamp"] = 0;
if(!isset($_POST["timestamp"]))
$_POST["timestamp"] = 0;
// previous timestamp - saved in session variable:
$prev_ts = $_SESSION["timestamp"];
// currently posted timestamp:
$post_ts = $_POST["timestamp"];
if($prev_ts != $post_ts)
{
// code to increase your counter goes here.
$feedback = "button pressed";
}
else
{
// do nothing when the page just got refreshed
$feedback = "refreshed";
}
$_SESSION["timestamp"] = $post_ts;
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php echo $feedback; ?>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="POST">
<input type="hidden" name="timestamp" value="<?php echo microtime(); ?>">
<input type="submit" name="go" value="count">
</form>
</body>
</html>

Add-to-cart coding is that correct with form?

<?php
session_start();
include("conn.php");
$action = $_POST['action'];
$user = $_SESSION['username'];
if(empty($user)){
echo"<script>alert('Please log in!');window.location='Log In.php';</script>";
exit;
}
if($action == 'add'){
$cart_arr = array(
'foodID'=>$_POST['foodID'],
'order_num'=>$_POST['order_num'],
'food_type'=>$_POST['food_type'],
);
$cart_session = $_SESSION['cart_'.$user];
if(empty($cart_session)){
$cart_session[$cart_arr['foodID']] = $cart_arr;
} else if(!empty($cart_session[$cart_arr['foodID']])){
$cart_session[$cart_arr['foodID']]['order_num']+=$cart_arr['order_num'];
} else {
echo $cart_session[$cart_arr['foodID']] = $cart_arr;
}
$_SESSION['cart_'.$user] = $cart_session;
} else if($action == 'clear'){
$_SESSION['cart_'.$user]=array();
echo"<script>alert('Shopping cart is empty, return home!');window.location='homepage.php';</script>";
exit;
} else if($action == 'change'){
$temp_cart = $_SESSION['cart_'.$user];
foreach($temp_cart as $k=>$v){
if($_POST['goods_'.$k]!= $v['order_num']){
$temp_cart[$k]['order_num'] = $_POST['goods_'.$k];
}
if($_POST['goods_'.$k] == 0){
unset($temp_cart[$k]);
}
}
$_SESSION['cart_'.$user] = $temp_cart;
}
if(empty($_SESSION['cart_'.$user])){
echo"<script>alert('Shopping cart is empty, please add some orders!');window.location = 'homepage.php';</script>";
exit;
}
$goods_id = array();
$cart = $_SESSION['cart_'.$user];
$v['food_type'] = $_POST['food_type'];
foreach($cart as $k=>$v){
$goods_id[$v['foodID']] = $v['foodID'];
}
$goods_id_str = implode(",",$goods_id);
mysql_query("set names utf8");
$sql = "select * from foodmenu where foodID IN (".$goods_id_str.")";
$query = mysql_query($sql);
$cart_goods = array();
while($arr = mysql_fetch_array($query)){
$cart_goods[$arr['foodID']] = $arr;
}
foreach($cart as $k=>$v){
$cart[$k]['food_name'] = $cart_goods[$k]['food_name'];
$cart[$k]['food_img'] = str_replace("../","",$cart_goods[$k]['food_img']);
$cart[$k]['food_price'] = $cart_goods[$k]['food_price'];
$cart[$k]['food_description'] = $_POST['food_description'];
}
?>
May I know is that this coding correct?
Because it shows blank page when it click on the button on previous php for add-to-cart purpose and it just shows normal header at the top.
I will attach form to access this php.
<div class="detailtop">
<?php
$result = mysql_query("SELECT * FROM foodmenu where foodID = '$foodID'");
while($row=mysql_fetch_array($result)){
?>
<dl>
<dt>
<img src="<?php echo $row["food_img"];?>" /> </dt>
<dd>
<form action="order.php" method="get" name="send" onSubmit="return Check()" enctype="multipart/form-data">
<h3><?php echo $row["food_name"];?></h3>
<div class="detailtips">
<?php echo $row["food_description"];?>
</div>
<p><span>Restaurant:</span><strong><?php echo $row["restaurant_name"];?></strong></p>
<p><span>Type :</span><strong><?php echo $row["food_type"];?></strong></p>
<p><span>Price :</span>RM <strong><?php echo $row["food_price"];?><input name="num" type="hidden" class="num" value="<?php echo $row["food_price"];?>" /></strong></p>
<div class="order" style=" padding-top:20px; padding-left:20px;">
<input name="id" type="hidden" value="<?php echo $row["foodID"];?>" />
<input name="" type="submit" value="" class="ordersubmit" style=" margin-left:30px; margin-top:20px;">
</div>
</form>
</dd>
</dl>
<?php }?>
</div>

Categories