I am building a bus reservation system using php & mysql.
In here I am trying to input the search field "route" which is fields of the mysql table.
It seems to have problem in searching and printing the results to the page. Please help me out.
<?php
$connect=mysqli_connect("localhost","root","","tsms");
$output ='';
if(isset($_POST['from'])){
$searchq = $_POST['from'];
$query = mysqli_query("SELECT * FROM bus WHERE route='$serchq' ");
$count = mysqli_num_rows($query);
if($count==0){
echo "<script>
alert('No bus services are found');
</script>";
} else {
while($row = mysqli_fetch_array($query)){
$imageData = $row['image'];
$arrival = $row['arrival_time'];
$departure = $row['departure_time'];
$type = $row['bus_type'];
$class = $row['class'];
$name = $row['bus_name'];
$facilities = $row['facilities'];
$reservation = $row['reservation_fee'];
$output = '<div>'.$arrival.''.$departure.''.$type.''.$class.''.$name.''.$facilities.''.$reservation.'</div>';
}
}
}
echo $output;
?>
Not sure where is the problem, but the sql comparison with "=" searches for a perfect match. Try to use the "like" as
SELECT * FROM bus WHERE route like '%$serchq%'
also, do escape the serchq, because you can get hacked this way.
In your search form, do you have a (dropdown) input or a simple text input?
In your sql query, you are searching for an exact match.
Should this be your issue, consider changing "route='$serchq'" to "route LIKE $serchq" for a more broad match. Also the quotes are not necessary around $serch so eliminating them might help.
Related
I have a web application and I'm trying to modify one of the queries. The query fetches information (from a table named voyage_list) and returns various fields.
I want to modify the query so that it is based on certain filters the user applies (which will be placed in the URL).
I can't get the query to work in the web application, but if I copy the query and execute it directly within PHPMyAdmin, it works fine.
$vesselFilter = $_GET['vesselFilter'];
$vesselArray = explode(',', $vesselFilter);
$arrayCount = count($vesselArray);
$sqlExtend = ' status = 1 AND';
foreach ($vesselArray as $value) {
$i = $i + 1;
$sqlExtend .= " vesselID = '$value'";
if ($i < $arrayCount){
$sqlExtend .= " OR";
}
}
$newQuery = "SELECT * FROM voyage_list WHERE" . $sqlExtend;
echo $newQuery;
$query = $db->query($newQuery)->fetchAll();
I appreciate the above is pretty messy, but it's just so I can try and figure out how to get the query to work.
Any help would be greatly appreciated!
Thanks
That query probably doesn't return what you think it does. AND takes precedence over OR, so it will return the first vessel in the list if the status is 1, and also any other vessel in the list, regardless of status.
You'd do better to create a query with an IN clause like this:
SELECT * FROM voyage_list WHERE status = 1 AND vesselID IN(8,9,10)
Here's some code to do just that:
$vesselFilter = $_GET['vesselFilter'];
// Validate data. Since we're expecting a string containing only integers and commas, reject anything else
// This throws out bad data and also protects against SQL injection.
if (preg_match('/[^0-9,]/', $vesselFilter)) {
echo "Bad data in input";
exit;
}
// filter out any empty entries.
$vesselArray = array_filter(explode(',', $vesselFilter));
// Now create the WHERE clause using IN
$sqlExtend = 'status = 1 AND vesselID IN ('.join(',', $vesselArray).')';
$newQuery = "SELECT * FROM voyage_list WHERE " . $sqlExtend;
echo $newQuery;
$query = $db->query($newQuery)->fetchAll();
var_dump($query);
I have a variable ($city) that pass through from other page and would like to select out from my database. However, I would only allow either one of the mysql_query to be selected when either of the condition is met but for my case it only work for the second condition. I apologize that I am lack of experience in php but would appreciate if anyone can assist here. thanks.
$allcity = "AllCity";
if (($city) == ($allcity))
{
$sql = mysql_query("SELECT * FROM upload WHERE allcity = '$city'");
}
else
{
$sql = mysql_query("SELECT * FROM upload WHERE city = '$city'");
}
while ($row = mysql_fetch_array($sql))
{
echo $id = $row['id'];
echo $lat = $row['lati'];
echo $long = $row['longi'];
echo $name = $row['name'];
echo $country = $row['country'];
echo $city = $row['city'];
echo $price = $row['price'];
}
As others have stated, stop using mysql_.
However, if the ($city == $allcity) doesn't match, you need to look at the $city-variable, to see if that contains spaces or other "hidden" characters breaking the match.
Do a var_dump($city)before the if/else, to check the string and see if it's actually 7 characters long. Also, to avoid capitalization errors, you might wanna do something like (strtolower($city) == strtolower($allcity)) and see if that works.
As I am learning PHP, naturally, I decided to create a search feature on my webpage. However I wanted to make mine more unique, so rather than using just a simple html input field as the 'search' field, I created two html select tags which allow the user to select two options and search based upon that. I managed to get the php to generate the search query, however it wasn't the sql query I wanted. My php code managed to generate a query hat looked like this: .com/results.php?option1=london&option2=car whereas ideally I want it to generate something like this: .com/results.php?combinedoptions=london+car
I've researched thoroughly into this and I hate to ask, what may be, a very simple question on this site.
$input = $_GET['input'];
$topic = $_GET['topic'];
$location = $_GET['location'];
$combined = $input . $topic . '' . $location;
$terms = explode(" ", $combined);
$query = "SELECT * FROM search WHERE ";
foreach ($terms as $each){
$i++;
if ($i == 1)
$query .= "keywords LIKE '%$each%'";
else
$query .= "OR keywords LIKE '%$each%'";
}
You would just split the incoming string. Here's a piece of code:
<?php
$combinedoptions = 'london+car';
$array = explode("+", $combinedoptions);
if (sizeof($array) != 2) { /*problem here*/ echo 'bad parameters'; return; }
$option1 = $array[0];
$option2 = $array[1];
?>
Just using the explode() method. Compiled code.
I have made a php search bar before, which worked fine. However, I have recently been developing a one-file web app using the jQuery mobile framework. The aim is to be able to search for a certain trade, person or business, but the results are not showing up. If you search, and there are no results, the message in the output variable prints "There are no results" on the page. The code for the search bar is below:
if(isset($_POST['search'])){
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i", "", "$searchq");
$squery = mysql_query("SELECT * FROM users WHERE name LIKE '%$searchq%' OR fname LIKE '%$searchq%' OR lname LIKE '%$searchq%' OR trade LIKE '%$searchq%' LIMIT 10") or die("Could not search");
$counts = mysql_num_rows($squery);
$output = '';
$outputs = '';
if($counts != 0){
while($row = mysql_fetch_array($searchq)){
$ids = $row['id'];
$fnames = $row['fname'];
$lnames = $row['lname'];
$trades = $row['trade'];
$abouts = $row['about'];
$emails = $row['email'];
$numbers = $row['number'];
$names = $row['name'];
$output .= '<div>'.$trades.' '.$ids.'</div>';
}
}else{
$output = 'Sorry there were no results';
}
}
I print this to the page with:
<h1><?php print($output); ?></h1>
It may also be worth noting that the first feature using php (the sign up form) worked perfectly, but the login form on the same page didn't, and neither does the search bar; I am wondering if having different forms on the same page accessing the same database may cause some kind of problem. If anyone requires any more code, just leave a comment. Thank you in advance.
$searchq = preg_replace("#[^0-9a-z]#i", "", "$searchq"); Should be $searchq = preg_replace("#[^0-9a-z]#i", "", $searchq);
i guess this would work fine now.
http://se1.php.net/preg_replace last one should be a variable containing a string and not a string it self.
I think you may use == instead of one =. Please make the change and tell me if it works. It should look like this
if($counts ! == 0)
I'm posting from the HTML code shown in this jsfiddle to the PHP page for which the code is below. The issue is that the array $_POST['selectedpost'] isn't being received. That's the array containing which checkboxes were ticked. In the js fiddle I added in an example row to the table containing the checkboxes as normally these are generated using PHP and SQL.
<?php
include "connect2.php";
if (isset($_POST['selectedpost'])) {
$postschecked = $_POST['selectedpost'];
$length = count($postschecked);
}
else{
returnpage();
}
if (isset($_POST['deleteposts'])) {
foreach($postschecked as $post_id){
$sql = "DELETE FROM posts WHERE post_id='$post_id'";
mysql_query($sql);
}
returnpage();
}
if (isset($_POST['passposts'])) {
foreach($postschecked as $post_id){
$sql = "UPDATE posts SET moderation=1 WHERE post_id='$post_id'";
mysql_query($sql);
}
returnpage();
}
if (isset($_POST['editpost'])) {
if ($lenght==1){
foreach($postschecked as $post_id){
header("location:editpost.php?post_id=$post_id");
}
}
else{
returnpage();
}
}
if (isset($_POST['returnpost'])) {
if (isset($_POST['reasonreturned'])) {
foreach($postschecked as $post_id){
$sql = "SELECT description FROM posts WHERE post_id='$post_id'";
$query = mysql_query($sql);
$array = array();
while ($row = mysql_fetch_array($query, MYSQL_NUM)) {
$array[] = $row; }
$description = "".$array[0][0];
$description = $description . "<br/><br/><span style='color:red;font-size:18px;'>" . $_POST['reasonreturned'] . "</span>";
$sql = "UPDATE posts SET description='$description' WHERE post_id='$post_id'";
$query = mysql_query($sql);
}
}
foreach($postschecked as $post_id){
$sql = "UPDATE posts SET moderation=3 WHERE post_id='$post_id'";
$query = mysql_query($sql);
}
returnpage();
}
if ($length){
returnpage();
}
function returnpage(){
//header("location:moderate.php");
}
?>
http://jsfiddle.net/3A6az/2/
Also extra note, I am aware as to how un-efficient my code is in places and I'm also aware to the fact I should drop mysql and move to something like mysqli. Thank's for any help given
If you have more than 1 checkbox you need to use
name='selectedpost[]'
It will then be available to you with $_POST['selectedpost']; as an array.
Hope this helps!
You're using an unbracketed input <input type='checkbox' name='selectedpost' value='404'></input> plus you don't need </input> <(FYI)
If anything you shouldn't be using value='404' unless that's what you want to pass as a "value".
You probably meant to use multiple checkboxes and using name='selectedpost[]'
I.e.:
<input type='checkbox' name='selectedpost[]'>
Using square brackets [] are treated as an array.
Footnotes:
I would like to point out though, that switching to mysqli_* functions would be most beneficial. mysql_* functions are deprecated.
Using mysqli_* functions with prepared statements or PDO would be even better in order to protect yourself from SQL injection.
Here is a guide on how to prevent SQL injection: How can I prevent SQL injection in PHP?
N.B.: I also found a typo which may give you trouble if ($lenght==1){
You have the word $length in your code as well. Change it to if ($length==1){