PHP MySQL search using multiple text boxes to search multiple columns - php

I'm learning PHP and working on a project for searching books in a MySQL database. The user should be able to search by Book Title, Book Author and by the Category, using all, one or any combination of the 3.
At present here is my code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Welcome to Library Management System</title>
<link href="main.css" rel="stylesheet" type="text/css" />
</head>
<body>
<?php
require_once "db.php";
include "header.html";
if(isset($_POST["bookTitle"]))
{
$bookTitle = mysqli_real_escape_string($con, $_POST["bookTitle"]);
}
else
{
$bookTitle = NULL;
}
if(isset($_POST["bookAuthor"]))
{
$bookAuthor = mysqli_real_escape_string($con, $_POST["bookAuthor"]);
}
else
{
$bookAuthor = NULL;
}
if(isset($_POST["category"]))
{
$category = mysqli_real_escape_string($con, $_POST["category"]);
}
else
{
$category= NULL;
}
echo "Results by Book Title Search";
$bookTitle = mysqli_real_escape_string($con, $_POST["bookTitle"]);
$query = "Select * From book NATURAL JOIN category where category.CategoryDesc LIKE '%" .$category ."%' OR book.BookTitle LIKE '%" .$bookTitle ."%' OR book.Author LIKE '%" .$bookAuthor."%'";
$result=mysqli_query($con, $query) or die(mysqli_error());
echo '<table border="1" width="95%">'."\n";
echo "<tr><th>ISBN</th><th>Title</th><th>Author</th><th>Edition</th><th>Year</th><th>Category ID</th><th>Reserved</th><th>Reserve?</th><tr>";
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)){
echo "<tr><td>";
echo(htmlentities($row[0]));
echo("</td><td>");
echo(htmlentities($row[1]));
echo("</td><td>");
echo(htmlentities($row[2]));
echo("</td><td>\n");
echo(htmlentities($row[3]));
echo("</td><td>\n");
echo(htmlentities($row[4]));
echo("</td><td>\n");
echo(htmlentities($row[5]));
echo("</td><td>\n");
echo(htmlentities($row[6]));
echo("</td><td>\n");
echo('Edit
/ ');
echo('Delete');
echo("</td></tr>\n");
}
echo "</br>";
If I search using all three fields, the query returns the relevant results. If one or more of the fields is left blank, the entire database is returned, which is not what i want.
Is there a better approach to this?

you can use this
$condition="sasaaa";
$bookTitle=trim($_POST['bookTitle']);
$bookAuthor=trim($_POST['bookAuthor']);
$category=trim($_POST['category']);
if(isset($bookTitle))
$condition="booktitle=$bookTitle";
if(isset($bookAuthor))
$condition="bookAuthor=$bookAuthor";
if(isset($category))
$condition="category=$category";
and use this $condition variable in your SQl. use mysqli_real_escape_string().
Hope it will help you :)

It would be better to skip all your tests at the beginning, and simply build your query dynamically, only putting where conditions when your post variables are set. But if you wish to keep this logic (which isn't too good) , just replace your NULLvalues with empty string, and that should do the trick...

Related

Get an output after a select option in html

So basically, i have a database that simulates an airport, and i want to make a page that after a selected category i provide the total amount of customs fees of the category(example: category selected=electronics, output wanted= eletronics = somenumber) the select tag in the html is dynamic based on the category(so if i remove a category the select option disappears). The problem is that i don't know how to display the amount. I've managed to display the selected option but i have no idea on how to pair the amount with the category.
Sorry for the messy explaination, but it's really hard for me to explain my problem in another language, please help a poor student
For any doubts about the code just ask
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Dazi</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="style.css">
<script src="script.js"></script>
</head>
<body>
<form action="home.php" method="GET">
<select name="categoria" id="cate">
<?php
$conn = MySQLi_connect("localhost","root","","aeroporto");
if (!$conn)
die("Problems");
$query = "select CA.descrizione as 'categoria', sum(C.dazio) as 'qta_dazi'
from controlli C inner join merci M on C.id=M.id_controllo_fk inner join categorie CA on CA.id=C.id
group by CA.id";
$res=MySQLi_query($conn ,$query);
while( $row= MySQLi_fetch_array($res,MYSQLI_ASSOC))
{
$c=$row["categoria"];
$n=$row["qta_dazi"];
$cat=$_GET["categoria"];
echo "<option value='$c'>$c</option>";
}
echo"</select>";
echo"<input type='submit' value='Visualizza il totale'>";
echo"<br><br><br>";
if(isset($cat)){
echo $cat." =";
}
$ok= MySQLi_close($conn);
if (!$ok)
die("problems");
?>
</form>
</body>
</html>
During the loop, check if $c ever equals $cat (note that you can set $cat outside the loop, since it does not change as a result of the DB query). At that point, set a separate variable (which has scope outside the loop) to denote the matching amount, and use that in your display:
$cat=$_GET["categoria"];
$val = "";
while( $row= MySQLi_fetch_array($res,MYSQLI_ASSOC))
{
$c=$row["categoria"];
$n=$row["qta_dazi"];
if ($c == $cat) $val = $n; //check the category value from the DB against the GET variable.
echo "<option value='$c'>$c</option>";
}
echo"</select>";
echo"<input type='submit' value='Visualizza il totale'>";
echo"<br><br><br>";
if(isset($cat)) {
echo $cat." = ".$val;
}
Just for didactical purpose, do not use this in production.
In home.php:
$categoryId = $_REQUEST['categoria'];
//sanitization...
$conn = MySQLi_connect("localhost","root","","aeroporto");
//...
$query = "select sum(C.dazio) as 'prezzo_dazi', count(C.dazio) as 'qta_dazi'
from controlli C join categorie CA on CA.id = C.id WHERE CA.id = $categoryId";
$res=MySQLi_query($conn ,$query);
if( $row = MySQLi_fetch_array($res,MYSQLI_ASSOC))
{
echo "Dazi: {$row['prezzo_dazi']} € (qt. {$row['qta_dazi']}";
}else{
echo "Categories doesn't have any Dazio assigned.";
}
MySQLi_close($conn);
Usually a small attention o research on Google it's enough to have an higher understanding of the programming concept.
Cheers.

Some sort php error on my search engine project result page

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Search Engine Project</title>
<link rel="stylesheet" type="text/css" href="css/styles.css">
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
</head>
<body>
<div class="container">
<form action="action.php" method="GET" class="search_form result-form" autocomplete="off">
<span class="result-header">Server Search</span>
<input type="text" name="k" class="input result_input" value="<?php echo $_GET['k'] ?>">
<input type="submit" name="search" value="Search Web" class="search">
</form>
</div>
<script src="js/bootstrap.min.js" ></script>
<script src="js/jquery-3.1.1.min.js" ></script>
<script src="js/javascript.js"></script>
</body>
</html>
<?php
$q=$_GET['k'];
if(isset($_GET['search'])){
header("Location:https://www.google.co.in/? gfe_rd=cr&ei=oyBmWN3FNvPx8Afe7a7IDA&gws_rd=ssl#q=$q");
}
if(isset($_GET['image'])){
header("Location:https://www.google.co.in/search? site=&tbm=isch&source=hp&biw=1280&bih=670&q=$q");
}
if(isset($_GET['video'])){
header("Location:https://www.google.com/search? q=$q&biw=1280&bih=670&tbm=vid&source=lnms&sa=X&ved=0ahUKEwiJ_ruKxpvRAhVFgI8KHeVRBK4Q_AUICigD&dpr=1");
}
if(isset($_GET['local'])){
mysql_connect("localhost", "root", "");
mysql_select_db("search_query");
$k = $_GET['k'];
if($k == "") {
echo "";
}
else {
$terms = explode(" ", $k);
$query= "SELECT * FROM search_table WHERE ";
foreach($terms as $each)
{
$i=0;
$i++;
if($i==1)
{
$query .= "keywords LIKE '%$each%' ";
}
else
{
$query .= "OR keywords LIKE '%$each%' ";
}
}
//query
$query=mysql_query($query) or die(mysql_error());;
$numrows= mysql_num_rows($query);
if($numrows>0)
{
while($row = mysql_fetch_assoc($query))
{
$id= $row['id'];
$title= $row['title'];
$description= $row['description'];
$keywords= $row['keywords'];
$link= $row['link'];
echo "<div style=''><h2><a href='$link'>$title</a></h2>
$description</div> <hr><br/> <br/>";
}
}
else
{
echo"No results found for \"<b>$k</b>\"";
}
//disconnect
mysql_close();
}
}
?>
The above is the php code and the code searches the database in the mysql db and displays the approtiate result........
But when in the home page where i type the required keyword with lots of space before it and press search it gives a error type message :
You have an error in your SQL syntax; check the manual that
corresponds to your MariaDB server version for the right syntax to use
near 'keywords LIKE '%%' keywords LIKE '%%' keywords LIKE '%%'
keywords LIKE '%%' keyw' at line 1 error"
I dont know what to do . I googled a lot in search for the fix.....
Images
PHP Error:
Blank Space input:
Your query failed because of blank values in LIKE clause.
E.g. if user entered book cover
Your existing query will look something like this:
SELECT *
FROM search_table
WHERE keywords LIKE '%%'
OR keywords LIKE '%%'
OR keywords LIKE '%%'
OR keywords LIKE '%%'
OR keywords LIKE '%book%'
OR keywords LIKE '%%'
OR keywords LIKE '%cover%'
To fix this, trim value $_GET['k'] first.
$k = trim($_GET['k']);
Then, filter out blank values in case user adds multiple spaces in between words.
$terms = explode(" ", $k);
$terms = array_filter($terms);
Now, your query will be
SELECT *
FROM search_table
WHERE keywords LIKE '%book%'
OR keywords LIKE '%cover%'
The error you are getting is due to the fact that the OR is not being included in your SQL query. Hence the SQL in the error is keywords LIKE '%%' keywords LIKE '%%' keywords LIKE '%%' keywords LIKE '%%' (no ORs). The reason for this is that you are setting $i=0 just before $i++ in your loop. Thus $i is always 1 and the string with the OR included is never appended. Set $i=0 outside the loop.
The error message came because $i=0; is inside the loop. Move it outside.
Also avoid using blank strings.
Here's what I find a better way to build a WHERE clause:
$ors = array();
foreach ...
{
if (...)
$ors[] = 'keywords LIKE ...'
}
$or_str = implode(' OR ', $ors);
I find that simpler than special-casing the first or last item in an OR or AND list.
Meanwhile, you should consider using FULLTEXT instead of a bunch of LIKEs.

Online Task Manager for website

Requesting some help on this task management system that i am making for class. I cant quite get it to work right. information is sometimes lost before it gets to the server and some of the last php code leeks thru to being seen on the site. can anyone tell me what i am doing wrong and help me to fix this? this code is supposed to allow you to send the task to a data base and the managing section relays the data from the database to the webpage.
data base is set up as this
3 Columns:
id - INT - 5 Length - Primary Key - AI.
description - VARCHAR - 255 Length.
active - BOOLEAN - 1 Length.
I am creating this on the hostica text editor that is within the site not an IDE if there are any discrepancy in the code
the website link is http://jtaylor84.net/taskmanager.php
I would like this code to work to take the information entered and relay it to the database and show in the managed tasks in order to have them up to be removed and show the tasks that have been entered.
<!DOCTYPE html>
<html>
<head>
<title>Online Task Manager</title>
<link href="style.css" rel="stylesheet">
</head>
<body>
<div id="main">
<?php
$con = mysqli_connect('localhost', 'root', '', 'Jhonny3_Task_Manager') or die(mysql_error());
if (isSet($_POST['createTask'])) {
if (isSet($_POST['desc']) && $_POST['desc'] != '') {
$desc = $_POST['desc'];
$q = mysqli_query($con, "INSERT INTO `tasks` VALUES ('', '$desc', '1')") or die(mysql_error());
if ($q) { echo 'Added task.';
}else
echo 'Failed to add task.';}}
if (isSet($_GET['removeTask']) && isSet($_GET['id'])) {
$id = $_GET['id'];
$q = mysqli_query($con, "UPDATE `tasks` SET `active`='0' WHERE `id`='$id'");
if ($q) { echo 'Task removed.';
}else
echo 'Failed to remove task.';}
?>
<h1>Add Task:</h1>
<form action='taskmanager.php' method='POST'>
Description of Task: <input type='text' name='desc'/>
<input type='submit' value='Create Task' name='createTask'/>
</form>
<h1>Manage Tasks:</h1>
<?php
$qu = mysqli_query($con, "SELECT * FROM `tasks` WHERE `active`='1'");
if (mysqli_num_rows($qu) > 0) {
after this section the code shows up on the web page and i am not sure why
while ($row = mysqli_fetch_array($qu)) {
echo "";
echo $row['description'];
echo "<a href='taskmanager.php?removeTask&id=".$row['id']."'>Remove Task</a>";
}
}
?>
<footer id="foot01"></footer>
</div>
<script src="sitescript.js"></script>
</body>
</html> `
Problem might be your php server .your code working fine in my server .

PHP and secure forms

I am doing an exercise from the book PHP & MYSQL in easy steps. It involves an HTML form to update a row in a database then various PHP scripts to check the the input data for HTML code and make it into a secure format. However, the code just does not work the way the book says. I went to the publisher's website and downloaded the code example, but no joy.
Instead of a form with the name of the row below it, instead I get the form, then below that "No valid new name submitted". Then below that the current name of row in the table which I want to change. When I try to enter and submit data into the form it makes no difference. It displays exactly the same page. The code is below.
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ensuring security
</title>
</head>
<body>
<form action="secure.php" method="POST">
<p>New Name : <input type="text" name="name">
<input type="submit"></p></form>
<?php
require('../connect_db.php');
if (!empty($POST['name']) && !is_numeric($_POST['name'])) {
$name = $POST['name'];
$name = mysqli_real_escape_string($dbc, $name);
$name = strip_tags($name);
$q = 'UPDATE towels SET name "' . $name . '" WHERE id= 1';
mysqli_query($dbc, $q);
} else {
echo 'No valid new name submitted';
}
$q = 'SELECT * FROM towels WHERE id = 1 ';
$r = mysqli_query($dbc, $q);
while ($row = mysqli_fetch_array($r, MYSQLI_NUM)) {
echo "<p>Name : $row[1] </p>";
}
mysqli_close($dbc);
I'd appreciate any ideas on this. I have spent about 3 hours and been on the publishers website, but I am still at square one.
There is no superglobal array $POST so you have to change $POST['name'] to $_POST['name'].
PHP can't see that array so it evaluates !empty($POST['name']) as false and never executes code with update query.
And, like #BartFriederichs said, buy better book. I don't think you'll learn something valuable from current one.

it wont sum up, what is wrong with my code?

I want to be able to sum up all the revenue that is being displayed in the page and it auto sums every time I added another data to the revenue column:
Following is my code :
<?php
require_once('Connections/connect.php');
$id_customer = mysql_real_escape_string($_GET['id_customer']);
$sql_PK = "SELECT * FROM tbl_delivery_details WHERE tbl_customer_id_customer = {$id_customer}";
$PK = mysql_query($sql_PK, $connect);
if ( mysql_error() ) {
die ( mysql_error());
}
$row_PK = mysql_fetch_assoc($PK);
$customer_name = $row_PK['tbl_customer_id_customer'];
$customer_name = mysql_real_escape_string($customer_name);
$sql = "SELECT tbl_customer.customer_name,
tbl_delivery_details.delivery_details_route,
tbl_delivery_details.delivery_details_destination,
tbl_delivery_details.delivery_details_van_no,
tbl_delivery_details.delivery_details_waybill_no,
tbl_delivery_details.delivery_details_charge_invoice,
tbl_delivery_details.delivery_details_revenue,
tbl_delivery_details.delivery_details_strip_stuff,
tbl_delivery_details.delivery_details_date
FROM tbl_customer, tbl_delivery_details
WHERE tbl_customer.id_customer = tbl_delivery_details.tbl_customer_id_customer
AND tbl_customer.id_customer = '{$customer_name}'";
$res = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($res);
$sum = 0;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/x html">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Customer Revenue</title>
<link rel="stylesheet" type="text/css" href="qcc.css"/>
</head>
<body>
<table border="1">
<tr>
<th>Reveneu</th>
</tr>
<?php do { ?>
<tr>
<td><?php echo $row_PK['delivery_details_revenue'];?></td>
</tr>
<?php } while ($row_PK = mysql_fetch_assoc($PK));?>
<?php { ?>
<?php $sum+=$row_PK['delivery_details_revenue'] ?>
<?php } ?>
</table>
<?php echo $sum; ?>
</body>
</html>
When I load the page echo $sum always is zero how to correctly sum up the column I made that it will sum automatically if I add another data to it :
Instead of adding the revenue values up in PHP, why not have MySQL do it for you in the query?
$sql = "SELECT SUM(tbl_delivery_details.delivery_details_revenue) as revenue,
tbl_customer.customer_name,
tbl_delivery_details.delivery_details_route,
tbl_delivery_details.delivery_details_destination,
tbl_delivery_details.delivery_details_van_no,
tbl_delivery_details.delivery_details_waybill_no,
tbl_delivery_details.delivery_details_charge_invoice,
tbl_delivery_details.delivery_details_revenue,
tbl_delivery_details.delivery_details_strip_stuff,
tbl_delivery_details.delivery_details_date
FROM tbl_customer, tbl_delivery_details
WHERE tbl_customer.id_customer = tbl_delivery_details.tbl_customer_id_customer
AND tbl_customer.id_customer = '{$customer_name}'";
And then in youru view, just echo the SUM figure...
echo $row_PK['revenue'];
If I read this correctly, you're summing up the values outside of your while loop. That won't work.
I think you're mixing up a normal while loop, and a 'do while' loop.
See this code:
<?php do { ?>
<tr>
<td><?php echo $row_PK['delivery_details_revenue'];?></td>
</tr>
<?php } while ($row_PK = mysql_fetch_assoc($PK));?>
<?php { ?>
<?php $sum+=$row_PK['delivery_details_revenue'] ?>
<?php } ?>
It should be more along these lines:
<?php do { ?>
<tr>
<td><?php
echo $row_PK['delivery_details_revenue'];
$sum+=$row_PK['delivery_details_revenue']
?>
</td></tr>
<?php } while ($row_PK = mysql_fetch_assoc($PK));?>
this wouldn't happen if you would write the code a bit more clearly; try to avoid interleaving html and php so much:
<?php
do {
$revenue = $row_PK['delivery_details_revenue'];
$sum += revenue;
println("<tr><td>$revenue</td></tr>");
} while ($row_PK = mysql_fetch_assoc($PK));
?>
This is a lot clearer, if you ask me.
Well, I don't have a PHP interpreter in my head to run your code on sight. So, just a few things which I can spot
First, there is an SQL injection in your first query. Either cast your variable to integer
$id_customer = intval($_GET['id_customer']);
or treat it as a string in your query
$sql_PK = "SELECT * FROM tbl_delivery_details WHERE tbl_customer_id_customer = '$id_customer'";
or - better yet - use some database wrapper that allows you to use placeholders to represent actual data in the query.
Next, your query is incredible hard to read.
If your field names do not interfere, there is no reason to use table.field notation then.
Also use shortland aliases and consider using * if you want most of the fields from the table:
$sql = "SELECT SUM(delivery_details_revenue) as revenue,
customer_name, tbl_delivery_details.*
FROM tbl_customer, tbl_delivery_details
WHERE id_customer = tbl_customer_id_customer
AND id_customer = '$customer_name'";
By the way, while editing your query, I've noticed inconsistent naming: id_customer = '$customer_name'. Don't confuse yourself with wrong variable names. If it's id, then call it "id", not "name"
And also I see no point in the first query at all, if id_customer is equal to tbl_customer_id_customer. I think you need to simplify your code - it's compexity is the main reason why you're not getting your results, I believe.
Start from very simple query like
$sql = "SELECT SUM(delivery_details_revenue) as revenue,
FROM tbl_delivery_details
WHERE tbl_customer_id_customer = '$id_customer'";
and see if it returns anything.
If so - start adding some more data to fetch.
If no - check your data and overall data structure if it's all right.

Categories