MySQL statement with wildcards using PHP is not working - php

Solved: Not sure why, but after I reloaded LAMP stack everything started to work just fine. Thank all of you for help!
I have following MySQL statement prepared in PHP:
SELECT * FROM my_table WHERE (country LIKE 'Latvia' AND phone NOT LIKE '371%')
which selects records with incorrect country phone codes.
In php it looks like this:
$sql = "SELECT * FROM {$table_name} WHERE (
country LIKE '$country' AND phone NOT LIKE '$phone_code%')";
While it perfectly filters records in phpMyAdmin, it doesn't works in my application - I get all of the records in including correct ones. Your help is really appreciated!
EDIT:
Here's how more code looks like:
while ($row = $this->fetch_array($result_set)) {
$countries_to_check[$row['short_name']] = $row['calling_code'];
}
$i = 1;
$sql = "SELECT * FROM {$this->table_name} WHERE ";
foreach ($countries_to_check as $country => $phone_code) {
if ($i > 1) {
$sql .= " OR ";
}
$sql .= "(country LIKE '".$country."' AND phone NOT LIKE '".$phone_code."%')";
$i++;
}
$result_set = $this->query($sql);
As I wrote in comments, all the variables are not empty, I have echoed $sql and even ran this query in phpMyAdmin, with success.
Result looks like this:
country phone
Lithuania 37028694529 * Correct
Latvia 37122171755 * Correct
Latvia 37522433153 * Incorrect
Latvia +37126378238 * Incorrect

Or with curly syntax
$sql = "SELECT * FROM {$table_name} WHERE (
country LIKE '{$country}' AND phone NOT LIKE '{$phone_code}%')";

It must be this way:
$sql = "SELECT * FROM {$table_name} WHERE (
country LIKE '".$country."' AND phone NOT LIKE '".$phone_code."%')";

Related

Auto complete suggestion box are not working properly?

code:
<?php
include('config.php');
$return_arr = array();
$term = $_GET['term'];
$term = str_replace('.','',$term);
$sql = "SELECT * FROM submission where keyword like '%".$term."%' or companyname like '%".$term."%' ORDER BY CASE WHEN keyword LIKE '%".$term."%' THEN 1
ELSE 2 END";
$r = mysqli_query($link,$sql);
while($row = mysqli_fetch_assoc($r))
{
$key = explode(",", $row['keyword']);
foreach ($key as $keyword)
{
$return_arr[] = $keyword;
}
}
echo json_encode($return_arr);
?>
In my code I have created a auto complete suggestion box and its working but it always showing wrong result if I write (i) it always show result with (a) alphabet why not (i) and also want to search with short name. So, How can I do this ?Please help me.
Thank You
if you want to compare result start with input character then remove % from beginning
$sql = "SELECT * FROM submission where keyword like '".$term."%' or companyname
like '".$term."%' ORDER BY CASE WHEN keyword LIKE '".$term."%' THEN 1
ELSE 2 END";
You used %$term% in your query. So whether the data store the searched keyword anywhere in the string, it will display to you. So if you want to search the data start with a specific character remove % from the start of your query to make it as $term% as
$sql = "SELECT * FROM submission where keyword like '".$term."%' or companyname
like '".$term."%' ORDER BY CASE WHEN keyword LIKE '".$term."%' THEN 1
ELSE 2 END";

sql select where like statement with many OR operands

I am trying to write a simple search function that reads in a string $query.
my question is, can I use multiple ORs in a select statement? I am trying to search one string to see if it matches many column values, then print those rows.
function search($query) {
try {
$db = db_open();
$sql = "select * from pms where (name like :query) or (state like :query) or
(start like :query) or (finish like :query) ";
$statement = $db->prepare($sql);
$statement->bindValue(':query', $query);
$statement->execute();
$pms = $statement->fetchAll();
} catch(PDOException $e) {
die("Error: ".$e->getMessage());
}
return $pms;
}
This is not working, except when i search for a state.
Thanks
For sure.
SELECT * FROM pms WHERE (name LIKE :query) OR (start LIKE :query) OR (finish LIKE :query)
Should work just fine.
1) use backtick in table nam eand column names.
2) use bracket for each or for more clear understanding
3)if you are not using binding then use wildcat (%) with quotes .
try like this:
$sql = "select * from `pms`
where (`name` like '%query%')
OR (`state` like '%query%')
OR (`start` like '%query%')
OR (`finish` like '%query%') ";

How to make query that ignores undefined variables?

How make mysql search defined just by what is written in html form, by user, and if some form box is stayed empty, mysql should ignore it. For example:
$sql = "SELECT * FROM catalog WHERE name= '".$name."' AND publisher = '".$publisher."' ";
mysql_query($sql);
This query will display all rows where name and publisher are together. Now, what if user insert just name, and left publisher box empty. The idea is that php/mysql ignore empty form box, and display every row with inserted name. But it will not do that because $publisher will be undefined, and error emerges. How to tell musql to ignore $publisher? More generally, the question is: how to generate query that make searching defined by certain criteria if they exists, and if they don't how to just ignore it?
You can build up the sql programmatically. I am assuming you have escaped the values properly.
$sql = "SELECT * FROM catalog";
$wheres = array();
if (!empty($name)) {
$wheres[] = " name = '$name'";
}
if (!empty($publisher)) {
$wheres[] = " publisher = '$publisher'";
}
if (count($wheres)) {
$sql .= " WHERE " . implode (' AND ', $wheres);
}
//RUN SQL
Also have a read through this, you are using a deprecated mysql library.
This will allow either the name or the publisher to be NULL.
<?php
$sql = "SELECT * FROM catalog WHERE (name= '".$name."' OR name IS NULL) AND (publisher = '".$publisher."' OR publisher IS NULL)";
mysql_query($sql);
Try like
$my_var = " ";
if($publisher) //if(!empty($publisher))
$my_var = " AND publisher = '".$publisher."' ";
$sql = "SELECT * FROM catalog WHERE name= '".$name."' ".$my_var;
if the publisher is empty then you need to pass the NULL value and PLZ note that it is a bad practise.It will causes many sql injection issues.Try to put validations for the things

Php select * where like

Hi I am trying to get a search working for a site. It has 2 inputs for taking in info, one is a dropdown.
<div id="search">
<form action="projectsearchall.php" method="post" enctype="multipart/form-data">
<h3>Search for an Item</h3>
<p>Keywords</p><p><input name="keywords" type="text" value="keywords"></p>
<p>Select A Location</p><p>
<select name="location" id="jumpMenu">
<option>Any Location</option>
<option>Antrim</option>
<option>Armagh</option>
<option>Carlow</option>
<option>Cavan</option>
</select>
</p>
<p>
</form>
</div>
I cannot seem to figure out how to combine the 2 inputs to give a result, I can do it separately, but not working together to get a more accurate result.
php
$keywords = $_POST['keywords'];
$keylocation =$_POST['location'];
$username = $_SESSION['username'];
//MySQL Database Connect
include 'connect.php';
//make sql query
$result = mysqli_query($con,"SELECT * FROM projectitem where description like '%$keywords%' or item like '%$keywords%' or location like '%$keywords%'");
Thanks in advance!
I think you may do some preprocessing, before running your query.
First off, you need to give your select options some sort of value to check against.
I don't know your exact database structure, but assuming that you're working with the select texts, you may want to try this:
$query = "SELECT * FROM projectitem WHERE (description LIKE '%$keywords%' OR item LIKE '%$keywords%')";
This is your base query and running it right now will check against the keywords, but no location.
if($keylocation != "Any location") $query .= " AND location = '$keylocation'";
This last line will add the location as additional filter to your query. Run it, and see what it does. (I'm not sure about the string comparison there though)
Ah yes, as a final advice: Be sure to run your input through the escape function mysqli_escape_string. Otherwise you're opening yourself to SQL injections.
You're not actually using the value of $keylocation; to narrow searches down, you need an AND instead of OR:
$stmt = mysqli_prepare($con, 'SELECT * FROM projectitem
where (description LIKE ? OR item LIKE ?) AND location LIKE ?');
mysqli_stmt_bind_param($stmt, 'sss', "%$keywords%", "%$keywords%", "%$keylocation%");
mysqli_stmt_execute($stmt);
// etc.
Update
Since the drop down may have "any location" you would need to dynamically change your query:
$sql = 'SELECT * FROM projectitem WHERE 1'; // base query
$types = ''; $vars = array();
if (!empty($keywords)) {
$sql .= ' AND (description LIKE ? OR item LIKE ?)';
$types .= 'ss';
$vars[] = "%$keywords%";
$vars[] = "%$keywords%";
}
if ($keylocation != 'Any Location') {
$sql .= ' AND location LIKE ?';
$types .= 's';
$vars[] = $keylocation;
}
$stmt = mysqli_prepare($con, $sql);
if ($types) {
mysqli_stmt_bind_param($stmt, $types, $vars);
}
mysqli_stmt_execute($stmt);
first you have sql injection
use mysqli_real_escape_string
if keywords for example is null your query will be like this
$result = mysqli_query($con,"SELECT * FROM projectitem where description like '%%' or item like '%%' or location like '%$keylocation%'");
and description like '%%' return all row !
you must check data first
$query = "SELECT * FROM projectitem where 1=1 "
if($keywords)
$query .= " AND ( description like '%$keywords%' AND item like '%$keywords%' )";
if($keylocation)
$query .= " AND location like '%$keylocation%'";

How to select all where the condition is null?

I have a php code with a query:
$query = "SELECT * FROM TDdb WHERE status = $status AND occupation =$occupation";
I am sending the values status and occupation with a client application to this php code.
This works when I send both status and occupation. But I want it to return rows if I just send status but not occupation also ( I mean no matter what the occupation is).
does anyone have any suggestions?
I would appreciate any help.
PS: I want to do it without if statement and just but changing the query
Personally I would create a base query and append conditions wherever you have them, like so:
$sql = 'SELECT * FROM TDdb';
$conditions = array();
$args = array();
if ($action) {
$conditions[] = 'status = :status';
$args[':status'] = $status;
}
if ($occupation) {
$conditions[] = 'occupation = :occupation';
$args[':occupation'] = $occupation;
}
if ($conditions) {
$sql .= ' WHERE ' . join(' AND ', $conditions);
}
$stmt = $db->prepare($sql);
$stmt->execute($args);
Looks like you've got a few good options for how to do it in SQL, or how to make the SQL string variable in PHP.
One reason to consider using an 'if' in the PHP code for the database access performance.
When you introduce an 'or' condition like that in SQL, you're not going to get index access. It is much harder for the database to determine what path it should take than for the PHP code because the SQL engine optimizes the query without knowing what the variable will resolve to at execution.
You already know in the PHP which version of the query you really want. This will perform better if you make that choice there.
This will work if you pass an occupation or a NULL value.
SELECT *
FROM TDdb
WHERE status = $status
AND ($occupation IS NULL OR occupation = $occupation)
"SELECT * FROM TDdb WHERE status = '$status' AND (occupation = '$occupation' OR occupation IS NULL)";
Apart from the solution provided by #Tom and #Damien Legros, you may create two query strings one with occupation and one without occupation. Something like:
$query = "SELECT * FROM TDdb WHERE status = $status";
if ($occupation != "") {
/*When you have value for occupation*/
$query .= " AND occupation =$occupation";
}
So in this case, data will be returned if you have only the status field. Secondly, please check if the status and occupation fields in table are varchar then you have to enclose them in single quotes (').
Thanks everyone for help. specially jack.
finally i created my query like this:
$query = 'SELECT * FROM TDdb';
if ($status) {
$query = $query." WHERE status = '".$status."'";
}
if ($occupation) {
$query = $query." AND occupation = '".$occupation."'";
}

Categories