What have I done wrong with my MySql query? - php

I'm trying to create a simple search function in PHP for my MySQL database. I've tried different tutuorials but I end up with the same result. From testing a bit with print_r I think the problem is the query, but I don't understand why it doesn't work. Does anyone have an idea? My code is following:
html
<form action="search.php" method="get">
<div class="input-field">
<input id="search" name="search" type="search" placeholder="Search lesson plans" required>
<label for="search"><i class="material-icons">search</i></label>
<i class="material-icons" id="closesearch">close</i>
</div>
</form>
php
<?php
require_once("db_link.inc.php");
if(isset($_GET['search'])) {
$search = $link->escape_string($_GET['search']);
$query = $link->query('SELECT * FROM LessonPlans WHERE Subject LIKE "%{$search}%" OR Level LIKE "%{$search}%" OR Aim LIKE "%{$search}%" AND Language="English"');
if($query->num_rows){
while($r = $query->fetch_object()){
echo '<div>
<p>'; $r->Subject; echo '</p>
</div>';
}
}
}
?>
Table
LessonPlans
Id | Subject | Level | Aim | Text | Language
Can anyone see what I've done wrong?
/HÃ¥kan

You did not print the $r->Subject inside your loop.
You did not properly concatenate the $search variable to your query
Your query should look like (if you insist on using single tick '):
$query = $link->query('SELECT * FROM LessonPlans WHERE Subject LIKE "%'.$search.'%" OR Level LIKE "%'.$search.'%" OR Aim LIKE "%'.$search.'%" AND Language="English"');
but if you want to keep on using the curly brackets:
$query = $link->query("SELECT * FROM LessonPlans WHERE Subject LIKE '%{$search}%' OR Level LIKE '%{$search}%' OR Aim LIKE '%{$search}%' AND Language='English'");
and for displaying/echoing the data:
echo '<div>
<p>'.$r->Subject.'</p>
</div>';
You can refer here for the difference of single tick (') and double tick (").

Related

Using HTML checkboxes to dynamically create SQL query within PHP code

I currently have a html / PHP webpage which uses a series of user inputs to query a SQL database and return data for plotting. The user input is driven by html checkboxes, driven by data in the SQL database and created using PHP code. The entire html code is too large to put on here but below is an excerpt of the part I want to ask about...
...
<div id="AccProject" class="w3-hide">
<?php
$queryProject = "SELECT DISTINCT ProjID, Project, Sample, Type, Description FROM PROJECTS ORDER BY Project ASC";
$resultProject = $dbhandle->query($queryProject) or exit("Error code ({$dbhandle->errno}): {$dbhandle->error}");
while($row=mysqli_fetch_array($resultProject)){
echo "<input id='".$row['ProjID']."' value='".$row['ProjID']."' name='projID[]' type='checkbox' class='chkbox'>";
echo "<label title='".$row['Description']."

Project: ".$row['Project']."
Sample: ".$row['Sample']."
Type: ".$row['Type']."' for='".$row['ProjID']."' class='chkbox-label'> ".$row['Project']." | ".$row['Sample']." | ".$row['Type']."</label>";
}
?>
</div>
...
You can see that I query the SQL database, return a number of fields and then use PHP to generate a number of checkboxes. Later the in the html, I use javascript to extract the checked / unchecked state of these checkboxes and query the database again to return more data.
What I'd like to do is add a number of pre-filters which will reduce the number of checkboxes visible to the user on the page. For example, if the 'Type' field defines whether the data entry is a 'Cake', 'Biscuit' or 'Pudding', I would like to add some switches which would then amend the SQL query. I've given an example with some pseudo code below.
...
<div id="AccProject" class="w3-hide">
<label class="form-switch"><input type="checkbox" id="filterCake"><i></i> Select Cakes only </label>
<label class="form-switch"><input type="checkbox" id="filterBiscuit"><i></i> Select Biscuits only </label>
<label class="form-switch"><input type="checkbox" id="filterPudding"><i></i> Select Puddings only </label>
<?php
if filterCake == True
$queryProject = "SELECT DISTINCT ProjID, Project, Sample, Type, Description FROM PROJECTS WHERE Type == 'Cake' ORDER BY Project ASC";
if filterBiscuit == True
$queryProject = "SELECT DISTINCT ProjID, Project, Sample, Type, Description FROM PROJECTS WHERE Type == 'Biscuit' ORDER BY Project ASC";
if filterPudding == True
$queryProject = "SELECT DISTINCT ProjID, Project, Sample, Type, Description FROM PROJECTS WHERE Type == 'Pudding' ORDER BY Project ASC";
$resultProject = $dbhandle->query($queryProject) or exit("Error code ({$dbhandle->errno}): {$dbhandle->error}");
while($row=mysqli_fetch_array($resultProject)){
echo "<input id='".$row['ProjID']."' value='".$row['ProjID']."' name='projID[]' type='checkbox' class='chkbox'>";
echo "<label title='".$row['Description']."

Project: ".$row['Project']."
Sample: ".$row['Sample']."
Type: ".$row['Type']."' for='".$row['ProjID']."' class='chkbox-label'> ".$row['Project']." | ".$row['Sample']." | ".$row['Type']."</label>";
}
?>
</div>
...
How can I achieve this with my code?
All I need to do is change the SQL query within the PHP code (adding a WHERE clause) based on the state of the cake, biscuit or pudding checkboxes but I've been struggling to see how to do this.
Any help greatly appreciated!
You will have to do it with AJAX and each time the user clicks on a checkbox send the value to a different page and then you can either loop thru the results with PHP in the other page and return it in HTML or return the results and loop thru it with JS on the checkbox page
See a somewhat example:
$("#formName").on("change", "input:checkbox", function(){
//send $(this).val() with ajax
//Assuming you are selecting cakes and
//getting back an array with cakes
//you are the looping thru the array and gettig populating the html
var response = [];
var cakes = {};
cakes.description = 'Cake Description 1';
cakes.project = 'Cake Project 1';
response.push(cakes);
cakes = {};
cakes.description = 'Cake Description 2';
cakes.project = 'Cake Project 2';
response.push(cakes);
var formattedResponse = '';
response.forEach(function(res){
formattedResponse += `This is ${res.description} <br>`});
$('#responseContainer').html(formattedResponse);
});
<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<form action="" id="formName">
<label class="form-switch"><input type="checkbox" value="cake" id="filterCake"><i></i> Select Cakes only </label>
<label class="form-switch"><input type="checkbox" value="biscuits" id="filterBiscuit"><i></i> Select Biscuits only </label>
<label class="form-switch"><input type="checkbox" value="puddings" id="filterPudding"><i></i> Select Puddings only </label>
</from>
<div id="responseContainer"></div>
yes you can fetch data from database by making a dynamic query. Please try this.
$type = $post['type']; //'Cake','Biscuit','Pudding'
$queryProject = "SELECT DISTINCT ProjID, Project, Sample, Type, Description FROM PROJECTS WHERE Type = '" . $type ."' ORDER BY Project ASC";

Modify $select to allow for searching in php

How do I modify my $select function to allow searching with a database when the customer types in the search text and clicks "Search"? I'd also like to be able to type in the form field, and PHP automatically updates the page with the form data dynamically and to be able to define the field to search upon in the database!
This is letting me view my customers table:
$select = $db->query("SELECT * FROM customers ORDER BY id DESC");
<?php
if (!$select->num_rows) {
echo '<p>', 'No records', '</p>';
}else{
?>
<table border="1" width="100%">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
<?php
while ($row = $select->fetch_object()) {
?>
<tr>
<td><?php echo $row->FName;?></td>
<td><?php echo $row->LName;?></td>
First of all, you might try putting your opening <?php before rather than after the first line of code... :-)
Then you simply modify your code to get the values from your HTML form - I will assume that your search term is named q kind of like this:
Search: <input type="text" name="q" /> <input type="submit" name="search" />
Then your PHP script doing the searching will change the query to something like this:
$select = $db->query("SELECT * FROM customers WHERE FName LIKE '%$_REQUEST[q]%' OR LName LIKE '%$_REQUEST[q]%' ORDER BY id DESC");
If you are entered "Sam" that will end up with a query that looks like this:
$select = $db->query("SELECT * FROM customers WHERE FName LIKE '%Sam%' OR LName LIKE '%Sam%' ORDER BY id DESC");
Do note that I am showing you the simplest version by simply constructing the query. In fact you should NEVER do this with user-supplied data. Instead, you should prepare and then bind and then execute your statement. This is not just filler at the end of the answer - it's really important. But while you are testing you may want to see how it works just be forming a string as above.
To answer your "BONUS POINTS" - you can update the current page by simply including your search form on the same page as the PHP script which displays the results. Then you only process your PHP code if the submit button has been pressed. Your whole script (in a very simple form) might look like this:
Search: <input type="text" name="q" /> <input type="submit" name="search" />
<?php
if (isset($_REQUEST['search'])) {
# do your query
# loop through the results, printing them off in appropriate HTML
}
To answer your "BONUS BONUS" points, you would probably set up a pull-down ("select" in HTML) where the values of the options were the actual field names and the display was a human-readable form of that. If your select had the name "field_name" then you would modify your query like this:
$select = $db->query("SELECT * FROM customers WHERE $_REQUEST[field_name] LIKE '%$_REQUEST[q]%' ORDER BY id DESC");
Do note that you cannot prepare/bind to a column name, so you will just have to be very careful to validate that field very exactly (probably checking that it exists in a list of acceptable values).

multiple checkboxes used for search in php and mysql?

This seems to be a common question as I have seen plenty of similar questions.
however, none of the answers actually pointing out how to do the selecting from mysql database and this is my issue as the moment.
basically I have a table which I store the search data in it.
it looks like this:
id blond darkHair busty curvy
---------------------------------------------------
1 blond busty
2 dark hair busty curvy
3 blond curvy
4 blond curvy
and I have a form with checkboxes like so:
<form action="search.php" method="post">
<input name="keyword[]" type="checkbox" value="blond" />
<input name="keyword[]" type="checkbox" value="dark hair" />
<input name="keyword[]" type="checkbox" value="busty" />
<input name="keyword[]" type="checkbox" value="curvy" />
</form>
and the PHP codes like this:
if(isset($_POST['keyword']))
{
$keyword = $_POST['keyword'];
foreach ($_POST['keyword'] as $keyword) {
$keywordarray[] = mysqli_real_escape_string($conx, $keyword);
}
$keywords = implode (",", $keywordarray);
$sql = "SELECT * FROM girlsStaff
WHERE (`blond` LIKE '%".$keyword."%') OR (`darkHair` LIKE '%".$keyword."%') OR (`busty` LIKE '%".$keyword."%') OR (`thin` LIKE '%".$keyword."%')" or die();
$query = mysqli_query($conx, $sql);
Now, apart from converting this code to PDO or prepared statement, there is another issue which I don't understand!
it doesn't matter how many chechboxes i select... it always returns the result for last checked/selected checkbox value from mysql database....
is there something that I am missing?
i also, did echo $keywords at the top of my page to see whats being sent to the page and I get the value of all the selected/checked boxes being sent correctly.. so I know the issue is not there.
any help or advice would be appreciated.
You require to build query dynamically.
<?php
$clause = " WHERE ";//Initial clause
$sql="SELECT * FROM `girlsStaff` ";//Query stub
if(isset($_POST['submit'])){
if(isset($_POST['keyword'])){
foreach($_POST['keyword'] as $c){
if(!empty($c)){
$sql .= $clause."`".$c."` LIKE '%{$c}%'";
$clause = " OR ";//Change to OR after 1st WHERE
}
}
}
echo $sql;//Remove after testing
}
?>
<form method="POST" action="#">
<form action="search.php" method="post">
Blond: <input name="keyword[]" type="checkbox" value="blond" />
Dark Hair: <input name="keyword[]" type="checkbox" value="dark hair" />
Busty : <input name="keyword[]" type="checkbox" value="busty" />
Curvy; <input name="keyword[]" type="checkbox" value="curvy" />
<input type="submit" name="submit" value="Submit">
</form>
Sample queries
2 check boxes filled
SELECT * FROM `girlsStaff` WHERE `dark hair` LIKE '%dark hair%' OR `curvy` LIKE '%curvy%'
4 filled
SELECT * FROM `girlsStaff` WHERE `blond` LIKE '%blond%' OR `dark hair` LIKE '%dark hair%' OR `busty` LIKE '%busty%' OR `curvy` LIKE '%curvy%'
I think that small change from $keyword to $keywords will solve your problem :)
Now you are looking for items like your last value from $_POST['keyword'] array.
This line:
$sql = "SELECT * FROM girlsStaff WHERE (`blond` LIKE '%".$keyword."%') OR (`darkHair` LIKE '%".$keyword."%') OR (`busty` LIKE '%".$keyword."%') OR (`thin` LIKE '%".$keyword."%')" or die();
You should also use IN instead of LIKE if you have list aaa, bbb, ccc...., but then you will look for elements that have exactly same string in those fields.
After change to $keywords you will have:
... WHERE (`blond` LIKE '%".$keywords."%')
will also not work due to it will mean:
... WHERE (`blond` LIKE '%aaa,bbb,ccc%')
If you want to use like (if fields in DB only contain strings from array) then I suggest to build your query in foreach loop. Example:
$sql = "SELECT * FROM girlsStaff WHERE ".
foreach ($_POST['keyword'] as $keyword) {
$sql .= "(`blond` LIKE '%".$keyword."%') OR ";
}
//and here cut last four character " OR " part that will be unusefull
Typos:
$keywords = implode (",", $keywordarray);
^--- with an S
WHERE (`blond` LIKE '%".$keyword."%')
^--- without an S
You're stuffing in your original $_POST['keyword'] array. An array in string context is the literal word Array, so your query is actually executing as
WHERE (`blond` LIKE '%Array%')

PHP SQLITE Full Text Search

I have written an sqlite full text search which i am doing something wrong. If i type in my search "Puma Adidas" i want to search both words in the column MAKE.
At the moment it will only display one word if it exactly matches the search word. I just cannot figure out what i have missed, could i have some assistance please?
Thanks
HTML:
<form action="search.php" method="get">
Search: <input type="text" name="SEARCH">
<input type="submit" class="btn btn-default">
</form>
PHP:
$search_string = $_GET['SEARCH'];
$result = $db->query("SELECT * FROM PRODUCTS WHERE MAKE IN('$search_string') AND VISIBLE='YES' ORDER BY DATE DESC");
I did change the PHP code to this:
$result = $db->query("SELECT * FROM PRODUCTS WHERE MAKE LIKE ('%$search_string%') AND VISIBLE='YES' ORDER BY DATE DESC");
But it still does not work unfortunately, same issue.
Try using LIKE, not IN. IN is used for a different purpose.
$search_string = $_GET['SEARCH'];
$result = $db->query("SELECT * FROM PRODUCTS WHERE MAKE LIKE '$search_string') AND VISIBLE='YES' ORDER BY DATE DESC");
Check the syntax for the LIKE statement; you'll need to surround your search string with percent signs if you want to search the entire field for the search term.

Two Search Fields (One a drop down list) - PHP & MYSQL Code

I really would like some help on this as I'm pulling hair out!!!
I have two fields, one being an input box & the other being a drop down list which search the database and display the results, however I cannot seem to figure it out...here is what I have so far...
This is the actual search form:
<form id="myform" name="myform" action="<?php echo $_SERVER['PHP_SELF']?>" method="get"><br />
<div class="T1"><br /><p></div> <input name="term" type="text" value="<? php echo $_GET['searched']; ?>" size="10" maxlength="4" placeholder="e.g. BS1"/>
<select>
<option value="">I feel like...</option>
<option value="">Anything</option>
<option value="Indian">Indian</option>
<option value="Chinese">Chinese</option>
<option value="Thai">Thai</option>
</select>
<input type="submit" name="submit" value="Go"/>
</form>
And this is the PHP code:
<?php
if (isset($_GET['submit'])){
mysql_connect ("host", "user","password") or die (mysql_error());
mysql_select_db ("database");
$term = $_GET['term'];
$term = $_GET['option value'];
}
else
$sql = mysql_query("select pagetitle from Restaurant where extra like '%$term%' and showing like '1'");
$sql = mysql_query("select cuisine from Restaurant where cuisine like 'option value' and showing like '1'");
echo Restaurants in $term and Cuisine $option value:";
}
while ($row = #mysql_fetch_array($sql)){
echo ''.$row['pagetitle'];
echo '<br/>';
}
}
?>
The database has a table called Restaurant with two coloumns, one called 'Extra' which contains the postcode & the other called 'Cuisine' which containts the cuisine.
I would like it to return a list of restaurants that match both 'Extra' and 'Cuisine'
Any help will be greatly appretiated.
Echoing $_SERVER['PHP_SELF'] or $_GET['searched'] anywhere in your script (even in the form action) will open your site up to XSS attacks. Do not do this unless you sanitize them first.
For all new projects, it is recommended to use prepared statements for mysql queries. You can do this with either mysqli or PDO. Your code is just asking for SQL injection by the looks of what you are trying to do.
You are missing a bracket in your code and you have some extra ones at the end. Also after echo you're missing a quotation mark. I'm not sure what's going on there. Try to get those fixed.
What is with the # before mysql_fetch_array() ? There are really very few cases where # should ever be used in PHP. It is usually an indicator that there is some sort of error somewhere in your code that should be fixed instead of suppressed.
Your needs a name attribute if you want to be able to use it in PHP.
In your SQL query, you should not be using LIKE when you should be using equals. Also, you should not quote integers.
Why are you echoing an empty string like echo ''.$somevar; ? Just echo the variable.
I'm not sure what "showing" is for but I assume is a record that can be displayed. The first thing to do is update your query:
$sql = mysql_query("select pagetitle, cuisine from Restaurant where (extra like '%$term%') and (showing like '1') and (cuisine like 'option value')");
You also need to check if the user did not enter an option or selected 'anything' in which case the query needs to be changed a little:
$sql = mysql_query("select pagetitle, cuisine from Restaurant where (extra like '%$term%') and (showing like '1') and (cuisine like 'option value' or 'option value' = '')");

Categories