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.
Related
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.
<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.
I want to add loop to my sql query so that all the data from the table gets updated at one click. Right now only the last row is getting updated.
<?php
include_once 'db_connect.php';
if(isset($_POST['btn-signup']))
{
$PersonID = mysql_real_escape_string($_POST['PersonID']);
$FirstName = mysql_real_escape_string($_POST['FirstName']);
$Status = mysql_real_escape_string($_POST['Status']);
$Date = mysql_real_escape_string($_POST['Date']);
$uname = trim($uname);
$email = trim($email);
$upass = trim($upass);
// email exist or not
$query = "SELECT Date FROM status WHERE Date='$Date'";
$result = mysql_query($query);
$count = mysql_num_rows($result); // if email not found then register
if($count == 0){
if(mysql_query("INSERT INTO status(PersonID,FirstName,Status, Date) VALUES('$PersonID','$FirstName','$Status','$Date')"))
{
?>
<script>alert('successfully Added ');</script>
<?php
}
else
{
?>
<script>alert('error while registering you...');</script>
<?php
}
}
else{
?>
<script>alert('Sorry Attendence already taken ...');</script>
<?php
}
}
echo "<!DOCTYPE html>\n";
echo "<html>\n";
echo "<head>\n";
echo " <meta charset=\"utf-8\">\n";
echo " <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n";
echo " <title>Attendance</title>\n";
echo "</head>\n";
echo "<body>\n";
echo " \n";
echo "\n";
echo "\n";
include_once 'dbconnect.php';
$query = "SELECT * FROM attandance ";
$result = mysql_query($query);
echo "<h2>Mark Attendance</h2>\n";
echo "<form method=\"POST\" action=\"\">\n";
echo "<table border=\"2\">\n";
echo " <tr>\n";
echo " <th>PersonId</th>\n";
echo " <th>First Name</th>\n";
echo " <th>Status</th>\n";
echo " <th>Date</th>\n";
echo " </tr>\n";
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$PersonID=$row['PersonID'];
$FirstName=$row['FirstName'];
echo "<td> <input type=\"text\" name=\"PersonID\" value=\" $PersonID\"></td>\n";
echo "<td> <input type=\"text\" name=\"FirstName\" value=\" $FirstName\"></td>\n";
echo "<td><select name=\"Status\">\n";
echo " <option value=\"Present\">Present</option>\n";
echo " <option value=\"Absent\">Absent</option>\n";
echo " </select></td>\n";
echo "<td> <input type=\"date\" name=\"Date\" value=\" $Date\"></td>\n";
echo "</tr>\n";
}
echo " </table>\n";
echo "<input id=\"button\" type=\"submit\" name=\"btn-signup\" value=\"Mark\">\n";
echo "</form>\n";
echo "\n";
echo "\n";
echo "<a href='sheet.php'>Attendence Sheet</a>\n";
echo "</body>\n";
echo "</html>\n";
echo "\n";
?>
I am confused as i have used loop in the 2nd part to get value from the database and now i want to use loop to add those value in the database table. How can i add the code to the Insert SQL query in the first part of my code.
Hi Im creating a multiple search form using PHP,HTML,SQL with the use of functions, for example I have 3 search fields Firstname, lastname and email. I would let the user input from any of those, therefore i would be needing the if else statement, but to be able to satisfy all conditions it would take a lot of if else, so i think of using a function to output the table and place it inside the if else after the query on the database. But it seems that it could not be able to search in the database if I do it like this it outputs "0 results", but if i remove the function and place it on the end of my script I am able to search in the db but it could not detect my else condition which is "You have not yet entered any values"
function checkres()
{
//Get query on the database
$result = mysqli_query($conn, $sql);
//Check results
if (mysqli_num_rows($result) > 0)
{
//Headers
echo "<table border='1' style='width:100%'>";
echo "<tr>";
echo "<th>Image ID</th>";
echo "<th>Lastname</th>";
echo "<th>Firstname</th>";
echo "<th>Email</th>";
echo "<th>PhoneNumber</th>";
echo "</tr>";
//output data of each row
while($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<td>".$row['ID']."</td>";
echo "<td>".$row['LastName']."</td>";
echo "<td>".$row['FirstName']."</td>";
echo "<td>".$row['Email']."</td>";
echo "<td>".$row['PhoneNumber']."</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
}
if (!empty($sfname) && empty($slname) && empty($semail) )
{
$sql = "select * from Userlist where FirstName LIKE '%". $sfname ."%'" ;
checkres();
}
else if (!empty($sfname) && !empty($slname) && empty($semail))
{
$sql = "select * from Userlist where FirstName LIKE '%". $sfname ."%' AND LastName LIKE '%". %slname. "%'";
checkres();
}
else
{
echo "You have not yet entered any values ";
}
mysqli_close($conn);
?>
This is the new one
<form method="post" action="#" id="searchform">
First Name:<br>
<input type="text" name="fname">
<br>Last Name:<br>
<input type="text" name="lname">
<br>Email: <br>
<input type="text" name="email">
<br>
<input type="submit" name="submit" value="Search">
</form>
<?php
$sfname = $_POST["fname"];
$slname = $_POST["lname"];
$semail = $_POST["email"];
$servername = "xxx";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
function checkres()
{
//Get query on the database
$result = mysqli_query($conn, $sql);
//Check results
if (mysqli_num_rows($result) > 0)
{
//Headers
echo "<table border='1' style='width:100%'>";
echo "<tr>";
echo "<th>Image ID</th>";
echo "<th>Lastname</th>";
echo "<th>Firstname</th>";
echo "<th>Email</th>";
echo "<th>PhoneNumber</th>";
echo "</tr>";
//output data of each row
while($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<td>".$row['ID']."</td>";
echo "<td>".$row['LastName']."</td>";
echo "<td>".$row['FirstName']."</td>";
echo "<td>".$row['Email']."</td>";
echo "<td>".$row['PhoneNumber']."</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
}
if(!empty($sfname) || !empty($slname) || !empty($semail)){
$emailQueryPart = !empty($semail) ? "Email LIKE '%$semail%'" : "";
$lastnameQueryPart = !empty($slname) ? "LastName LIKE '%$slname%'" : "";
$firstnameQueryPart = !empty($sfname) ? "FirstName LIKE '%$sfname%'" : "";
$arr = array($emailQueryPart, $lastnameQueryPart,$firstnameQueryPart);
$sql = "select * from Userlist";
for($i = 0; $i < count($arr); $i++){
if(!empty($arr[$i])){
if($i > 0){
$sql.= " AND ".$arr[$i];
}else{
$sql.= " WHERE ".$arr[$i];
}
}
}
}else{
echo "You must enter at least one value";
}
checkres();
mysqli_close($conn);
?>
You have a few errors:
$sql = "select * from Userlist where FirstName LIKE '%". $sfname ."%' AND LastName LIKE '%". %slname. "%'";
You have %slname instead of $slname.
Another mistake is in the program flow. Your else condition, which is saying :"You have not yet entered any values" will be reached in two cases:
When all fields are left blank
When all fields are filled with values.
You don't want that. You have to improve your logic, and build a query based on that, and that can be done like this:
function checkres()
{
//Get query on the database
$result = mysqli_query($conn, $sql);
//Check results
if (mysqli_num_rows($result) > 0)
{
//Headers
echo "<table border='1' style='width:100%'>";
echo "<tr>";
echo "<th>Image ID</th>";
echo "<th>Lastname</th>";
echo "<th>Firstname</th>";
echo "<th>Email</th>";
echo "<th>PhoneNumber</th>";
echo "</tr>";
//output data of each row
while($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<td>".$row['ID']."</td>";
echo "<td>".$row['LastName']."</td>";
echo "<td>".$row['FirstName']."</td>";
echo "<td>".$row['Email']."</td>";
echo "<td>".$row['PhoneNumber']."</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
}
if(!empty($sfname) || !empty($slname) || !empty($semail)){
$emailQueryPart = !empty($semail) ? "Email LIKE '$semail'" : "";
$lastnameQueryPart = !empty($slname) ? "LastName LIKE '%$slname%'" : "";
$firstnameQueryPart = !empty($sfname) ? "FirstName LIKE '%$sfname%'" : "";
$arr = array($emailQueryPart, $lastnameQueryPart,$firstnameQueryPart);
$sql = "select * from Userlist";
for($i = 0; $i < count($arr); $i++){
if(!empty($arr[$i])){
if($i > 0){
$sql.= " AND ".$arr[$i];
}else{
$sql.= " WHERE ".$arr[$i];
}
}
}
}else{
echo "You must enter at least one value";
}
checkres();
mysqli_close($conn);
?>
What you do is in my opinion a little bit confusing (and a little bit odd n terms of the program's flow structure).
You can simply use an array of variables for your input fields and then loop through the array to generate your SQL statement. So your HTML form would look like this:
<form method="post" action="#" id="searchform">
First Name:<br />
<input type="text" name="queryArray[FirstName]" />
<br />Last Name:<br />
<input type="text" name="queryArray[LastName]" />
<br />Email:<br />
<input type="text" name="queryArray[Email]" />
<br />
<input type="submit" name="submit" value="Search" />
</form>
A more clear structure would be if you define these 2 functions, which of course can be placed anywhere in your PHP code block:
function createSql($queryArray) {
if (is_array($queryArray)) {
$sql = null;
foreach ($queryArray as $key => $value) {
if ($value != null ) {
$addQuery = "`".$key."` LIKE '%".$value."%'";
if ($sql == null)
$sql = "SELECT * FROM `Userlist` WHERE ".$addQuery;
else
$sql = $sql." AND ".$addQuery;
}
return $sql;
}
}
function checkres($sql) {
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn)
die("Connection failed: " . mysqli_connect_error());
//Get query on the database
$result = mysqli_query($conn, $sql);
//Check results
if (mysqli_num_rows($result) > 0) {
//Headers
echo "<table border='1' style='width:100%'>";
echo "<tr>";
echo "<th>Image ID</th>";
echo "<th>Lastname</th>";
echo "<th>Firstname</th>";
echo "<th>Email</th>";
echo "<th>PhoneNumber</th>";
echo "</tr>";
//output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>".$row['ID']."</td>";
echo "<td>".$row['LastName']."</td>";
echo "<td>".$row['FirstName']."</td>";
echo "<td>".$row['Email']."</td>";
echo "<td>".$row['PhoneNumber']."</td>";
echo "</tr>";
}
echo "</table>";
} else
echo "0 results";
// Close connection
mysqli_close($conn);
}
Finally you will have to call the functions according to user activity:
if ($_POST != null) {
$sql = createSql($_POST[queryArray]);
checkres($sql);
}
An example how the SQL generation works is listed here
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.