Filtering search results PHP - php

I'm trying to give a user the ability to filter search results by ascending or descending order. It isn't working.
I think it is an issue with my select or post method or something.
What could be the reason why it isn't working?
<?php
$search = "";
if(isset($_POST["search"])){
$search = $_POST["search"];
$Ascending= $_POST["Sort By"];
$Descending= $_POST["Sort By"];
}
?>
<form method="POST">
<input type="text" name="search" placeholder="Search for Question"
value="<?php echo $search;?>"/>
<label for="Sort">SortBy:</label>
<select id="SortBy" name="Sort By">
<option value="Ascending">Ascending Order</option>
<option value="Descending">Descending Order</option>
<input type="submit"
</select>
</form>
<?php
if(isset($Ascending)) {
if (isset($search)) {
require("common.inc.php");
$query = file_get_contents(__DIR__ . "/queries/SearchTableASC.sql");
if (isset($query) && !empty($query)) {
try {
$stmt = getDB()->prepare($query);
//Note: With a LIKE query, we must pass the % during the mapping
$stmt->execute([":question" => $search]);
//Note the fetchAll(), we need to use it over fetch() if we expect >1 record
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
echo $e->getMessage();
}
}
}
}
if(isset($Descending)){
if (isset($search)) {
require("common.inc.php");
$query = file_get_contents(__DIR__ . "/queries/DescendingOrder.sql.sql");
if (isset($query) && !empty($query)) {
try {
$stmt = getDB()->prepare($query);
//Note: With a LIKE query, we must pass the % during the mapping
$stmt->execute([":question" => $search]);
//Note the fetchAll(), we need to use it over fetch() if we expect >1 record
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
echo $e->getMessage();
}
}
}
}
?>
<!--This part will introduce us to PHP templating,
note the structure and the ":" -->
<!-- note how we must close each check we're doing as well-->
<?php if(isset($results) && count($results) > 0):?>
<p>This shows when we have results</p>
<ul>
<!-- Here we'll loop over all our results and reuse a specific template for each iteration,
we're also using our helper function to safely return a value based on our key/column name.-->
<?php foreach($results as $row):?>
<li>
<?php echo get($row, "question")?>
Delete
</li>
<?php endforeach;?>
</ul>
<?php else:?>
<p>This shows when we don't have results</p>
<?php endif;?>

You are not using the incoming parameters correctly:
$Ascending= $_POST["Sort By"];
$Descending= $_POST["Sort By"];
Here you set ascending and descending to the same value.
You should do something like:
$ascOrDec = $_POST['Sort By'];
And than check the value of $ascOrDec before you choose your query.

Related

How to fetch data from database based on selection in the dropdown using PHP?

I am trying to fetch the details of the person selected in the dropdown on another page.
Here's my code:
<form class="cmxform" action ='functions/processform.php' id="Form1" method="post">
<legend> Faculty Transaction Form</legend>
<label for="addname">Please Select School</label>
<select class="form-control" name="school" id="school">
<?php
$nameslist = $getschool->getSchool();
oci_execute($nameslist, OCI_DEFAULT);
while ($row = oci_fetch_array($nameslist, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo '<option value="' . $row['SCHOOLPROPERNAME'] . '">' . $row['SCHOOLPROPERNAME']. '</option>';
}
?>
</select>
<label for="names">Please Select Name</label>
<select class="form-control" name="names" id="names1234">
<option value='0' >Select Name</option>
</select>
<label for="names">Recall FTF in progress</label>
<select class="form-control" name="ftf" id="ftf">
<option value='0' >Select Name</option>
</select>
<p>Paid/Unpaid/Terminated:</p>
<div>
<input type="radio" id="paid" name="paid" value="paid" >
<label for="paid">Paid</label>
</div>
<div>
<input type="radio" id="unpaid" name="unpaid" value="unpaid" >
<label for="unpaid">Un-Paid</label>
</div>
<div>
<input type="radio" id="terminated" name="terminated" value="terminated" >
<label for="terminated">Terminated</label>
</div>
</form>
<?php
$report = $getschool->getftf();
if (count($report) === 0) {
echo "<tr>No Reports</tr>";
} else {
for ($i = 0; $i < count($report); $i++) {
echo
"
<a class=btn href='createftf.php?id=".$report[$i]['ID']. "'id='recallFTF'>Create FTF</a>
</tr>";
";
}
}
?>
queries.php
class Queries {
public static function getftf() {
$dbUser = "xxxx";
$dbPass = "xxxx";
$dbConn = "(DESCRIPTION = (ADDRESS = (PROTOCOL=TCP)(HOST=xxxx)(PORT=1521))(CONNECT_DATA=(SID=xxxx)))";
$conn = oci_connect($dbUser, $dbPass, $dbConn);
$sql = oci_parse($conn,"SELECT * from tblFTF_Archive_Page1 ");
if (oci_execute($sql, OCI_DEFAULT)){
$result = oci_fetch_array($sql, OCI_ASSOC+OCI_RETURN_NULLS);
return $result;
} else {
return false;
}
}
}
}
I'm trying to fetch the ID of the person that's selected in the second or third dropdown and then I will be fetching more details of the same person. With the above code I'm getting an error sayig "PHP Warning: count(): Parameter must be an array or an object that implements Countable".
I've referred to some similar questions here but none of them had an answer for my question. Any help would be appreciated. TIA
If you look at the documentation the oci_parse function returns "a statement handle on success, or FALSE on error".
If you wrote the code count(false); you would get the warning you describe.
There are numerous ways to resolve what you've encountered. You need to know what a function might return and account for that. This is always the case!
So, you could do the following for example.
<?php
$report = $getschool->getftf();
if ($report === false || count($report) === 0) {
echo "<tr>No Reports</tr>";
} else {
...
That way you've checked the returned value is not Boolean false (might want to check for an error or see what went wrong). You then assume the returned value is a resource and is countable so you proceed to use count.
Inversely you could test for it being explicitly what you expect. See is_resource
Update:
Seeing now you are missing code... you need to use oci_execute and a fetch on the statement you prepared.

My Select form is not displaying database items

I am attempting to create a form where the user can insert a product into a database. One of the the things they must input is the category, which I am using a select input form to allow them to choose from the available categories (PHP and MySQL displays all the available categories). The options inside the select element is given with PHP. But for some reason, when I run the application, the categories do not show up. No errors or anything, and the connection to the database is assured. The code is below. I am using the MVC pattern, if that helps any
The file with the function (category_db.php)
<?php
function get_categories() {
global $db;
$query = "SELECT * FROM categories ORDER BY categoryID";
$statement= $db->prepare($query);
$statement->execute();
return $statement;
}
The controller for the files (index.php)
<?php
require ('../models/database.php');
require ('../models/product_db.php');
require ('../models/category_db.php');
$action = filter_input(INPUT_POST, 'action');
if($action == NULL || $action==FALSE){
$action = 'list_products';
}
if ($action == 'list_products'){
$categories = get_categories();
$category_id = filter_input(INPUT_GET, 'category_id');
if ($category_id == NULL || $category_id == FALSE){
$category_id = 1;
}
$product_item = get_product_list($category_id);
include ('product_list.php');
} else if ($action = 'delete_product') {
$product_id = filter_input(INPUT_POST, 'product_id');
$category_id = filter_input(INPUT_POST, 'category_id');
delete_product($product_id);
header("Location: .?category_id=$category_id");
}
else if($action == 'add_product'){
$categories = get_categories();
include('add_product_form.php');
}
And finally, the page that display the form (add_product_form.php)
<?php include '../includes/header.php'; ?>
<main>
<h3>Add Product Form</h3>
<form method="post" action=".">
<label for="category">Category</label>
<select name="category">
<?php foreach ( $categories as $category ) : ?>
<option value="<?php echo $category['categoryID']; ?>">
<?php echo $category['categoryName']; ?>
</option>
<?php endforeach; ?>
</select>
<br>
<label for="product_code">Product Code</label>
<input type="text" name="product_code"><br>
<label for="product_name">Product Name</label>
<input type="text" name="product_name"><br>
<label for="list_price">List Price</label>
<input type="text" name="list_price"><br>
<input type="submit" value="Add Product">
</form>
</main>
<?php include '../includes/footer.php'; ?>
Now I have triple checked the code, but I cannot find the problem. Any help on this would be appreciated. I am also using netbeans if that helps any
I think you should use a "fetchAll" in your function so you will return an array with all your categories :
function get_categories() {
global $db;
$query = "SELECT * FROM categories ORDER BY categoryID";
$statement= $db->prepare($query);
$statement->execute();
$categories = $statement->fetchAll(PDO::FETCH_ASSOC);
return $categories;
}
Then you can loop throught the array to get the data you want.

confused in echo mysql result inside echo

after sign in and redirect to next page, i check the user with $_SESSION.
Then if username valid, i want to show dropdown list which the list is get from database. I am confuse how to echo.
<?php
session_start(); //Start the session
if(!isset($_SESSION['pic']))
{
header('Location:index.php?p=signin');
}
else {
echo '<div class="form-group">
<label for="symcat" class="control-label">Symptom Category</label>
<select id="symcat" name="symcat" class="selectlist form-control">
<option value=""></option>
$sql='SELECT category FROM sym_category';
if ($sql) {
$res=mysqli_query($dbc,$sql) or die(_ERROR26.': '.mysqli_connect_error());
}
while ($dat = mysqli_fetch_array($res, MYSQLI_NUM)) {
echo '\t<option value="'.$dat[0].'">'.$dat[0].'</option>\n';
}
mysqli_free_result($res);
</select>
</div> <!-- /form-group -->';
}
?>
This would probably be better:
<?php
session_start(); //Start the session
if(!isset($_SESSION['pic']))
{
header('Location:index.php?p=signin');
}
else {
$sql = 'SELECT category FROM sym_category';
if ($sql) {
$res = mysqli_query($dbc,$sql) or die(_ERROR26.': '.mysqli_connect_error());
}
?>
<div class="form-group">
<label for="symcat" class="control-label">Symptom Category</label>
<select id="symcat" name="symcat" class="selectlist form-control">
<option value=""></option>
<?php if (isset($res)): ?>
<?php while ($dat = mysqli_fetch_array($res, MYSQLI_NUM)): ?>
<option value="<?php echo $dat[0] ?>"><?php echo $dat[0] ?></option>
<?php endwhile ?>
<?php mysqli_free_result($res); ?>
<?php endif ?>
</select>
</div> <!-- /form-group -->
<?php } ?>
Honestly I still don't think this is a very nice way. If possible, please use view files.
I think it's reasonable to say that you shouldn't use an echo within another echo. Echo is used to print something to your screen, so it shouldn't be necessary to use an echo within that same echo.
Check out this sample code. Maybe it'll help you.
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Fetch the option list details from DB
$optionList = array();
$sql = "SELECT category FROM sym_category";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$optionList[] = $row['category']
}
} else {
echo "0 results";
}
// Create the dropdown list
echo "<div class='form-group'>";
echo '<label for="symcat" class="control-label">Symptom Category</label>';
echo '<select id="symcat" name="symcat" class="selectlist form-control">';
echo '<option value=""></option>';
foreach ($optionList as $key => $value)
{
echo "<option value='$value'>$value</option>";
}
echo '</select>';
echo '</label>';
echo "</div>"
As Akintunde & SheperOfFire said the nice and tidy way is like :
<?php
session_start(); //Start the session
if(!isset($_SESSION['pic']))
{
header('Location:index.php?p=signin');
}
else {
header('Location:index.php?p=forminputcar');
}
?>
Because, inside of forminputcar has php tag and echo also. Or you can also put above script at the top of forminputcar page. So, if session match we stay on current page.
<?php
session_start();
if(isset($_SESSION['pic']))
{
header('charset=UTF-8');
}
else {
header('Location:index.php?p=signin');
}
?>

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.

undefined variable while updating

Here my aim to update a book's information with title which I set in the textbox. But in my code I when I run I'm getting the error as $query2 is undefined in $query2['status']=="Available". Can anyone rectify my error?
<?php
$user="root";
$server="localhost";
$password="";
$db="library book";
$query=mysql_connect($server,$user,$password);
$dbRes = mysql_select_db($db,$query);
if(isset($_GET['book_id']))
{
$bookid = $_GET['book_id'];
$str="select * from books where bookid=$bookid";
$query1=mysql_query($str);
//echo $query1;
$query2=mysql_fetch_array($query1);
//print_r ($query2);
}
if(isset($_POST['Update']))
{
$title=mysql_real_escape_string($_POST['title']);
$author=mysql_real_escape_string($_POST['author']);
$publisher=mysql_real_escape_string($_POST['publisher']);
$numcopies=mysql_real_escape_string($_POST['numcopies']);
$shelfno=mysql_real_escape_string($_POST['shelfno']);
$status=mysql_real_escape_string($_POST['status']);
$str1="update books set title=$title where bookid=$bookid";
$query3=mysql_query($str1);
echo $query3;
$query4=mysql_query("select * from books");
$row=mysql_fetch_array($query3);
echo "<table>";
echo "<tr><th>BookID</th><th>Title</th><th>Author</th><th>Publisher</th><th>numcopies</th><th>shelfno</th><th>status</th><th>Action</th></tr>";
echo "<tr>";
echo "<td>".$row['bookid']."</td>";
echo "<td>".$row['title']."</td>";
echo "<td>".$row['author']."</td>";
echo "<td>".$row['publisher']."</td>";
echo "<td>".$row['numcopies']."</td>";
echo "<td>".$row['shelfno']."</td>";
echo "<td>".$row['status']."</td>";
echo "</tr>";
echo "</table>";
if ($query2['status']=="Available")
echo "selected";
if ($query2['status']=="Unavailable")
echo "selected";
}
?>
<html>
<head><title>Editing the fields</title>
<style>
body {
background-color: rgb(255,0,255);
}
</style>
</head>
<body>
<form action="edit1.php" action="post">
EnterTitle:<input type="text" name="title" value="<?php echo $query2['title'];?>">
<br/>
EnterAuthor:<input type="text" name="author" value="<?php echo $query2['author'];?>" >
<br/>
EnterPublisher:<input type="text" name="publisher" value="<?php echo $query2['publisher'];?>">
<br/>
EnterNumCopies:<input type="text" name="numcopies" value="<?php echo $query2['numcopies'];?>">
<br/>
EnterShelfNo:<input type="text" name="shelfno" value="<?php echo $query2['shelfno'];?>">
<br/>
<input type="hidden" name="bookid" value=<?php if(isset($bookid)) echo $bookid; ?>>
<select>
<option value="available" <?php if ($query2['status']=="Available") echo "selected";?>>Available</option>
<option value="unavailable" <?php if ($query2['status']=="Unavailable") echo "selected";?>>Unavailable</option>
</select>
<br>
<input type="submit" name="submit" value="Update">
</form>
</body>
</html>
I think unfortunately, what you have going on here is the beginnings of a "spaghetti code" syndrome so you will want to invest in learning a PHP framework. You will have less chance of security issues, your script will be cleaner from the get-go, more-easily maintained, etc.
For this particular snippet, among other things, you have sql injection issues, you set bookid by $_GET and $_POST but it's hard to determine which is best to use, you have html happening above the <html> tag, but the main problem you are experiencing is that you have variables that are defined in an if scope but are also referenced outside of that if scope so will create the error(s) when the if condition is not satisfied (See this example for more reference).
Some suggestions besides fixing the scope issue:
Use PDO or mysqli_ with parameter binding. My example uses PDO
Use functions or class/method for both usability and readability in your final layout (it looks more complex as I have it below, but only because it's all pasted on one page. Each page should be separate). All of this $query, $query1, $query2, etc. gets confusing. I have used functions, but a class would have been better to pass bookid to all the methods internally.
Standardize your book id key name, either make it book_id or bookid, not both. My example uses bookid.
There are probably some flaws in this, but hopefully it gives you some useful ideas and as I said before, this would be more useful implemented as a class (a few classes actually) but using functions might be a good start to help clean your scripting up.
IMPORTANT NOTE: I have not tested this (there should be no syntax errors though) but you should be able to get the idea about what is happening and what things are for by paralleling your version to this one. If you don't understand it, read up on it first, don't blindly copy and paste or you will get into more trouble. Use at your own risk, as they say.
/functions/getBooks.php
# Create a general function to fetch all books.
function getBooks($con)
{
$result = array();
$query = $con->prepare("SELECT * FROM books");
$query->execute();
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$result[] = $row;
}
return $result;
}
/functions/getBookById.php
# Create a function to fetch a specific book by id
function getBookById($id,$con)
{
$query = $con->prepare("SELECT * FROM books WHERE bookid = :id");
$query->execute(array(":id"=>$id));
$row = $query->fetch(PDO::FETCH_ASSOC);
return (!empty($row))? $row : array();
}
/functions/getBook.php
# This should fetch from a global request, that way you can tell if
# a book is currently being accessed
function getBook($con)
{
autoload(array('getBookById','getId'));
$id = getId('req');
if(empty($id))
return false;
return getBookById($id,$con);
}
/functions/updateBookById.php
# Create an update function that can be accessed at anytime. Use binding
# so you don't need to mess with any sort of escaping
function updateBookById($id,$values,$con)
{
foreach($values as $keys => $vals) {
$bKey = ":{$keys}";
$bind[$bKey] = $vals;
$sql[] = '`'.$key.'` = '.$bKey;
}
$bind[":id"] = $id;
$query = $con->prepare("UPDATE books SET ".implode(', ',$sql)." WHERE bookid = :id");
$query->execute($bind);
}
/functions/updateBookTitle.php
# This is is just a specific function to focus on title. Not sure you need
# it since the update book by id function would do the same thing
function updateBookTitle($id,$title,$con)
{
$bind[":id"] = $id;
$bind[":title"] = $title;
$query = $con->prepare("UPDATE books SET title = :title WHERE bookid = :id");
$query->execute($bind);
}
/functions/getId.php
# This will fetch the id value from a global
function getId($type = false)
{
switch($type) {
case('post'):
return (isset($_POST['bookid']))? $_POST['bookid'] : false;
case('req'):
return (isset($_REQUEST['bookid']))? $_REQUEST['bookid'] : false;
default:
return (isset($_GET['bookid']))? $_GET['bookid'] : false;
}
}
/functions/bookObserver.php
# This will sit and just wait for the right globals activate it
function bookObserver($con,&$curr)
{
autoload('getId');
if(getId('req')) {
autoload('getBookById');
$books = getBookById(getId('req'),$con);
if(!empty($books))
$curr = $books;
if(isset($_POST['Update'])) {
$values = array(
'title' => $_POST['title'],
'author' => $_POST['author'],
'publisher' => $_POST['publisher'],
'numcopies' => $_POST['numcopies'],
'shelfno' => $_POST['shelfno'],
'status' => $_POST['status']
);
autoload('updateBookById');
updateBookById(getId('req'),$values,$con);
}
}
}
/functions/bookListObserver.php
# This sits and waits for the update to write the table to the page
function bookListObserver($current,$con)
{
if(isset($_POST['Update'])) {
autoload('bookList');
echo bookList(((!empty($current['status']))? $current['status'] : false),$con);
}
}
/functions/getValue.php
# This will just check if a value is set. Saves on scripting
function getValue($array,$key,$def = false)
{
return (!empty($array[$key]))? $array[$key] : $def;
}
/functions/bookList.php
# Displays your book list. Currently you are only showing the last book,
# which doesn't appear correct. No point in getting all books but only showing
# the last one
function bookList($selected = false,$con)
{
autoload('getBooks');
$books = getBooks($con);
ob_start();
?>
<table>
<tr>
<th>BookID</th>
<th>Title</th>
<th>Author</th>
<th>Publisher</th>
<th>numcopies</th>
<th>shelfno</th>
<th>status</th>
<th>Action</th>
</tr>
<?php foreach($books as $row) { ?>
<tr>
<td><?php echo $row['title'] ?></td>
<td><?php echo $row['author'] ?></td>
<td><?php echo $row['publisher'] ?></td>
<td><?php echo $row['numcopies'] ?></td>
<td><?php echo $row['shelfno'] ?></td>
<td><?php echo $row['status'] ?></td>
</tr>
<?php } ?>
</table>
<?php
if($selected == "Available")
echo "selected";
elseif($selected == "Unavailable")
echo "selected";
$data = ob_get_contents();
ob_end_clean();
return $data;
}
/functions/connect.php
# This is your mysql connection, it requires attention to build out
# It's not as useful as it could be, so you will want to research it
function connect()
{
return new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME,DB_USER,DB_PASS);
}
/functions/autoload.php
# This is just a handy function to autoload functions when you want
# to use them. If you used classes, you would make an spl_autoload_register()
# function or install something like Composer to autoload
function autoload($name,$run = false)
{
if(is_array($name)) {
foreach($name as $func) {
autoload($func);
}
return;
}
if(!function_exists($name)) {
if(is_file($file = FUNCTIONS.DS.$name.'.php'))
include_once($file);
}
if($run) {
if(function_exists($name))
return $name();
}
}
/config.php
# Make sure errors are on in testing
ini_set('display_errors',1);
error_reporting(E_ALL);
# Creating commonly-used defines will help your scripts be
# more reliable and consistent
define('DS',DIRECTORY_SEPARATOR);
define('ROOT_DIR',__DIR__);
define('FUNCTIONS',ROOT_DIR.DS.'functions');
define('DB_HOST','localhost');
define('DB_NAME','library book');
define('DB_USER','root');
define('DB_PASS','');
# Start session by default
session_start();
require_once(FUNCTIONS.DS.'autoload.php');
# Autoload the connect function and assign it
$con = autoload('connect',true);
/index.php
<?php
# Add config
include(__DIR__.DIRECTORY_SEPARATOR.'config.php');
# Include all our starting page functions
autoload(array('bookObserver','bookListObserver','getBook', 'getValue'));
# Set default array for current selection
$current = array();
# Start observer, pass connection
bookObserver($con,$current);
?>
<html>
<head><title>Editing the fields</title>
<style>
body {
background-color: rgb(255,0,255);
}
</style>
</head>
<body>
<?php
# This writes the table if update is set
# You should not put this html above the <html> tag
bookListObserver($current,$con);
# This gets the book from the page request
$book = getBook($con);
?>
<form action="edit1.php" action="post">
EnterTitle:<input type="text" name="title" value="<?php echo getValue($book,'title') ?>"><br/>
EnterAuthor:<input type="text" name="author" value="<?php echo getValue($book,'author') ?>" ><br/>
EnterPublisher:<input type="text" name="publisher" value="<?php echo getValue($book,'publisher') ?>"><br/>
EnterNumCopies:<input type="text" name="numcopies" value="<?php echo getValue($book,'numcopies') ?>"><br/>
EnterShelfNo:<input type="text" name="shelfno" value="<?php echo getValue($book,'shelfno') ?>"><br/>
<input type="hidden" name="bookid" value="<?php echo getValue($book,'bookid') ?>" />
<select>
<option value="available" <?php if(isset($current['status']) && $current['status'] == "Available") echo "selected";?>>Available</option>
<option value="unavailable" <?php if (isset($current['status']) && $current['status'] == "Unavailable") echo "selected";?>>Unavailable</option>
</select><br>
<input type="submit" name="submit" value="Update">
</form>
</body>
</html>

Categories