Search multiple Criteria - And/or search in PHP - php

Not sure what I am doing wrong here. I would like to create a search that allows the user to do an and or search.
However when I use the below code, if I type in Brown as Colour1 it will return all results, same as post code.
The goal is to allow the user to search multiple fields to return a match. So Colour1 and Postcode
<html>
<head>
<title> Logo Search</title>
<style type="text/css">
table {
background-color: #FCF;
}
th {
width: 250px;
text-align: left;
}
</style>
</head>
<body>
<h1> National Logo Search</h1>
<form method="post" action="singlesearch2.php">
<input type="hidden" name="submitted" value="true"/>
<label>Colour 1: <input type="text" name="criteria" /></label>
<label>Colour 2: <input type="text" name="criteria2" /></label>
<label>PostCode: <input type="text" name="criteria3" /></label>
<label>Suburb: <input type="text" name="criteria4" /></label>
<input type="submit" />
</form>
<?php
if (isset($_POST['submitted'])) {
// connect to the database
include('connect.php');
//echo "connected " ;
$criteria = $_POST['criteria'];
$query = "SELECT * FROM `Mainlist` WHERE (`Colour1`like '%$criteria%')
or
('Colour2' like '%$criteria2%')
or
('PostCode' = '%$criteria3%')
or
('Suburb' like '%$criteria4%')
LIMIT 0,5";
$result = mysqli_query($dbcon, $query) or die(' but there was an error getting data');
echo "<table>";
echo "<tr> <th>School</th> <th>State</th> <th>Suburb</th> <th>PostCode</th> <th>Logo</th> <th>Uniform</th></tr>";
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo "<tr><td>";
echo $row['School'];
echo "</td><td>";
echo $row['State'];
echo "</td><td>";
echo $row['Suburb'];
echo "</td><td>";
echo $row['PostCode'];
echo "</td><td><img src=\"data:image/jpeg;base64,";
echo base64_encode($row['Logo']);
echo "\" /></td></td>";
echo "</td><td><img src=\"data:image/jpeg;base64,";
echo base64_encode($row['Uniform']);
echo "\" /></td></td>";
}
echo "</table>";
}// end of main if statment
?>
</body>
</html>
I can get it to work correctly when I use a dropdown list to select the criteria however I would like them to have multiple options to filter results.
<form method="post" action="multisearch.php">
<input type="hidden" name="submitted" value="true"/>
<label>Search Category:
<select name="category">
<option value="Colour1">Main Colour</option>
<option value="Colour2">Secondary Colour</option>
<option value="PostCode">Post Code</option>
</select>
<label>Search Criteria: <input type="text" name="criteria" /></label>
<input type="submit" />
</form>
<?php
if (isset($_POST['submitted'])) {
// connect to the database
include('connect.php');
echo "connected " ;
$category = $_POST['category'];
$criteria = $_POST['criteria'];
$query = "SELECT * FROM `Mainlist` WHERE $category LIKE '%$criteria%'";
$result = mysqli_query($dbcon, $query) or die(' but there was an error getting data');

In general you run your query with AND condition because it has criteria and you have it means that you have to show value by matching each criteria with receptive column. but it also depends on users or client how they want to show their field.
In short it doesn't have any rule how to show.

Played around with it for a bit and found the answer. I needed to define the criteria. see below code
<?php
if (isset($_POST['submitted'])) {
// connect to the database
include('connect.php');
//echo "connected " ;
$criteria = $_POST['criteria'];
$criteria2 = $_POST['criteria2'];
$criteria3 = $_POST['criteria3'];
$criteria4 = $_POST['criteria4'];
$criteria5 = $_POST['criteria5'];
$query = "SELECT * FROM `Mainlist` WHERE (`Colour1`like '%$criteria%') and (`Colour2`like '%$criteria2%')
and (`PostCode`like '%$criteria3%') and (`Suburb`like '%$criteria4%') and (`State`like '%$criteria5%')

Related

How to make my PHP code more efficient for a search database?

Main objective for this post is to open up a can of worms. I would like to get some advise on what is the best way/ most efficient way to search a phpmyadmin database.
I am just starting to learn PHP. Main goal is to be able to write my own search databases as that has always interested me. I played around with some code to build a basic search database and have it working now.
Below is the code I used. I would guess as it is my first attempt at this I am going about it the wrong way. Assuming this was a large database, how could I make this more efficient? Am I going about it the wrong way using PHP? Is there a better way to do this?
The goal is to have searchable database where the user has multiple options to query to help refine the results.
<html>
<head>
<title> test Search </title>
<style type="text/css">
table {
background-color: #ffffff;
}
th {
width: 200px;
text-align: left;
}
</style>
</head>
<body>
<h1> test Search</h1>
<form method="post" action="index.php">
<input type="hidden" name="submitted" value="true"/>
<label>Colour 1: <input type="text" name="criteria" /></label>
<label>Colour 2: <input type="text" name="criteria2" /></label>
<label>PostCode: <input type="text" name="criteria3" /></label>
<label>Suburb: <input type="text" name="criteria4" /></label>
<label>State: <input type="text" name="criteria5" /></label>
<input type="submit" />
</form>
<?php
if (isset($_POST['submitted'])) {
// connect to the database
include('connect.php');
//echo "connected " ;
$criteria = $_POST['criteria'];
$criteria2 = $_POST['criteria2'];
$criteria3 = $_POST['criteria3'];
$criteria4 = $_POST['criteria4'];
$criteria5 = $_POST['criteria5'];
$query = "SELECT * FROM `Mainlist` WHERE (`Colour1`like '%$criteria%') and (`Colour2`like '%$criteria2%')
and (`PostCode`like '%$criteria3%') and (`Suburb`like '%$criteria4%') and (`State`like '%$criteria5%')
LIMIT 0,10";
$result = mysqli_query($dbcon, $query) or die(' but there was an error getting data');
echo "<table>";
echo "<tr> <th>School</th> <th>State</th> <th>Suburb</th> <th>PostCode</th> <th>Logo</th> <th>Uniform</th></tr>";
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo "<tr><td>";
echo $row['School'];
echo "</td><td>";
echo $row['State'];
echo "</td><td>";
echo $row['Suburb'];
echo "</td><td>";
echo $row['PostCode'];
echo "</td><td><img src=\"data:image/jpeg;base64,";
echo base64_encode($row['Logo']);
echo "\" /></td></td>";
echo "</td><td><img src=\"data:image/jpeg;base64,";
echo base64_encode($row['Uniform']);
echo "\" /></td></td>";
}
echo "</table>";
}// end of main if statment
?>
</body>
</html>

How do I run multiple SQL Queries using "if(isset($_POST['Submit'])){"

Trying to make a CRUD, everything works except my Update function. I feel like the problem is in the second sql query. When I click on submit it just refreshes and the change is gone. Can anyone show me how to find what I need to change/show me what to change?
<head>
<title>Update</title>
</head>
<body>
</form>
<?php
require_once('dbconnect.php');
$id = $_GET['id'];
$sql = "SELECT * FROM dealers where ID=$id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<form action="" method="post">';
echo "Company: <input type=\"text\" name=\"CName\" value=\"".$row['CName']."\"></input>";
echo "<br>";
echo "Contact: <input type=\"text\" name=\"Contact\" value=\"".$row['Contact']."\"></input>";
echo "<br>";
echo "City: <input type=\"text\" name=\"City\" value=\"".$row['City']."\"></input>";
echo "<br>";
echo "<input type=\"Submit\" = \"Submit\" type = \"Submit\" id = \"Submit\" value = \"Submit\">";
echo "</form>";
}
echo "</table>";
} else {
echo "0 results";
}
if(isset($_POST['Submit'])){
$sql = "UPDATE dealers SET CName='$CName', Contact='$Contact', City='$City' where ID=$id";
$result = $conn->query($sql);
}
$conn->close();
?>
Instead of building a form inside PHP, just break with ending PHP tag inside your while loop and write your HTML in a clean way then start PHP again. So you don't make any mistake.
Also you've to submit your $id from your form too.
Try this
<?php
require_once('dbconnect.php');
$id = $_GET['id'];
$sql = "SELECT * FROM dealers where ID=$id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?= $id ?>" />
Company: <input type="text" name="CName" value="<?= $row['CName'] ?>" />
<br>
Contact: <input type="text" name="Contact" value="<?= $row['Contact'] ?>" />
<br>
City: <input type="text" name="City" value="<?= $row['City'] ?>" />
<br>
<input type="Submit" name="Submit" id="Submit" value="Submit" />
</form>
<?php
} // end while loop
echo "</table>";
}
else {
echo "0 results";
}
Note: You are passing undefined variables into your update query. As you are submitting your form you must have to define those variables before you use them.
if (isset($_POST['Submit'])) {
$CName = $_POST['CName'];
$Contact = $_POST['Contact'];
$City = $_POST['City'];
$id = $_POST['id'];
$sql = "UPDATE dealers SET CName='$CName', Contact='$Contact', City='$City' where ID=$id";
$result = $conn->query($sql);
}
$conn->close();
that loop? ID primary key or not?
maybe u need create more key in table dealer like as_id
<input type="hidden" name="idform" value="$as_id">
in statment
if($_POST){
$idf = $_POST['idform'];
if(!empty($idf)){
$sql = "UPDATE dealers SET CName='$CName', Contact='$Contact', City='$City' where as_id=$idf";
$result = $conn->query($sql);
}
$conn->close();
}

Having a hard time with displaying information from my database

I'm just learning PHP and I followed the book to the last detail and when I go to the localhost web page that I created to pull information from the database nothing shows on the webpage. I've troubleshooted all night I've Google and read the book over and over to see what I missed. I'm posting the code that I wrote to see if someone can lead me in the right area to fix my problem.
<html>
<head>
<title>Pay Scale</title>
<style type="text/css">
table {
background-color: #FCF;
}
th {
width:150px;
text-align: left;
}
</style>
</head>
<body>
<h1>Pay Scale</h1>
<form method= "post" action= "Payscale.php"
<input type="hidden" name="submitted" value="true" />
<label> Search Category:
<select name="category">
<option value="Id">ID</option>
<option value="First Name">First Name</option>
<option value="Last_Name">Last_Name</option>
</select>
</label> <label>Search Criteria:
<input type="text" name="criteria" />
</label>
<input type="submit" />
</form>
<?php
if (isset($_POST['submitted'])){
include('payconnect.php');
$category = $_POST['category'];
$criteria = $_POST['criteria'];
$query = "SELECT * FROM employee pay range WHERE $category = '$criteria'";
$result = mysqli_query($dbcon, $query) or die('error getting data');
echo "<table>";
echo "<tr> <th>ID</th> <th>First Name</th> <th>Last_Name</th> <th>Pay_Range</th> </tr>";
While($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo "<tr><td>";
echo $row['ID'];
echo "</td><td>";
echo $row['First Name'];
echo "</td><td>";
echo $row['Last_Name'];
echo "</td><td>";
echo $row['Pay_Range'];
echo "</td><tr>";
}
echo "<table>";
}
?>
</body>
</html>
There are a couple of problems with the html code for the page. The most obvious is that there is no closing > on your form tag, so the browser slurps up the next line, thinking that it is part of the form tag. Since that line sets the $_POST['submitted'] variable that your PHP script is looking for, the value doesn't get set and the script never runs.
To correct the problem, just add a > to your form declaration:
<form method="post" action="Payscale.php">
There are also a few other problems in the HTML that could be fixed at the same time:
At the top of the page:
<html>
<head>
A document should start with a DOCTYPE declaration so that the browser knows how to interpret the page. For HTML5, this is as simple as adding a line to the start of your file:
<!DOCTYPE html>
<html>
<head>
There is also an error in the table creation code:
echo $row['Last_Name'];
echo "</td><td>";
echo $row['Pay_Range'];
echo "</td><tr>"; # A
}
echo "<table>"; # B
The lines marked A, and B create new elements--a table row, and a new table respectively. You should be closing the elements--i.e. using </tr> and </table>.
It appears that your opening tag is not closed (a minor syntactical error).
Try changing it from this:
<form method= "post" action= "Payscale.php"
to this:
<form method="post" action="Payscale.php">
and see if that solves the problem.
Try this it's working :
<html>
<head>
<title>Pay Scale</title>
<style type="text/css">
table {
background-color: #FCF;
}
th {
width:150px;
text-align: left;
}
</style>
</head>
<body>
<h1>Pay Scale</h1>
<form method= "post" action="Payscale.php">
<input type="hidden" name="submit" value="true"/>
<label> Search Category:
<select name="category">
<option value="Id">ID</option>
<option value="First Name">First Name</option>
<option value="Last_Name">Last_Name</option>
</select>
</label> <label>Search Criteria:
<input type="text" name="criteria" />
</label>
<input type="submit" value="submit" name="submitted"/>
</form>
</body>
</html>
Payscale.php
<?php
if (isset($_POST['submitted'])){
include('payconnect.php');
$category = $_POST['category'];
$criteria = $_POST['criteria'];
$query = "SELECT * FROM employee pay range WHERE $category = '$criteria'";
$result = mysqli_query($dbcon, $query) or die('error getting data');
echo "<table>";
echo "<tr> <th>ID</th> <th>First Name</th> <th>Last_Name</th> <th>Pay_Range</th> </tr>";
While($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo "<tr><td>";
echo $row['ID'];
echo "</td><td>";
echo $row['First Name'];
echo "</td><td>";
echo $row['Last_Name'];
echo "</td><td>";
echo $row['Pay_Range'];
echo "</td><tr>";
}
echo "<table>";
}
?>

Using SELECT from WHILE as value in html input PHP SQL

I am a complete beginner, so please bear with me. This is just a test project I am putting together to try to teach myself some of the basics.
I know that a lot of my commands are outdated and/or susceptible to injection, but I'd rather stick with this for now (many reasons).
I just had a question about trying to use SELECT from WHILE, and figured that out and got it to echo the correct response on the page.
Now, how do I make it echo that as a value for an HTML text box? It won't work, and I've tried to look for typos but I don't know what I am doing, frankly.
I see that the $studentid and $teacherinfo show fine, I presume because they are normal variables.
Can I somehow define two more variables for first name and last name further up in the page so that I do not need to include so much code in each input (and to keep it from being buggy)?
Here is my code for the page. The inputs will be hidden, but I have been making them text boxes for debugging purposes.
<?php
$connection = mysql_connect($serverName, $userName, $password) or die('Unable to connect to Database host' . mysql_error());
$dbselect = mysql_select_db($dbname, $connection) or die("Unable to select database:$dbname" . mysql_error());
$studentid = $_POST['student_id'];
$teacherinfo = $_POST['teacher'];
$result = mysql_query("SELECT `first_name` FROM `students` WHERE student_id = '$studentid'",$connection);
?>
</head>
<body>
<div align="center">
<form method="post" action="vote_post.php">
<h1>Vote for Teacher of the Month</h1>
<h4>(step 2 of 2)</h4>
<h2>Confirm the Information Below</h2>
<h5>Student id: <?php echo $studentid ?></br>
Student first name: <?php
while($row = mysql_fetch_array($result)){
echo $row['first_name'];
}
?>
</br>
Voted for: <?php echo $teacherinfo ?>
</h5>
<input type="text" name="student_id" value="<?php echo $studentid; ?>"/></br>
<input type="text" name="first_name" value="<?php while($row = mysql_fetch_array($result)){
echo $row['first_name'];
} ?>"/>
</br>
<input type="text" name="last_name" value="<?php while($row = mysql_fetch_array($result)){
echo $row['last_name'];
} ?>"/>
</br>
<input type="text" name="teacher" value="<?php echo $teacherinfo; ?>"/></br>
<input type="submit" value="Submit Vote" class="inputbutton"/></br></br></br>
</form>
You can't use while because your query return only one student. You have to use if instead of while. If your query return many students you can use while.
Try this code:
<?php
if($row = mysql_fetch_array($result)){
?>
Student first name: <?php echo $row['first_name'];?>
</br>
Voted for: <?php echo $teacherinfo ?></h5>
<input type="text" name="student_id" value="<?php echo $studentid; ?>"/></br>
<input type="text" name="first_name" value="<?php echo $row['first_name'];?>"/></br>
<input type="text" name="last_name" value="<?php echo $row['last_name'];?>"/></br>
<input type="text" name="teacher" value="<?php echo $teacherinfo; ?>"/></br>
<input type="submit" value="Submit Vote" class="inputbutton"/></br></br></br>
<?php
}
?>
I hope this help.
I tried to build a code that will help you. Remember that you use last_name, but does not return the field in SQL.
</head>
<body>
<div align="center">
<form method="post" action="vote_post.php">
<h1>Vote for Teacher of the Month</h1>
<h4>(step 2 of 2)</h4>
<h2>Confirm the Information Below</h2>
<?php
$connection = mysql_connect($serverName, $userName, $password) or die('Unable to connect to Database host' . mysql_error());
$dbselect = mysql_select_db($dbname, $connection) or die("Unable to select database:$dbname" . mysql_error());
$studentid = $_POST['student_id'];
$teacherinfo = $_POST['teacher'];
$result = mysql_query("SELECT `first_name`,`last_name`,`student_id` FROM `students` WHERE student_id = $studentid",$connection);
while($row = mysql_fetch_array($result)){
echo "<h5>Student id: $row['student_id'] </br>" .
"Student first name: $row['first_name'] </br>" .
"Voted for: $teacherinfo </h5> " .
"<input type='text' name='student_id' value='$row[\'student_id\']' /></br>" .
"<input type='text' name='first_name' value='$row[\'first_name\']' /></br>" .
"<input type='text' name='last_name' value='$row[\'last_name\']' /></br>" .
"<input type='text' name='teacher' value='$teacherinfo' /></br>"
}
?>
<input type="submit" value="Submit Vote" class="inputbutton"/></br></br></br>
</form>
WHILE I left because I do not know if your query can return more than one record, despite appearing to be a key. If you do not need to check the response of the Ragnar.

How to get the ID when selected the particular item?

I have a page that display products and I would like to get the product ID when I click on the particular item and pass it to another page.
May I know how can I achieve this?
I always get the last PID, my code:
<head>
<title>Toy-All</title>
<!--Wilmos: Using external CSS File to format the page style and fonts.-->
<link href="StyleSheet2.css" rel="Stylesheet" type="text/css" />
</head>
<body>
<form method = "post" action "getpid.php">
<div class="stylediv2-Middle-Toy-all">
<div class="transbox-Toy-all">
<?php
//open connection to MySQL Server
$connection = mysql_connect('localhost','root', '')
or die ('Unable to connect to !');
// select database for use
mysql_select_db('we-toys') or die ('Unable to select database!');
$query = 'SELECT p.*, price.priceN FROM product p, pricing price WHERE p.pid = price.pid and p.PGroup = 1 and p.PType = 1';
$result = mysql_query($query)
or die ('Error in query: $query. ' . mysql_error());
if (mysql_num_rows($result) > 0)
{
while ($row = mysql_fetch_array($result))
{
echo '<div style="float:left;margin-right: 10px; margin-left: 10px;"><img src="'.$row[5].'" width=200px height=200px; ?> </div>
<h3>'.$row[1].'</h3>
<h1><span style="color:red"> $ '.$row[7].' </span>
<input type="hidden" name="pid" value= '.$row[0].' >
<input id="AddtoCart-Btn" type="Submit" value= "Add to Cart" >
</h1>
';
}
}
else
{
echo "No rows found!";
}
mysql_free_result($result);
mysql_close($connection);
?>
</div>
</div>
</form>
</body>
</html>
If you retrieve your data from $_SESSION['PID'], then you will always get the last ID because you keep reassign new value to that session.
You can just achieve this with a link to the another PHP page. For example:
<a href='anotherPage.php?id=<?php echo $row[0]; ?>'>Add to Cart</a>
A more completed code as requested
<?php
$query = 'SELECT p.*, price.priceN FROM product p, pricing price
WHERE p.pid = price.pid and p.PGroup = 1 and p.PType = 1';
$result = mysql_query($query)
or die ('Error in query: $query. ' . mysql_error());
?>
<?php while ($row = mysql_fetch_array($result)) { ?>
<h3><?php echo $row[1]; ?></h3>
<a href='anotherPage.php?id=<?php echo $row[0]; ?>'>Add to Cart</a><br><br>
<?php } ?>
And for anotherPage.php code
<?php
echo "You are trying to add this product ID to cart: " . $_GET['id'];
?>
You can use this form that i also provide in this code.
$query = 'SELECT p.*, price.priceN FROM product p, pricing price WHERE p.pid = price.pid and p.PGroup = 1 and p.PType = 1';
$result = mysql_query($query)
or die ('Error in query: $query. ' . mysql_error());
if (mysql_num_rows($result) > 0)
{
while ($row = mysql_fetch_array($result))
{
$pid = ($row[0]);
$_SESSION['PID'] = $pid;
echo '<div style="float:left;margin-right: 10px; margin-left: 10px;"><img src="'.$row[5].'" width=200px height=200px; ?> </div>
<h3>'.$row[1].'</h3>
<h1><span style="color:red"> $ '.$row[7].' </span>
<form method="post" action="cart.php">
<input type="hidden" name="pid" value= '.$row[0].' >
<input id="AddtoCart-Btn" type="Submit" value= "Add to Cart" >
</form>
$pid = '.$row[0].';
</h1>
';
}
}
Now you should make a new page such as cart.php
echo $_POST['pid'];
If I understand you correctly, the following should work:
<form method="post" action="anotherPage.php">
<input type="hidden" name="id" value="<?php echo "$row[0]"?>"/>
<input id="AddtoCart-Btn" type="Submit" value="<?php echo "$row[0]" ?>" />
</form>
So basically when you click the product button, the id will be accessible in anotherPage.php
EDIT:
I rewrote your code to improve readability:
<div style="float:left;margin-right: 10px; margin-left: 10px;"><img src=<?php echo $row[5]; ?> width=200px height=200px; ?> </div>
<h3><?php echo $row[1]; ?></h3>
<h1>
<span style="color:red"> $ <?php echo $row[7] ?></span>
<form method="post" action="cart.php">
<input type="hidden" name="pid" value=<?php $row[0]; ?> >
<input id="AddtoCart-Btn" type="Submit" value= "Add to Cart" >
</form>
<?php $pid = $row[0]; ?>
</h1>
Avoid echo-ing out large chunks of HTML where possible. Try it now, If it fails provide the error message.
The above does, what the simple test below achieves:
<?php
$id = 1;
if (isset($_POST['submit_btn'])){
echo $_POST['id'];
}
?>
<form method="post" action="#">
<input type="hidden" name="id" value= <?php echo $id; ?> >
<input type="submit" name="submit_btn" value="submit">
</form>

Categories