Calling different function for different search Option - php

Dear Friend i have two function and maybe i might have more in the future but the point is that i want when a user searches for hotel based on postal code on the same text field the function
hotel_by_postel_code($textvalue) should be called and when i search based on country then the function
hotel_by_country($textvalue) should be called. the following is the code that should displays the result however it is not displayong the result as it should at all.
<?php require_once("includes/header.php");?>
<?php require_once("includes/connection.php")?>
<?php
if(isset($_POST['submit'])){
$message ="";
$textvalue = $_POST['search'];
if(empty($allhotels = hotel_by_postel_code($textvalue)) || empty($allhotels = hotel_by_country($textvalue))){
$message = "There is no record in the database";
}
}else{
$allhotels = select_all_hotels();
}
?>
<div class="cBoth"></div>
<div id="sep"></div>
<div id="mainContentSection" class="Calign">
<div id="detaillist">
<div id="searching" class="Calign">
<form action="list2.php" method="POST" id="searchForm">
<fieldset>
<input type="text" name="search" />
<input type="submit" name ="submit" value="Search" /></fieldset>
</form>
</div><!--End of searching-->
<?php
if(isset($message)){
echo"<div id=\"listtitle\">";
echo"<h2>".$message."</h2>";
echo"</div>";//End of listtitle div
}else{
echo"<div id=\"listtitle\">";
echo"<h2>Property Name</h2> <h2>Location</h2> <h2>Guest Rating</h2><h2>Hotel Rank</h2><h2>Per night</h2>";
echo"</div>";
}
?><!--End of listtitle-->
<div class="cBoth"></div>
<?php
$i=0;
while($hotels_set = mysql_fetch_array($allhotels)){
$room_rate = rateforhotel($hotels_set['hotel_id']);
if(!empty( $hotels_set['hotel_name']) && ($room_rate['hotel_id'] == $hotels_set['hotel_id'] ) ){
if($i % 2 == 0) { echo "<div id=\"innerlisteven\">"; }
else
{
echo"<div id=\"innerlistodd\">";
}
echo"<h2>". $hotels_set['hotel_name'] ."</h2>";
echo"<h2>". $hotels_set['country'] ."</h2>";
if(!intval($hotels_set['star'])){
echo"<h2>". $hotels_set['star'] ."</h2>";
}else{
echo"<h2>". $hotels_set['star'] . "<img src=\"img/repetimg/star.png\"/></h2>";
}
echo"<h2>". $hotels_set['star'] . "</h2>";
echo"<h2>". $room_rate['rate'] . "</h2>";
echo"</div>";
$i++;
}//end of if()
}//end of hotel while
mysql_close($con);
?>
</div><!--End of details-->
<div id="advertlisting">
<div id="search">search menu</div>
</div><!--End of adverts left-->
</div><!--End of end of maincontent-->
<div class="cBoth"><!-- clear Both--></div>
<?php require_once("includes/footer.php"); ?>
and the following code is the function itself
function hotel_by_country($country){
global $connection;
$query = "SELECT * FROM Hotels WHERE country ='{$country}'";
$hotel_set = mysql_query($query,$connection);
confirm_query($hotel_set);
return $hotel_set;
}
function hotel_by_postel_code($postal){
global $connection;
$query = "SELECT * FROM Hotels WHERE hotel_postal_code ='{$postal}'";
$hotel_set = mysql_query($query,$connection);
confirm_query($hotel_set);
return $hotel_set;
}
function select_all_hotels(){
global $connection;
$query = "SELECT *
FROM Hotels";
$hotel_set = mysql_query($query,$connection);
confirm_query($hotel_set);
return $hotel_set;
}

You're missing closing (right) brackets ) of the empty functions - one before the OR and one at the end of the condition). Change:
if(empty($allhotels = hotel_by_postel_code($textvalue) OR empty($allhotels = hotel_by_country($textvalue))
to:
if(empty($allhotels = hotel_by_postel_code($textvalue)) OR empty($allhotels = hotel_by_country($textvalue))){
Next, I would break this line into a few lines:
$allhotels1 = hotel_by_postel_code($textvalue);
$allhotels2 = hotel_by_country($textvalue);
echo "allhotels1 = $allhotels1; allhotels1 = $allhotels1\n";//for debug
if(empty($allhotels1) OR empty($allhotels2){...
and one last thing - are you sure it should be OR and not AND ?

if(is_numermic($textvalue))
hotel_by_postel_code($textvalue)
else
hotel_by_country($textvalue)

I think your problem lies in this code
if(empty($allhotels = hotel_by_postel_code($textvalue)) || empty($allhotels = hotel_by_country($textvalue))){
$message = "There is no record in the database";
}
First you fill $allhotels with hotel_by_postel_code($textvalue). Then you overwrite it with $allhotels = hotel_by_country($textvalue).
Also, you should replace the || with && because you only want the message when both functions return no values.
Try
$allhotels = hotel_by_postel_code($textvalue);
if(empty($allhotels)) {
$allhotels = hotel_by_country($textvalue);
if(empty($allhotels)) {
$message = "There is no record in the database";
}
}

After many trail and error i was able to come to the solution and the following is the best option i found maybe in the future someone my come up with the same problem. one thing to keep in mind is that the options in IF and Else can easily be moved into a function on separate file. and i also added one more Html menu to select the type of option i am search for in this case it is the filter menu.
<?php
error_reporting(E_ALL);
ini_set('display_errors','1');?>
<?php require_once("includes/header.php");?>
<?php require_once("includes/connection.php")?>
<?php
if(isset($_POST['search']) && $_POST['search']!= "") {
if($_POST['filter'] == "HotelName"){
$search = $_POST['search'];
$sqlquery = "SELECT * FROM Hotels WHERE hotel_name LIKE '%$search%' OR description LIKE '%$search%'";
$allhotels = mysql_query($sqlquery, $connection) or die("Sorry Something wrong".mysql_error());
}else if($_POST['filter'] == "country"){
$search = $_POST['search'];
$sqlquery = "SELECT * FROM Hotels WHERE country LIKE '%$search%' OR hotel_address LIKE '%$search%'";
$allhotels = mysql_query($sqlquery, $connection) or die("Sorry Something wrong".mysql_error());
}else if($_POST['filter'] == "Postal"){
$search = $_POST['search'];
$sqlquery = "SELECT * FROM Hotels WHERE hotel_postal_code LIKE '%$search%'";
$allhotels = mysql_query($sqlquery, $connection) or die("Sorry Something wrong".mysql_error());
}
}
?>
<div class="cBoth"></div>
<div id="sep"></div>
<div id="mainContentSection" class="Calign">
<div id="detaillist">
<div id="searching" class="Calign">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" id="searchForm">
<fieldset>
<input type="text" name="search" />
<select name="filter">
<option value="HotelName">Hotel Name</option>
<option value="country">Country</option>
<option value="Postal">Postal Code</option>
</select>
<input type="submit" name ="submit" value="Search" />
</fieldset>
</form>
</div><!--End of searching-->
<div id="listtitle">
<h2>Property Name</h2> <h2>Location</h2><h2>Hotel Rank</h2><h2>Guest Rating</h2><h2>Per night</h2>
</div><!--End of listtitle-->
<div class="cBoth"></div>
<?php
if(!isset($allhotels)){
$allhotels = select_all_hotels();
}
$i=0;
while($hotels_set = mysql_fetch_array( $allhotels)){
$room_rate = rateforhotel($hotels_set['hotel_id']);
if(!empty( $hotels_set['hotel_name']) && ($room_rate['hotel_id'] == $hotels_set['hotel_id'] ) ){
if($i % 2 == 0) { echo "<div id=\"innerlisteven\">"; }
else
{
echo"<div id=\"innerlistodd\">";
}
echo"<h2><a href=\"desti_list.php?details=" . urlencode($hotels_set["hotel_id"]).
"\">" . $hotels_set['hotel_name'] ."</a></h2>";
echo"<h2>". $hotels_set['country'] ."</h2>";
if(!intval($hotels_set['star'])){
echo"<h2>". $hotels_set['star'] ."</h2>";
}else{
echo"<h2>". $hotels_set['star'] . "<img src=\"img/repetimg/star.png\"/></h2>";
}
echo"<h2>". $hotels_set['star'] . "</h2>";
echo"<h2>". $room_rate['rate'] . "</h2>";
echo"</div>";
$i++;
/*
echo"<h3><a href=\"desti_list.php?details=" . urlencode($hotels_set["hotel_id"]).
"\">Find Out More</a></span></h3>";
*/
}//end of if()
}//end of hotel while
mysql_close($connection);
?>
</div><!--End of details-->
<div id="advertlisting">
<div id="search">search menu</div>
</div><!--End of adverts left-->
</div><!--End of end of maincontent-->
<div class="cBoth"><!-- clear Both--></div>
<?php require_once("includes/footer.php"); ?>

Related

PHP How to show all results from db if the user selects "ALL" option from select list options

Hi :) I have a form that contains select lists and search button to show result from the database in a table. The first option of all my select lists are "ALL" (This is not from the database! Basically it supposes to bring all data from the database when user clicks Search without selecting any specific option). The current code works fine if I select real options (not the first option "ALL"). My question is: How to bring all the data if the user selects "ALL" in one select list, or in all select lists?
<!-- Search Components -->
<div class="row">
<form action="search.php" method="POST" name="" class="text-center">
<!-- Username -->
<div class="form-group col-sm-6 col-md-4">
<?php
include("dbc.php");
$qq = "SELECT DISTINCT username FROM users ORDER BY username";
$rr = mysqli_query($dbc,$qq);
while ($row = mysqli_fetch_array($rr)){
$username_array[] = $row['username'];
}
echo '<select class="form-control border-input" name="username">';
echo '<option value="all">ALL</option>';
foreach($username_array as $user){
$selected = '';
if($_POST['username'] == $user) {
$selected = 'selected="selected"';
}
echo '<option value="'.$user.'"'.$selected.'>'.$user.'</option>';
}
echo '</select>';
?>
</div>
<!-- Hospital Sections -->
<div class="form-group col-sm-6 col-md-4">
<?php
include("dbc.php");
$qqq = "SELECT DISTINCT section_name FROM hospital_sections ORDER BY section_name";
$rrr = mysqli_query($dbc,$qqq);
while ($row = mysqli_fetch_array($rrr)){
$sections_array[] = $row['section_name'];
}
echo '<select class="form-control border-input" name="section_name">';
echo '<option value="all">ALL</option>';
foreach($sections_array as $sec){
$selected = '';
if($_POST['section_name'] == $sec) {
$selected = 'selected="selected"';
}
echo '<option value="'.$sec.'"'.$selected.'>'.$sec.'</option>';
}
echo '</select>';
?>
</div>
<!-- Room Number -->
<!-- Qeblah Status -->
<div class="form-group col-sm-6 col-md-4">
<select class="form-control border-input" name="qeblah_status">
<option <?php if($_POST['qeblah_status'] == "ALL") echo 'selected="selected"'; ?> value="all">ALL</option>
<option <?php if($_POST['qeblah_status'] == "yes") echo 'selected="selected"'; ?> value="yes">Yes</option>
<option <?php if($_POST['qeblah_status'] == "no") echo 'selected="selected"'; ?> value="no">No</option>
</select>
</div>
<!-- Prayer Painting -->
<div class="form-group col-sm-6 col-md-4">
<select class="form-control border-input" name="prayer_painting">
<option <?php if($_POST['prayer_painting'] == "ALL") echo 'selected="selected"'; ?> value="all">ALL</option>
<option <?php if($_POST['prayer_painting'] == "yes") echo 'selected="selected"'; ?> value="yes">Yes</option>
<option <?php if($_POST['prayer_painting'] == "no") echo 'selected="selected"'; ?> value="no">No</option>
</select>
</div>
<!-- Fatwah -->
<div class="form-group col-sm-6 col-md-4">
<select class="form-control border-input" name="fatwa_status">
<option <?php if($_POST['fatwa_status'] == "ALL") echo 'selected="selected"'; ?> value="all">ALL</option>
<option <?php if($_POST['fatwa_status'] == "yes") echo 'selected="selected"'; ?> value="yes">Yes</option>
<option <?php if($_POST['fatwa_status'] == "no") echo 'selected="selected"'; ?> value="no">No</option>
</select>
</div>
<!-- Search Button -->
<div class="form-group col-sm-6 col-md-4">
<button type="submit" class="form-control btn btn-success btn-fill btn-wd" name="submit" value="Search"><i class="ti-search"></i> Search </button>
</div>
</form>
</div> <!-- .row Ends -->
<!-- Search Components Ends -->
<hr>
<!-- Search Results -->
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$username = $_POST['username'];
$section_name = $_POST['section_name'];
$qeblah_status = $_POST['qeblah_status'];
$prayer_painting = $_POST['prayer_painting'];
$fatwa_status = $_POST['fatwa_status'];
?>
<!-- The Table -->
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="content table-responsive table-full-width">
<table class="table table-striped table-bordered" style="border-style: hidden;">
<thead>
<th>Username</th>
<th>Section Name</th>
<th>Room Number</th>
<th>Qeblah</th>
<th>Prayer Painting</th>
<th>Fatwah</th>
<th>Condition</th>
</thead>
<tbody>
<?php
$selected_username = "";
if($username != 'All'){
$selected_username = "username = '$username'";
}
$selected_section_name = "";
if($section_name != 'All'){
$selected_section_name = "section_name = '$section_name'";
}
$selected_qeblah_status = "";
if($qeblah_status != 'All'){
$selected_qeblah_status = "qeblah_status = '$qeblah_status'";
}
$selected_prayer_painting = "";
if($prayer_painting != 'All'){
$selected_prayer_painting = "prayer_painting = '$prayer_painting'";
}
$selected_fatwa_status = "";
if($fatwa_status != 'All'){
$selected_fatwa_status = "fatwa_status = '$fatwa_status'";
}
include("dbc.php");
$q = "SELECT * FROM reports WHERE $selected_username AND $selected_section_name AND $selected_qeblah_status AND $selected_prayer_painting AND $selected_fatwa_status";
$r = mysqli_query($dbc, $q);
while ($row = mysqli_fetch_array($r)){
echo "<tr>";
echo "<td>".$row['username']."</td>";
echo "<td>".$row['section_name']."</td>";
echo "<td>".$row['room_number']."</td>";
echo "<td>".$row['qeblah_status']."</td>";
echo "<td>".$row['prayer_painting']."</td>";
echo "<td>".$row['fatwa_status']."</td>";
echo "<td>".$row['report_status']."</td>";
echo "</tr>";
}
?>
</tbody>
</table>
</div> <!-- .content Ends -->
</div> <!-- .card Ends -->
</div> <!-- .col-md-12 Ends -->
</div> <!-- .row Ends -->
}
<!-- Search Results Ends -->
</div> <!-- .container-fluid Ends -->
</div> <!-- .content Ends -->
Instead of suggesting solutions, I had a go at the code myself. I modified the page a bit to make it work without a database. The important part is the bottom section.
I took out the table formatting, what I concentrated on is to build the query dynamicly based on the users's choice. To understand:
when a user selects ALL, there is nothing to filter on, so it is not even mentioned in the $query.
If a user selects ALL for all the fields, there is no need for a WHERE clause in the query ($query remains empty).
In a user selects more than one field to be other than ALL, each WHERE item must be separated by "AND". So we must add "AND" in the $query.
So the code I produced and tested is this (the bottom section, I did not change the rest):
<div class="content table-responsive table-full-width">
<?php
$where = "";
$query = "";
if($username != 'all'){
$query = "username = '$username'";
$where = "WHERE ";
}
if($section_name != 'all'){
if (strlen($query) != 0)
{
$query = $query . " AND ";
}
$query = $query . "section_name = '$section_name'";
$where = "WHERE ";
}
if($qeblah_status != 'all'){
if (strlen($query) != 0)
{
$query = $query . " AND ";
}
$query = $query . "qeblah_status = '$qeblah_status'";
$where = "WHERE ";
}
if($prayer_painting != 'all'){
if (strlen($query) != 0)
{
$query = $query . " AND ";
}
$query = $query . "prayer_painting = '$prayer_painting'";
$where = "WHERE ";
}
if($fatwa_status != 'all'){
if (strlen($query) != 0)
{
$query = $query . " AND ";
}
$query = $query . "fatwa_status = '$fatwa_status'";
$where = "WHERE ";
}
$q = "SELECT * FROM reports $where $query";
echo "<h1>$q</h1>\n";
?>
</div>
So your query changes dynamically. You can then run it and display the output.
Hope this helps!
The way I understand your question, you want to modify your $q query for items that are selected as "ALL".
The query limits the number of returned values in the WHERE part of it. So if a user selects ALL, just remove that part of query.
I will do for the username part, you can use the same concept for the rest:
$username_part = "";
if ($username != 'ALL')
{
$username_part = "username = '$username' AND";
}
$q = "SELECT * FROM reports WHERE $username_part section_name = '$section_name' AND qeblah_status = '$qeblah_status' AND prayer_painting = '$prayer_painting' AND fatwa_status = '$fatwa_status'";
This way, if a user selects ALL, you do not specify a WHERE condition on it. You just take it all. If a user selects one value, it adds a condition in the WHERE, based on the user's selection.
Managing the results of such queries is left to you :-)
Obviously, if the username is named "ALL", you have a problem :-)

Is my statement not updating because of the way I have it layed out?

This "page" is part of many that are all linked together using includes, but because I can't make it work I'm going straight to the url that relates to this exact page, and I still can't make it work, or figure out why.
What is supposed to happen, is the query checks if that stock is in the db, if it is, echo the values of the row, and if a submit button is pressed update the db based on the input values. If it's not in, echo the blank form, and if a submit button gets pressed insert into the db. I can't get either update or insert to work.
I'm going to post the entire page (minus the mysql connect,) so hopefully someone can spot an error.
<?php
$status = 'Active';
$stock = (isset($_GET['stock'])) ? $_GET['stock'] : '';
$cat = (isset($_GET['cat'])) ? $_GET['cat'] : '';
include ('../helper_content/title_data.php');
/* WHAT CATEGORY DO WE WANT? */
if($cat == "Sales") {
$table = "Titles";
if($stock) {$where = "stock = $stock";}
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$status = $status;
$title_status = mysqli_real_escape_string($conn,$_POST['title_status']);
$title_number = mysqli_real_escape_string($conn,$_POST['title_number']);
$title_location = mysqli_real_escape_string($conn,$_POST['title_location']);
$title_owners = mysqli_real_escape_string($conn,$_POST['title_owners']);
$stock = $_GET['stock'];
}
}
/* Begin Main Query */
$sql5 = "SELECT * FROM `$table` WHERE $where";
$result5 = $conn->query($sql5);
if ($result5->num_rows > 0) {
// Stock exists, so submit will Update dB
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if ($update = $conn->prepare("UPDATE `Titles` SET status=?, title_status=?, title_number=?, title_location=?, title_owners=? WHERE stock=?")){
$update->bind_param('ssssii', $status, $title_status, $title_number, $title_location, $title_owners, $stock);
$update->execute();
};
if ($update->execute == TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating: " . $update->error;
}
}
// Display the HTML results
while($row5 = $result5->fetch_assoc()) {
echo "Found In Database";
// Title Number
$title_number = 'value="'.$row5['title_number'].'"';
$TitleStatus = $row5['title_status'];
$TitleLocation = $row5['title_location'];
$Owners = $row5['owners'];
}
} else {
// No Query Results Found
echo "Not Found In Database";
// Insert into dB
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if ($add = $conn->prepare("INSERT INTO `Titles` status=?, title_status=?, title_number=?, title_location=?, title_owners=? WHERE stock=?")){
$add->bind_param('ssssii', $status, $title_status, $title_number, $title_location, $title_owners, $stock);
$add->execute();
};
if ($add->execute == TRUE) {
echo "Record added into database";
} else {
echo "Error adding: " . $add->error;
}
}
/* End Main Query */
}
// Title Status
foreach($title_statuses as $title_status){
$selected = ($TitleStatus == $title_status) ? ' selected="selected"' : '';
$Title_status .= '<option value="'.$title_status.'"'.$selected.'>'.$title_status.'</option>';
}
// Title Location
foreach($title_locations as $title_location){
$selected = ($TitleLocation == $title_location) ? ' selected="selected"' : '';
$Title_location .= '<option value="'.$title_location.'"'.$selected.'>'.$title_location.'</option>';
}
// Prior Owners
foreach($prior_owners as $owners){
$selected = ($Owners == $owners) ? ' selected="selected"' : '';
$Owners_drop .= '<option value="'.$owners.'"'.$selected.'>'.$owners.'</option>';
}
?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>?stock=<?php echo $stock; ?>">
<section class="title">
<h3>Title Info - Stock #:<?php echo $stock; ?></h3>
<p>
<label for="title_number" class="inline-edit">Title Num</label>
<input type="text" name="title_number" id="title_number" size="20" spellcheck="false" <?php echo $title_number; ?>>
</p>
<p>
<label for="title_status" class="inline-edit">Status</label>
<select name="title_status" id="title_status">
<option></option>
<?php echo $Title_status; ?>
</select>
</p>
<p>
<label for="title_location" class="inline-edit">Location</label>
<select name="title_location" id="title_location">
<option></option>
<?php echo $Title_location; ?>
</select>
</p>
<p>
<label for="title_owners" class="inline-edit">Owners</label>
<select name="title_owners" id="title_owners">
<option></option>
<?php echo $Owners_drop; ?>
</select> <a target="_blank" href="https://www.vehiclehistory.com/paging-vin-report-data/specifications.php?vin=<?php echo $vin; ?>"><i class="fa fa-history" aria-hidden="true" title="Vehicle History"></i></a>
</p>
</section>
<input type="submit" id="Submit" value="Submit">
</form>
I would start by organizing your code a little differently. You have one of two things that can be true: either the form was submitted (a POST request), or the page was requested via URL (a GET request). So, start with this:
<?php
# Data for dropdowns
include ('../helper_content/title_data.php');
$error = array();
$status = "Active";
$title_number = "";
$title_status = "";
$title_location = "";
$title_owners = "";
$vin = "";
# Was the form submitted via POST?
if(isset($_POST['Submit']))
{
# Yes
# Is this a new stock item?
if(empty($_POST['stock']))
{
# Yes - insert
/*
... get your variables from the $_POST array
*/
$title_number = filter_var($_POST['title_number'], FILTER_SANITIZE_STRING);
# ... repeat for other variables
if ($stmt = $conn->prepare("INSERT INTO `Titles` (`status`,`title_status`,`title_number`,`title_location`,`title_owners`) VALUES (?,?,?,?,?)"))
{
$stmt->bind_param('ssssii', $status, $title_status, $title_number, $title_location, $title_owners);
if ($stmt->execute())
{
$stmt->close();
header('Location: ./?inserted=true');
exit();
}
else
{
$error[] = "Error adding: " . $stmt->error;
$stmt->close();
}
}
}
else
{
# No - update
$stock = $_POST['stock'];
/*
... get your variables from the $_POST array
*/
if ($stmt = $conn->prepare("UPDATE `Titles` SET status=?, title_status=?, title_number=?, title_location=?, title_owners=? WHERE stock=?"))
{
$stmt->bind_param('ssssii', $status, $title_status, $title_number, $title_location, $title_owners, $stock);
if ($stmt->execute())
{
$stmt->close();
header('Location: ./?updated=true');
exit();
}
else {
$error[] = "Error updating: " . $stmt->error;
$stmt->close();
}
}
}
}
else
{
# No - assume a GET
$status = 'Active';
$stock = $_GET['stock'];
$cat = $_GET['cat'];
if(isset($_GET['updated']))
{
$message = "Record updated";
}
else if(isset($_GET['inserted']))
{
$message = "Record added into database";
}
if($stock != "")
{
# Load the item?
$query = "SELECT * FROM `Sales` WHERE stock=?";
$stmt = $conn->prepare($query);
$stmt->bind_param('s', $stock);
if($stmt->execute())
{
$result = $stmt->get_result();
if($result)
{
$row = $result->fetch_assoc();
$title_number = $row['title_number'];
$title_status = $row['title_status'];
$title_location = $row['title_location'];
}
}
$stmt->close();
}
}
?>
<?php if(isset($message)) : ?>
<div class="alert alert-success">
<?= $message ?>
</div>
<?php endif; ?>
<?php if(isset($error)) : ?>
<div class="alert alert-danger">
<ul>
<?php foreach($error as $err): ?>
<li><?= $err ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<form method="POST" action="<?= $_SERVER['PHP_SELF']; ?>">
<section class="title">
<h3>Title Info - Stock #:<?= $stock; ?></h3>
<input type="hidden" name="stock" value="<?= $stock; ?>" />
<p>
<label for="title_number" class="inline-edit">Title Num</label>
<input type="text" name="title_number" id="title_number" size="20" spellcheck="false" value="<?= $title_number; ?>" />
</p>
<p>
<label for="title_status" class="inline-edit">Status</label>
<select name="title_status" id="title_status">
<option></option>
<?php foreach($title_statuses as $option): ?>
<option <?= $option == $title_status) ? 'selected="selected"' : '' ?>><?= $option ?></li>
<?php endforeach; ?>
</select>
</p>
<p>
<label for="title_location" class="inline-edit">Location</label>
<select name="title_location" id="title_location">
<option></option>
<!-- Repeat the same process as $title_statuses -->
</select>
</p>
<p>
<label for="title_owners" class="inline-edit">Owners</label>
<select name="title_owners" id="title_owners">
<option></option>
<!-- Repeat the same process as $title_statuses -->
</select>
<a target="_blank" href="https://www.vehiclehistory.com/paging-vin-report-data/specifications.php?vin=$vin">
<i class="fa fa-history" aria-hidden="true" title="Vehicle History"></i>
</a>
</p>
</section>
<input type="submit" id="Submit" value="Submit" />
</form>
Here's a partial re-implementation of your page. I'm starting with the assumption that a stock number was part of the requesting URL, and looking that value up. I (for the moment) am ignoring loading the dropdown values in favor of getting a basic lookup to work.
You'll also notice I've switched to using shorttags in your markup - this is generally a more concise method of templating than sprinkling echos all over the place.
I've added a partial implementation of some save logic. You'll also notice that I added a hidden input to your form - you don't want to rely on a query string value when posting a form.
The code stores some simple error messages in an array, which gets echoed out if the insert or update fails. If successful, we redirect back to the same page with a simple flag variable, which we read on that request to know if we need to display an informational message. This is known as POST-REDIRECT-GET, and prevents users from accidentally (or purposefully) resubmitting the same form data over and over.

PHP Stuck on Mysqli_error()

I am new to php still learning i have made a navigation with the drop down submenus its working when im inserting new item in navigation but the problem exist when i try to edit the same navigation i get the error in function everything seems fine need help.
![Edit Form][1]
Error:
<code>
Database Query Failed in get subject by idYou have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LIMIT 1' at line 1
</code>
functions.php
<code>
// Get Subject By ID
function get_subject_by_id($subject_id){
global $connection;
$query = "SELECT * FROM subjects WHERE id = {$subject_id} LIMIT 1";
$result_set = mysqli_query($connection, $query);
if(!$result_set){
die("Database Query Failed in get subject by id" . mysqli_error($connection));
}
if($subject_data = mysqli_fetch_array($result_set)) {
return $subject_data;
} else {
return null;
}
}
</code>
edit_subject.php
<code>
<?php include('includes/connection.php'); ?>
<?php require_once('includes/functions.php'); ?>
<?php
if(isset($_POST['submit'])) {
$id = $_GET['subj'];
$menu_name = $_POST['menu_name'];
$position = $_POST['position'];
$visible = $_POST['visible'];
$content = $_POST['content'];
$query = "UPDATE subjects SET menu_name = '{$menu_name}', position = {$position}, visible = {$visible}, content = '{$content}' WHERE id = {$id}";
$result_update = mysqli_query($connection, $query);
if(mysqli_affected_rows($connection) == 1){
$message = "The Subject was successfully created.";
} else {
}
}
?>
<?php
if(isset($_GET['subj'])){
$sel_subject = get_subject_by_id($_GET['subj']);
$sel_page = NULL;
} elseif (isset($_GET['page'])) {
$sel_subject = NULL;
$sel_page = get_page_by_id($_GET['page']);
} else {
$sel_subject = NULL;
$sel_page = NULL;
}
?>
<?php include('includes/header.php'); ?>
<div class="sidebar">
<ul class="sideNav">
<?php
$query_sub = "SELECT * FROM subjects";
$subject_set = mysqli_query($connection, $query_sub);
if(!$subject_set){
die("Database Query Failed1");
}
while($subject = mysqli_fetch_array($subject_set)){
?>
<li><?php echo $subject["menu_name"]; ?>
<?php
$query_page = "SELECT * FROM pages WHERE subject_id = {$subject["id"]}";
$page_set = mysqli_query($connection, $query_page);
if(!$page_set){
die("Database Query Failed2");
} ?>
<ul>
<?php
while($page = mysqli_fetch_array($page_set))
{
?><li><?php echo $page["menu_name"]; ?></li><?php
} ?>
</ul>
</li>
<?php } ?>
</ul>
<br>
+ Add a new Subject
</div><!-- end of sidebar -->
<h2>Edit Subject: <?php echo $sel_subject['menu_name']; ?></h2>
<div class="main">
<br/> <br/>
<?php if(!empty($message)) { ?> <p><?php echo $message; ?></p> <?php } ?>
<form action="edit_subject.php?subj=<?php $sel_subject['id']; ?>" method="post">
<fieldset>
<legend>Edit Subject:</legend>
<p>Subject Name:
<input type="text" name="menu_name" value="<?php echo $sel_subject['menu_name']; ?>">
</p>
<p>Position:
<select name="position">
<?php
$query_opt = "SELECT * FROM subjects ORDER BY position ASC";
$subject_opt = mysqli_query($connection, $query_opt);
if(!$subject_opt){
die("Database Query Failed3");
}
$subject_count = mysqli_num_rows($subject_opt);
for($count=1; $count <= $subject_count+1; $count++){
echo "<option value=\"{$count}\"";
if($sel_subject['position'] == $count){
echo " selected";
}
echo ">{$count}</option>";
}
?>
</select>
</p>
<p>Visible:
<input type="radio" name="visible" value="0"<?php if($sel_subject['visible'] == 0){ echo " checked"; } ?>> No
<input type="radio" name="visible" value="1"<?php if($sel_subject['visible'] == 1){ echo " checked"; } ?>> Yes
</p>
<p>Content:<br/>
<textarea name="content" rows="20" cols="150"><?php echo $sel_subject['content']; ?></textarea>
</p>
<p>
<input type="submit" name="submit" value="Add Subject" class="button-submit">
</p>
</fieldset>
</form>
<br /><br />
</div><!-- end of main -->
<?php include('includes/footer.php'); ?>
</code>
Are you sure that $subject_id in function get_subject_by_id() is not empty ? Try the below code after $query = "SELECT * FROM subjects WHERE id = {$subject_id} LIMIT 1"; in functions.php (only for testing) and make sure that your query is correct.
echo $query;
die();
you've missed the single quotes in the query string.
$query = "SELECT * FROM subjects WHERE id = {$subject_id} LIMIT 1";
should be
$query = "SELECT * FROM subjects WHERE id = '{$subject_id}' LIMIT 1";
youve also done it here.
$query = "UPDATE subjects SET menu_name = '{$menu_name}', position = {$position}, visible = {$visible}, content = '{$content}' WHERE id = {$id}";
should be
$query = "UPDATE subjects SET menu_name = '{$menu_name}', position = '{$position}', visible = '{$visible}', content = '{$content}' WHERE id = '{$id}'";
a note you dont need to wrap in {} for simple variables. You only need them if calling complex variables such as {$array['test']} as expained in this answer

edit_subject.php is not working, the error is saying about database query failed

This is kind of the error I'm getting:
Database query failed.
I've uploaded this webpage: http://widgetcorp.bugs3.com/public/edit_subject.php?subject=1
Here's my file:
<?php require_once("../includes/session.php"); ?>
<?php require_once("../includes/db_connection.php"); ?>
<?php require_once("../includes/functions.php"); ?>
<?php require_once("../includes/validation_functions.php"); ?>
<?php find_selected_page(); ?>
<?php
if (!$current_subject)
{
// subject ID was missing or invalid or
// subject couldn't be found in database
redirect_to("manage_content.php");
}
?>
<?php
if (isset($_POST['submit']))
{
// validations
$required_fields = array("menu_name", "position", "visible");
validate_presences($required_fields);
$fields_with_max_lengths = array("menu_name" => 30);
validate_max_lengths($fields_with_max_lengths);
if (empty($errors))
{
// Perform Update
$id = $current_subject["id"];
$menu_name = mysql_prep($_POST["menu_name"]);
$position = (int) $_POST["position"];
$visible = (int) $_POST["visible"];
$query = "UPDATE subjects SET ";
$query .= "menu_name='{$menu_name}', ";
$query .= "position={$position}, ";
$query .= "visible={$visible} ";
$query .= "WHERE id={$id} ";
$query .= "LIMIT 1";
$result = mysqli_query($connection, $query);
if ($result && mysqli_affected_rows($connection) >= 0)
{
// Success
$_SESSION["message"] = "Subject updated.";
redirect_to("manage_content.php");
}
else
{
// Failure
$message = "Subject update failed.";
}
}
}
// else
// {
// // This is probably a GET request
// }
?>
<?php include("../includes/layouts/header.php"); ?>
<div id="main">
<div id="navigation">
<?php
echo navigation($current_subject, $current_page);
?>
</div>
<div id="page">
<?php
// echo message();
// $message is just a variable, doesn't use the SESSION
if(!empty($message))
{
echo "<div class=\"message\">" . htmlentities($message) . "</div>";
}
?>
<?php echo form_errors($errors); ?>
<h2>Edit Subject: <?php echo htmlentities($current_subject["menu_name"]); ?></h2>
<form action="edit_subject.php?subject=<?php echo htmlentities($current_subject["menu_name"]); ?>" method="post">
<p>Menu name:
<input type="text" name="menu_name" value="<?php echo htmlentities($current_subject["menu_name"]); ?>" />
</p>
<p>Position:
<select name="position">
<?php
$subject_set = find_all_subjects();
$subject_count = mysqli_num_rows($subject_set);
for ($count=1; $count <= $subject_count; $count++)
{
echo "<option value=\"{$count}\"";
if ($current_subject["position"] == $count)
{
echo " selected";
}
echo ">{$count}</option>";
}
?>
</select>
</p>
<p>Visible:
<input type="radio" name="visible" value="0" <?php if ($current_subject["visible"] == 0) { echo "checked"; } ?> /> No
<input type="radio" name="visible" value="1" <?php if ($current_subject["visible"] == 1) { echo "checked"; } ?> /> Yes
</p>
<input type="submit" name="submit" value="Edit Subject" />
</form>
<br />
Cancel
Delete Subject
</div>
The problem is somewhere else and not with your UPDATE query actually. If you see the link you posted, you are passing subject parameter with url, whose value is 1 which is integer.
Now when you click submit it's changing the url to http://widgetcorp.bugs3.com/public/edit_subject.php?subject=About%20Widget%20Corp .
Here as you see the subject parameter is not integer but string value name of subject. And that is causing the problem.
You are getting error as it's not retrieving the subject data from database correctly because of wrong id type. You just need to make sure the form is being posted to right url, which would be http://widgetcorp.bugs3.com/public/edit_subject.php?subject=1.
You need to correct the action parameter on the <form> tag for that.
Look for the line below in your code:
<form action="edit_subject.php?subject=<?php echo htmlentities($current_subject["menu_name"]); ?>" method="post">
And change it to
<form action="edit_subject.php?subject=<?php echo htmlentities($current_subject["id"]); ?>" method="post">
If you see, now the form will be submitted to http://widgetcorp.bugs3.com/public/edit_subject.php?subject=1, which is the correct url.

PHP if option is selected, selected option can't selected again in other chooses

Hello my name is Patrick and this is my first question, i'm sorry but i'm not very good in PHP. probably there are more improvements but this post is for the questions. (but improvements are also welcome)
Question:
You can choose a team of 2 monsters // The monster are selected form database
The question is: if you choose 1 monster how can i fix that you can't choose the same monster on option 2?
PHP CODE:
Action of the 2 sumbit buttons
<?php
session_start();
include("header.php");
if(!isset($_SESSION['uid'])){
echo "You must be logged in to view this page!";
}else{
if (isset($_POST['save'])) {
if ($_POST['save'] == 'keuze4') {
$fuelQuery4 = sprintf("UPDATE user_team SET `m_keuze4` = '%s' WHERE `id`='".$_SESSION['uid']."' ",
mysql_real_escape_string($_POST['option4']));
$Result = mysql_query($fuelQuery4);
if($Result){
echo 'Team is aangepast!';
}
} elseif ($_POST['save'] == 'keuze5'){
$fuelQuery5 = sprintf("UPDATE user_team SET `m_keuze5` = '%s' WHERE `id`='".$_SESSION['uid']."' ",
mysql_real_escape_string($_POST['option5']));
$Result = mysql_query($fuelQuery5);
if($Result){
echo 'Team is aangepast!';
}
}
echo '';}
?>
Get the monsters form database and put it in a select list
<?php
$get=mysql_query("SELECT * FROM user_monsters WHERE `id`='".$_SESSION['uid']."' ORDER BY usid ASC");
$option4 = '';
while($row = mysql_fetch_assoc($get))
{
$option4 .= '<option value = "'.$row['usid'].'">'.$row['usid'].' - '.$row['monster'].' - '.$row['type'].'</option>';
}
?>
Show the selected item
<?php
$k4 = mysql_query("
SELECT user_team.m_keuze4, user_monsters.usid, user_monsters.monster, user_monsters.type, user_monsters.attack, user_monsters.defense
FROM user_team
INNER JOIN user_monsters
ON user_team.m_keuze4=user_monsters.usid
ORDER BY user_monsters.type;
");
while($row4 = mysql_fetch_assoc($k4))
{
$k4_1 = ''.$row4['m_keuze4'].' - '.$row4['monster'].' - '.$row4['type'].' - '.$row4['attack'].' - '.$row4['defense'].'';
}
?>
Option 5 is the same code as 4:
<?php
$get=mysql_query("SELECT * FROM user_monsters WHERE `id`='".$_SESSION['uid']."' ORDER BY usid ASC");
$option5 = '';
while($row = mysql_fetch_assoc($get))
{
$option5 .= '<option value = "'.$row['usid'].'">'.$row['usid'].' - '.$row['monster'].' - '.$row['type'].'</option>';
}
?>
<?php
$k5 = mysql_query("
SELECT user_team.m_keuze5, user_monsters.usid, user_monsters.monster, user_monsters.type, user_monsters.attack, user_monsters.defense
FROM user_team
INNER JOIN user_monsters
ON user_team.m_keuze5=user_monsters.usid
ORDER BY user_monsters.type;
");
while($row5 = mysql_fetch_assoc($k5))
{
$k5_1 = ''.$row5['m_keuze5'].' - '.$row5['monster'].' - '.$row5['type'].' - '.$row5['attack'].' - '.$row5['defense'].'';
}
?>
The Form
<form action="team.php" method="post">
<select name="option4">
<?php echo $option4; ?>
</select><br><br>Keuze 4
<?php
echo $k4_1;
?><br><br>
<input type="submit" name="save" value="keuze4"/>
</form>
<form action="team.php" method="post">
<select name="option5">
<?php echo $option5; ?>
</select><br><br>Keuze 5
<?php
echo $k5_1;
?><br><br>
<input type="submit" name="save" value="keuze5"/>
</form>
In php the best you can do check the option once its posted:
if (isset($_POST['save'])) {
if (filter_input(INPUT_POST,'option4') == filter_input(INPUT_POST,'option5')){
echo "Sorry. You can't select the same monster twice";
}else{
//your db insert logic goes here
}
}
It would be a good idea to also include some javascript to alert the user before they submit the form. This example uses jQuery
$('[name="option4"],[name="option5"]').change(function(){
if ($('[name="option4"]').val() == $('[name="option5"]').val()){
alert('you already chose that monster, please choose another');
}
});
The Form
<form action="team.php" method="post">
<select name="option4">
<?php echo $option4; ?>
</select><br><br>Keuze 4
<?php
echo $k4_1;
?><br><br>
<input type="submit" name="save" value="keuze4"/>
</form> <!-- remove this line-->
<form action="team.php" method="post"> <!-- and this line-->
<select name="option5">
<?php echo $option5; ?>
</select><br><br>Keuze 5
<?php
echo $k5_1;
?><br><br>
<input type="submit" name="save" value="keuze5"/>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(function () {
$('[name="option4"],[name="option5"]').change(function () {
if ($('[name="option4"]').val() == $('[name="option5"]').val()) {
alert('you already chose that monster, please choose another');
}
});
});
</script>
Action of the 2 sumbit buttons
if (isset($_POST['save'])) {
if (filter_input(INPUT_POST, 'option4') == filter_input(INPUT_POST, 'option5')) {
echo "Sorry. You can't select the same monster twice";
} else {
if ($_POST['save'] == 'keuze4') {
$fuelQuery4 = sprintf("UPDATE user_team SET `m_keuze4` = '%s' WHERE `id`='" . $_SESSION['uid'] . "' ", mysql_real_escape_string($_POST['option4']));
$Result = mysql_query($fuelQuery4);
if ($Result) {
echo 'Team is aangepast!';
}
} elseif ($_POST['save'] == 'keuze5') {
$fuelQuery5 = sprintf("UPDATE user_team SET `m_keuze5` = '%s' WHERE `id`='" . $_SESSION['uid'] . "' ", mysql_real_escape_string($_POST['option5']));
$Result = mysql_query($fuelQuery5);
if ($Result) {
echo 'Team is aangepast!';
}
}
}
}
Edit again,
Demo Fiddle of js

Categories