Search Data not outputting the correct results - php

This form is a search form which allows the user to search for an event using the Venue and category fields which are scripted as dropdown boxes and the Price and event title as user input text boxes, as shown via the code if a keyword is entered which matches the fields on the database it should output all the related information for that event if any matches have been made on either search fields, the tickboxes allow the user to identify what criteria they would like to search with, if the tickbox field hasn't been checked then the SQL enquiry will not search for keywords with that corresponding field.
The issue is, it all seems to work fine except no results seem to show up for the Venue and Category fields if they was solely used to search for an event. But if I choose another field everything is outputting correctly including the venue and Category field.
DATABASE: http://i.imgur.com/d4uoXtE.jpg
HTML FORM
<form name="searchform" action ="PHP/searchfunction.php" method = "post" >
<h2>Event Search:</h2>
Use the Check Boxes to indicate which fields you watch to search with
<br /><br />
<h2>Search by Venue:</h2>
<?php
echo "<select name = 'venueName'>";
$queryresult2 = mysql_query($sql2) or die (mysql_error());
while ($row = mysql_fetch_assoc($queryresult2)) {
echo "\n";
$venueID = $row['venueID'];
$venueName = $row['venueName'];
echo "<option value ='$venueName'";
echo ">$venueName</option>";
}# when the option selected matches the queryresult it will echo this
echo "</select>";
echo" <input type='checkbox' name='S_venueName'>";
mysql_free_result($queryresult2);
mysql_close($conn);
?>
<br /><br />
<h2>Search by Category:</h2>
<?php
include 'PHP/database_conn.php';
$sql3 ="SELECT catID, catDesc
FROM te_category";
echo "<select name = 'catdesc'>";
$queryresult3 = mysql_query($sql3) or die (mysql_error());
while ($row = mysql_fetch_assoc($queryresult3)) {
echo "\n";
$catID = $row['catID'];
$catDesc = $row['catDesc'];
echo "<option value = '$catDesc'";
echo ">$catDesc </option>";
}
echo "</select>";
mysql_free_result($queryresult3);
mysql_close($conn);
?>
<input type="checkbox" name="S_catDes">
<br /><br />
<h2>Search By Price</h2>
<input type="text" name="S_price" />
<input type="checkbox" name="S_CheckPrice">
<br /><br />
<h2>Search By Event title</h2>
<input type="text" name="S_EventT" />
<input type="checkbox" name="S_EventTitle">
<br /><br />
<input name="update" type="submit" id="update" value="Search">
</form>
PHP CODE THAT DEALS WITH PROCESSING THE FORM DATA
<?php
include 'database_conn.php';
$venuename = $_POST['venueName']; //this is an integer
$catdesc = $_POST['catdesc']; //this is a string
$Price = $_POST['S_price'];
$EventT = $_POST['S_EventT'];
#the IF statements state if the tickbox is checked then search with these enquires
if (isset($_POST['S_VenueName'])) {
$sql = "SELECT * FROM te_venue WHERE venueName= '$venuename'";
}
if (isset($_POST['S_catDes'])) {
$sql = "SELECT * FROM te_category WHERE catID= '$catdesc'";
}
if (isset($_POST['S_CheckPrice'])) {
$sql = "SELECT * FROM te_events WHERE (eventPrice LIKE '%$Price%')";
}
if (isset($_POST['S_EventTitle'])) {
$sql = "SELECT * FROM te_events WHERE (eventTitle LIKE '%$EventT%')";
}
$queryresult = mysql_query($sql) or die (mysql_error());
while ($row = mysql_fetch_assoc($queryresult))
{
echo "Event Title: "; echo $row['eventTitle'];
echo "<br />";
echo "Event Description: "; echo $row['eventDescription'];
echo "<br />";
echo "Event Venue "; echo "$venuename";
echo "<br />";
echo "Event Category "; echo "$catdesc";
echo "<br />";
echo "Event Start Date "; echo $row['eventStartDate'];
echo "<br />";
echo "Event End Date "; echo $row['eventEndDate'];
echo "<br />";
echo "Event Price "; echo $row['eventPrice'];
echo "<br /><br />";
}
mysql_free_result($queryresult);
mysql_close($conn);
?>

Try using atleast MySQLi instead of deprecated MySQL. You can try this:
database_conn.php:
<?php
/* ESTABLISH YOUR CONNECTION. REPLACE THE NECESSARY DATA BELOW */
$con=mysqli_connect("YourHost","YourUsername","YourPassword","YourDatabase");
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
?>
HTML Form:
<html>
<body>
<?php
include 'PHP/database_conn.php';
$sql2="SELECT venueID, venueName FROM te_venue"; /* PLEASE REPLACE THE NECESSARY DATA */
echo "<select name = 'venueName'>";
$queryresult2 = mysqli_query($con,$sql2);
while($row = mysqli_fetch_array($queryresult2)) {
echo "\n";
$venueID = mysqli_real_escape_string($con,$row['venueID']);
$venueName = mysqli_real_escape_string($con,$row['venueName']);
echo "<option value ='$venueName'>";
echo $venueName."</option>";
} /* when the option selected matches the queryresult it will echo this ?? */
echo "</select>";
echo "<input type='checkbox' name='S_venueName'>";
?>
<br><br>
<h2>Search by Category:</h2>
<?php
$sql3 ="SELECT catID, catDesc FROM te_category";
echo "<select name = 'catdesc'>";
$queryresult3 = mysqli_query($con,$sql3);
while($row = mysqli_fetch_array($queryresult3)) {
echo "\n";
$catID = mysqli_real_escape_string($con,$row['catID']);
$catDesc = mysqli_real_escape_string($con,$row['catDesc']);
echo "<option value = '$catDesc'>";
echo $catDesc."</option>";
}
echo "</select>";
?>
<input type="checkbox" name="S_catDes">
<br><br>
<h2>Search By Price</h2>
<input type="text" name="S_price" />
<input type="checkbox" name="S_CheckPrice">
<br><br>
<h2>Search By Event title</h2>
<input type="text" name="S_EventT" />
<input type="checkbox" name="S_EventTitle">
<br><br>
<input name="update" type="submit" id="update" value="Search">
</form>
</body>
</html>
PHP:
<?php
include 'database_conn.php';
$venuename = mysqli_real_escape_string($con,$_POST['venueName']); /* this is an integer */
$catdesc = mysqli_real_escape_string($con,$_POST['catdesc']); /* this is a string */
$Price = mysqli_real_escape_string($con,$_POST['S_price']);
$EventT = mysqli_real_escape_string($con,$_POST['S_EventT']);
/* SHOULD PRACTICE USING ESCAPE_STRING TO PREVENT SOME OF SQL INJECTIONS */
/* the IF statements state if the tickbox is checked then search with these enquires */
if (isset($_POST['S_VenueName'])) {
$sql = "SELECT * FROM te_venue WHERE venueName= '$venuename'";
}
if (isset($_POST['S_catDes'])) {
$sql = "SELECT * FROM te_category WHERE catID= '$catdesc'";
}
if (isset($_POST['S_CheckPrice'])) {
$sql = "SELECT * FROM te_events WHERE (eventPrice LIKE '%$Price%')";
}
if (isset($_POST['S_EventTitle'])) {
$sql = "SELECT * FROM te_events WHERE (eventTitle LIKE '%$EventT%')";
}
$queryresult = mysqli_query($con,$sql);
while ($row = mysqli_fetch_array($queryresult))
{
echo "Event Title: "; echo $row['eventTitle'];
echo "<br />";
echo "Event Description: "; echo $row['eventDescription'];
echo "<br />";
echo "Event Venue "; echo "$venuename";
echo "<br />";
echo "Event Category "; echo "$catdesc";
echo "<br />";
echo "Event Start Date "; echo $row['eventStartDate'];
echo "<br />";
echo "Event End Date "; echo $row['eventEndDate'];
echo "<br />";
echo "Event Price "; echo $row['eventPrice'];
echo "<br /><br />";
}
mysqli_close($conn);
?>
What if user checks all the check box? What would happen is, the last condition will be used. The first three conditions will be overwritten by the last condition.
If you use ELSE IF in those conditions, the first condition will be implemented.
My advice is to use radio button instead of check box and hope you gets the idea along the way.

Have you tried printing out your $sql query for debugging?
Try <input type="checkbox" name="S_catDes" value="checked">.
From memory checkboxes need a value field but I could be wrong. Hope this helps.

Related

Echo the selected items in drop down menus

I created two dropdown menu populated by two different database tables. I also created a button to press after having chosen something from the menu. What I would like to do (but I am not able to) is to print on the screen the selected items. Below the code I wrote until now:
<?php
require_once('assets/index.php');
$result1 = $conn->query("select * from partenze");
$result2 = $conn->query("select * from arrivi");
echo "<html>";echo "<body>";echo "<form action='index.php'>"; echo "Select your Departure: <select name='p_id'>";
while ($row1 = $result1->fetch_assoc()) {
unset($pid, $pname);
$pid = $row1['p_id'];
$plocalita = $row1['p_localita'];
echo '<option value="'.$pid.'">'.$plocalita.'</option>';}
echo "</select><br>";echo "Select your Arrival: <select name='a_id'>";
while ($row2 = $result2->fetch_assoc()) {
unset($aid, $aname);
$aid = $row2['a_id'];
$alocalita = $row2['a_localita'];
echo '<option value="'.$aid.'">'.$alocalita.'</option>';}
echo "</select>";
echo "<input type='submit' name='submit' value='Get Selected Values' />"; echo "</form>";
if(isset($_POST['submit'])){
$selected_val1 = $_POST['p_id']; // Storing Selected Value In Variable
$selected_val2 = $_POST['a_id']; // Storing Selected Value In Variable
echo "You have selected :" .$selected_val1. " and " .$selected_val2; // Displaying Selected Value
}
echo "</body>";echo "</html>";
?>
You are trying to retrieve data by $_POST data. but in form you haven't specify request method. So it will take get method by default. So you need to specify method=post in form to get request from POST
<?php
require_once('assets/index.php');
$result1 = $conn->query("select * from partenze");
$result2 = $conn->query("select * from arrivi");
echo "<html>";
echo "<body>";
echo "<form action='index.php' method='post'>";
echo "Select your Departure:
<select name='p_id'>";
while ($row1 = $result1->fetch_assoc()) {
unset($pid, $pname);
$pid = $row1['p_id'];
$plocalita = $row1['p_localita'];
echo '<option value="'.$pid.'">'.$plocalita.'</option>';}
echo "</select><br>";echo "Select your Arrival: <select name='a_id'>";
while ($row2 = $result2->fetch_assoc()) {
unset($aid, $aname);
$aid = $row2['a_id'];
$alocalita = $row2['a_localita'];
echo '<option value="'.$aid.'">'.$alocalita.'</option>';}
echo "</select>";
echo "<input type='submit' name='submit' value='Get Selected Values' />";
echo "</form>";
if(isset($_POST['submit'])){
$selected_val1 = $_POST['p_id']; // Storing Selected Value In Variable
$selected_val2 = $_POST['a_id']; // Storing Selected Value In Variable
echo "You have selected :" .$selected_val1. " and " .$selected_val2; // Displaying Selected Value
}
echo "</body>";echo "</html>";
?>

How do I create an edit-option for each row in a table?

I am using the following code to display certain rows from my database table:
<?php
$searchtype=$_POST['searchtype'];
$searchterm=$_POST['searchterm'];
$searchterm= trim($searchterm);
if (!$searchtype || !$searchterm)
{
echo 'Error';
exit;
}
if (!get_magic_quotes_gpc())
{
$searchtype = addslashes($searchtype);
$searchterm = addslashes($searchterm);
}
$db = include "connect2db.php";
$query = "select * from notes where ".$searchtype." like '%".$searchterm."%'";
$result = $db->query($query);
$num_results = $result->num_rows;
echo '<p>Number of rows found: '.$num_results.'</p>';
for ($i=0; $i <$num_results; $i++)
{
$row = $result->fetch_assoc();
echo '<i>';
echo stripslashes($row['date']);
echo '</i><br /> ';
echo '<b>';
echo stripslashes($row['notetitle']);
echo '</b><br /> ';
echo stripslashes($row['note']);
echo '<br /><br /> ';
echo '</p>';
}
$result->free();
$db->close();
?>
Now I would like to display an edit-link for each row displayed, that can open a new page in which it is possible to edit a specific row. I already have the code that lets you edit the row:
<?php
if ($_REQUEST['save']=="Save") { // is data submitted?
// create variables
$noteid = $_REQUEST['noteid'];
$coursename = $_REQUEST['coursename'];
$notetitle = $_REQUEST['notetitle'];
$note = $_REQUEST['note'];
$query = "UPDATE notes SET ";
$query .= "coursename='$coursename', ";
$query .= "notetitle='$notetitle', ";
$query .= "note='$note' ";
$query .= "WHERE noteid='$noteid'";
$result = $db->query($query);
} elseif ($_REQUEST['delete']=="Delete") { // is data to be removed?
$noteid = $_REQUEST['noteid'];
$query="DELETE FROM notes WHERE noteid='$noteid'";
$result = $db->query($query);
}
?>
<div class="formular">
<div class="row1">
<p>Id</p>
<p>Notetitle</p>
<p>Note</p>
</div>
<?php
$query = "SELECT * FROM notes ORDER BY noteid DESC";
$result = $db->query($query);
while ($row = mysqli_fetch_array($result)) {
echo "<form ".$_SERVER['PHP_SELF']." name='edit-form' method='post' class='row1'>\n";
echo "<p class='align_top padding_top'>".$row['noteid']."<input type='hidden' name='noteid' value='".$row['noteid']."' /></p>\n";
echo "<p class='align_top'><input type='text' name='notetitle' value='".$row['notetitle']."' /></p>\n";
echo "<p><textarea name='note' rows='10' cols='50'>".$row['note']."</textarea></p>\n";
echo "<p><input type='submit' name='save' value='Save' /></p>";
echo "<p><input type='submit' name='delete' value='Delete' /></p>";
echo "</form>\n";
}
echo '</div>';
$result->free();
$db->close();
?>
What I am struggling with is how to display an edit-link for each row that lets you open a page where you can edit/delete the content of only that row.
I hope someone can help, I am very new at this.
Thank you!
Add a button next to each row that opens an edit page (or modal) with the id inside, example: <button onclick="edit('randomId')">Edit RandomId </button>
You could implement something different that accepts the unique id of that specific row and open a new page or modal with it.

Session variable and Dynamic Pagination in php

<form action='movies.php' method='POST'>
Language: <select name="language">
<option selected>hindi</option>
<?php
require("config.php");
$result="SELECT language FROM movies";
$q = mysqli_query($conn,$result) or die(mysql_error());
while ($row=mysqli_fetch_array($q)) {
$s1=$row["language"];
echo "<option>
$s1
</option>";
}
echo "<br>"
?>
</select>
<br /> <br />
<input type='submit' value='Submit' />
</form>
<?php
$lang=#$_POST['language'];
$_SESSION["lang1"]=$lang;
/*
if($lang){
$sql = "SELECT name,language FROM movies WHERE language='$lang'";
$result = mysqli_query($conn,$sql);
if (mysqli_num_rows($result)>0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<div class="query"> <img src="images\tiles\bb.jpg"> ';
echo "<h3> " . $row["name"]."</h3>". "<br>";
echo "</div>";
}
} else {
echo "0 results";
}
}
*/
$page=#$_GET['page'];
if($page==""|| $page=="1")
{
$page1=0;
}
else{
$page1=($page*3)-3;
}
$sql = "SELECT name,language FROM movies WHERE language='". $_SESSION['lang1']."' limit $page1,3 ";
$result = mysqli_query($conn,$sql);
$a= mysqli_num_rows($result);
while ($list=mysqli_fetch_array($result))
{
echo $list['name'] . " : " . $list['language'] . "<br />";
}
$sql = "SELECT name,language FROM movies WHERE language='$lang'";
$result = mysqli_query($conn,$sql);
$a= mysqli_num_rows($result);
$numrows=$a;
$rowsperpage=3;
$totalpages= ceil($numrows/$rowsperpage);
echo "</br>";
for($b=1;$b<=$totalpages;$b++)
{
?><?php echo $b." ";?> <?php
}
?>
I get proper output on movies.php which is the first 3 rows from database,but when i click on the dynamically created pagination link like movies.php?page=2 then there is no output on this page.This code works fine if i manually set the
$_SESSION["lang1"]="English"; then i get proper output but when i take input from the form it doesnt work.

Creating record in php quotation mark issue

I'm trying to create a user record to input into a phpmyadmin database.
createUserRecord($usersTable, [$r2,"'".$_POST["firstName"]."'","'".$_POST["lastName"]."'","'".$_POST["username"]."'","'".$_POST["password"]."'","'".$_POST["admin"]."'","'".$_POST["email"]."'"]);
I think there is an issue with the quotation marks or concatenation of the $_POST variables.
There is a record created in the phpmyadmin database, but the values are either not there for the text data types or the two integer value are showing up as 0. When I use print_r to print the values of this createUserRecord, it only prints '1'.
This is the code for the signup page that creates user records:
<html>
<body>
<p><h2><strong>Welcome to the Marist Room Reservation Recommender!</strong></h2></p>
<p><h3><strong>Reserve a room below!</strong></h3></p>
<?php
require 'sql_helper3.php';
if ($_POST[submitted] == "submitted") {
$r2 = (rand(11111,99999));
createUserRecord($usersTable, [$r2,"'".$_POST["firstName"]."'","'".$_POST["lastName"]."'","'".$_POST["username"]."'","'".$_POST["password"]."'","'".$_POST["admin"]."'","'".$_POST["email"]."'"]);
header('location:verify3.php');
} else {
echo "<h1>Please enter your details:</h1>";
echo "<form action=verify3.php method=post>\n";
echo "First Name: <input type=text name=firstName placeholder=\"Enter First Name\" required=required>\n<br>";
echo "Last Name: <input type=text name=lastName placeholder=\"Enter Last Name\" required=required>\n<br>";
echo "CWID: <input type=\"text\" name=\"CWID\" placeholder=\"Enter CWID\" required=required>\n<br>";
echo "Class: <select name=\"class\">\n";
echo "<option value=\"1\">Freshman</option>\n";
echo "<option value=\"2\">Sophomore</option>\n";
echo "<option value=\"3\">Junior</option>\n";
echo "<option value=\"3\">Senior</option>\n";
echo "</select>\n<br>";
echo " Gender:\n";
echo " <select option name = \"Gender\">\n<br> ";
echo " <option value = \"None\">Select One...</option>\n<br> ";
echo " <option value = \"Male\">Male</option>\n<br> ";
echo " <option value = \"Female\">Female</option>\n<br> ";
echo " </select>\n<br> ";
$sql = "SELECT name, roomsAvailable FROM $dormTable";
if($result = mysqli_query($conn, $sql)) {
$numRows = mysqli_num_rows($result);
echo " <strong>Residence Areas</strong>\n ";
echo " <select name = dorm> \n";
for ($i = 0; $i < $numRows; $i++){
$aDorm = mysqli_fetch_assoc($result);
$dormName = $aDorm['name'];
$dormAvailable = $aDorm['roomsAvailable'];
if($dormName != 'Select One...' && $dormAvailable != 0){
echo "<option value = \"$dormName\" > $dormName ($dormAvailable)</option>\n";
}
elseif ($dormAvailable == 0 && $dormName != 'Select One...'){
echo "<option value = \"$dormName\" disabled=\"disabled\"> $dormName </option> \n";
}
elseif ($dormName == 'Select One...'){
echo "<option value = \"$dormName\"> $dormName </option> \n";
}
}
echo "</select>\n<br><br>";
}
else {
echo "something is wrong: " .mysqli_error($conn);
echo $result;
die;
}
echo "<input type=checkbox name=specialNeeds value=\"1\">Special Needs?\n<br>";
echo "<input type=checkbox name=laundry value=\"1\">Laundry?\n<br>";
echo "<input type=checkbox name=fullyEquippedKitchen value=\"1\">Kitchen?\n<br><br>";
echo "Username:<input type=text name=username placeholder=\"Enter Username\" required=required><br>\n";
echo "Password:<input type=password name=password placeholder=\"Enter Password\" required=required><br>\n";
echo "Email Address:<input type=email name=email placeholder=\"Enter Email\" required=required><br><br>\n";
echo "<input type=checkbox name=admin value=\"1\">Administrator?\n<br>";
echo "<input type=hidden name=submitted value=submitted>\n<br>";
echo "<input type=\"submit\" value=\"Signup\">\n<br>";
echo "</form>\n";
foreach ($_POST as $k => $v){
echo"<input type = hidden name = $k value = \"$v\"> <?php echo print_r($_POST) ?>";
}
}
?>
</body>
This is the function that is called from another php page:
$table = $usersTable;
function createUserRecord($table, $values) {
echo "<br> in createUserRecord(), table is \"$table\", values are ".print_r($values)."\n<br>";
return insertInto($table, ["id", "firstName", "lastName", "username", "password", "admin"], $values);
var_dump($values);
}
function insertInto($table, $columns, $values) {
$sql = "INSERT INTO $table (`" . implode("`, `", $columns) . "`) VALUES ('" . implode("', '", $values) . "')";
return query($sql);
}
This is the results page:
<?php
//Take user selection from verify
require 'sql_helper3.php';
date_default_timezone_set('America/New_York');
$date = date('m/d/Y h:i:s a', time());
$dorm = $_POST["dorm"];
$sql = "SELECT * FROM $dormTable WHERE name = '$dorm'";
if ($result = mysqli_query($conn, $sql)) {
$dormRecord = mysqli_fetch_assoc($result);
}
$reservationsTable = "Reservations";
$r1 = (rand(11111,99999));
// SQL query to fetch information of registered users and finds user match.
$username=$_POST['username'];
$password=$_POST['password'];
$sql = "SELECT * FROM $usersTable WHERE password = \"$password\" AND username = \"$username\"";
echo "Running SQL $sql\n<br>";
$result = mysqli_query($conn,$sql);
$_SESSION['login_user']=$username; // user is logged in now
// echo "Initializing session...";
$aUser = mysqli_fetch_assoc($result);
//print_r($aUser);die;
$_SESSION['user_firstname'] = $aUser['firstName'];
$_SESSION['user_lastname'] = $aUser['lastName'];
$_SESSION['user_email'] = $aUser['email'];
$_SESSION['user_class'] = $aUser['class'];
$_SESSION['user_gender'] = $aUser['Gender'];
$_SESSION['user_kitchen'] = $aUser['fullyEquippedKitchen'];
$_SESSION['user_laundry'] = $aUser['laundry'];
$_SESSION['user_specialneeds'] = $aUser['specialNeeds'];
$_SESSION['user_admin'] = $aUser['admin'];
$_SESSION['user_id'] = $aUser['id'];
createReservationRecord($reservationsTable, [$r1, $date, "'".$usersTable[id]."'", "'".$dormRecord[id]."'", "'".$_POST[CWID]."'", "'".$_POST[firstName]."'", "'".$_POST[lastName]."'", "'".$_POST['class']."'", "'".$_POST[gender]."'", "'".$_POST[fullyEquippedKitchen]."'", "'".$_POST[laundry]."'", "'".$_POST[specialNeeds]."'"]);
//Update the record where the dorm id is used and set the roomsAvailable to -1 for that dorm
$sql = "UPDATE $dormTable SET roomsAvailable = ".--$dormRecord[roomsAvailable] ." WHERE id = $dormRecord[id]";
query($sql);
//Update the record where the dorm id is used and set the roomsreserved to +1 for that dorm
$sql = "UPDATE $dormTable SET roomsReserved = ".++$dormRecord[roomsReserved] ." WHERE id = $dormRecord[id]";
query($sql);
echo"<br>This is the users table ".print_r($usersTable)."<br>";
?>
<html>
<body>
<h1>Reservation Confirmation </h1>
</table>
Confirmation Number: <?php echo "$r1"; ?> <br>
Date: <?php echo "$date";?><br>
First Name: <?php echo $_POST["firstName"];?><br>
Last Name: <?php echo $_POST["lastName"]; ?><br>
CWID: <?php echo $_POST["CWID"]; ?><br>
Gender: <?php echo $_POST["Gender"]; ?><br>
Class: <?php
if($_POST["class"] == 1){
echo "Freshman";
}
elseif($_POST["class"] == 2){
echo "Sophomore";
}
else{
echo "Junior/Senior";
//or we could do upperclassman
}
; ?><br>
Residence Area: <?php echo $_POST["dorm"]; ?><br>
Special Needs: <?php
if ($_POST["specialNeeds"]){
echo "Yes";
}
else{
echo "No";
} ?><br>
Laundry: <?php if (isset($_POST["laundry"])){
echo "Yes";
}
else{
echo "No";
}
?><br>
Fully Equipped Kitchen: <?php
if (isset($_POST["fullyEquippedKitchen"])){
echo "Yes";
}
else{
echo "No";
}
if ($aUser["admin"]) {
echo "<br><br><a href=admin_main.php>Click here</a> to go to the admin landing page.\n<br>";
//header("location: admin_main.php"); // redirecting to admin landing page
}
else {
echo "<br><br><a href=reservations.php>Click here</a> to go to the reservations page.\n<br>";
// header('Location: profile.php'); // Redirecting To Students Landing page
}
?>
<br>
</body>
The output for this results page is:
Running SQL SELECT * FROM Users WHERE password = "bbb" AND username = "kk"
Warning: Illegal string offset 'id' in /home/ubuntu/workspace/Project_Three/results3.php on line 42 Call Stack: 0.0003 241480 1. {main}() /home/ubuntu/workspace/Project_Three/results3.php:0 Users
This is the users table 1
Reservation Confirmation
Confirmation Number: 19843
Date: 11/29/2016 01:28:30 pm
First Name: k
Last Name: b
CWID: 18738783
Gender: Female
Class: Freshman
Residence Area: Leo Hall
Special Needs: No
Laundry: No
Fully Equipped Kitchen: No
Click here to go to the reservations page.

SQL insert query loop

Hello so i am doing this school assigment where i have make a comment system corresponding to the post ID and i know that it looping three times but i gave it the post id. And i know that the postID is changeing all the time. i just have no idea how to fix this bug any ideas?
<?php require_once("menu.php");
$connection = connectToMySQL();
$selectPostQuery = "SELECT * FROM (SELECT * FROM `tblposts` ORDER BY id DESC LIMIT 3) t ORDER BY id DESC";
$result = mysqli_query($connection,$selectPostQuery)
or die("Error in the query: ". mysqli_error($connection));
while ($row = mysqli_fetch_assoc($result))
{
$postid = $row['ID'];
if (!empty($_POST['comment']) ) #To insert new comments in the database
{
$comment = $_POST['comment'];
$userid = $_SESSION['userID'];
$insertCommentQuery = "INSERT INTO `tblcomments` (`Content`,`UserID`,`PostID`,`Timestamp`) VALUES ('$comment','$userid','$postid',CURRENT_TIMESTAMP)";
$resultComment = mysqli_query($connection, $insertCommentQuery)
or die("Error in the query: ". mysqli_error($connection));
}
echo "<div class=\"wrapper\">";
echo "<div class=\"titlecontainer\">";
echo "<h1>$row[Title]</h1>";
echo "</div>";
echo "<div class=\"textcontainer\">";
echo "<span>$row[Content]</span>";
echo "</div>";
if (!empty($row['ImagePath'])) #This will check if there is an path in the textfield
{
?>
<div class="imagecontainer">
<img src="images/<?php echo "$row[ImagePath]"; ?>">
</div>
<?php
}
echo "<div class=\"timestampcontainer\">";
echo "<b>Date posted :</b>$row[TimeStamp] ";
echo "<b>Author :</b> Admin";
echo "</div>";
#Selecting comments corresponding to the post
$selectCommentQuery = "SELECT * FROM `tblcomments` LEFT JOIN `tblusers` ON tblcomments.userID = tblusers.ID WHERE tblcomments.PostID ='$postid'";
$commentResult = mysqli_query($connection,$selectCommentQuery)
or die ("Error in the query: ". mysqli_error($connection));
while ($commentRow = mysqli_fetch_assoc($commentResult))
{
echo "<div class=\"commentcontainer\">";
echo "<div class=\"commentusername\"><h1>Username :$commentRow[Username]</h1></div>";
echo "<div class=\"commentcontent\">$commentRow[Content]</div>";
echo "<div class=\"commenttimestamp\">$commentRow[Timestamp]</div>";
echo "</div>";
}
if (!empty($_SESSION['userID']) )
{
echo "<form method=\"POST\" action=\"\" class=\"post-frm\">";
echo "<label>New Comment</label>";
echo "<textarea id=\"comment\" name=\"comment\"> </textarea>";
echo "<input id=\"submit\" type=\"submit\" name =\"submit\" class=\"button\"/>" ;
echo "</form>";
}
echo "</div>";
echo "<br /> <br /><br />";
}
require_once("footer.php") ?>
Well, that's exactly what your script does. It queries all posts, loops through them, and then performs an insert for all of them. To fix this, store the id of the post in the comment form. When you post the form, insert just a single comment and use the id in the form.
That could look something like this:
<?php
if (array_key_exists('postid', $_POST))
{
$postid = $_POST['postid'];
$comment = $_POST['comment'];
// Perform a single insert here, and use $postid and $comment.
}
// Then, start rendering the page:
require_once(menu.php);
$connection = connectToMySQL();
$selectPostQuery = SELECT * FROM (SELECT * FROM `tblposts` ORDER BY id DESC LIMIT 3) t ORDER BY id DESC;
$result = mysqli_query($connection,$selectPostQuery)
or die(Error in the query: . mysqli_error($connection));
while ($row = mysqli_fetch_assoc($result))
{
$postid = $row['ID'];
// Render the post itself here.
?>
<div class="wrapper">;
<div class="titlecontainer">;
<h1><?=$row['Title']?></h1>;
</div>;
<div class="textcontainer">;
<span><?=$row['Content']?></span>;
</div>;
<?php
// Render a comment form for each post (is that what you did?)
if (!empty($_SESSION['userID']) )
{?>
<form method=POST action= class=post-frm>
<label>New Comment</label>
<textarea id=comment name=comment></textarea>
<input type=hidden name=postid value=<?=$postid?>/>
<input id=submit type=submit name =submit class=button/>
</form>
<?}
}
Most of your code is the same, only the processing of the post data is now done before the loop.
Otherwise, I just fixed some small syntactic things (and maybe introduced new ones, I haven't tested it).
Also, I took the HTML out of echoes. It's a matter of taste, of course, but experience has taught me that big chunks of HTML in echo statements isn't very readable or maintainable. Rather just close the PHP tags, output the raw HTML and echo only the variables in it. You can use the short notation for that: <?= $value ?>, which basically means <?php echo $value ?>.

Categories