How to write a like query in PHP - php

I have a PHP string with a like query - something like this:
$select = "select category_id, category_name from categories where category_name like %"'.$category.'"%;
But I am pretty sure this is totally wrong, and I am getting confused in the million quotes :)
Whats the right way to put this query together?
Thank you!!

You want the % wildcards in the string, not outside it.
Also, If you want to evaluate the php variable in the string, you should brace the variable.
" select category_id, category_name from categories where category_name like '%{$category}%' "
or concatenate it
" select category_id, category_name from categories where category_name like '%" . $category . "%' "

If you're looking for "best practices", you should look into prepared statements using the mysqli class. That being said,
Your quotes are backwards around the $category variable (it's "', it should be '")
The %'s in your statement should be inside the quotes ('), not outside them

I'm pretty sure it's just:
$select = "select category_id, category_name from categories
where category_name like '%$category%'";

You can use positional parameters. Not sure what database server you're using, but say you're using the PDO layer, then have a look at PDO::prepare.

It would be better to do it a different way but to answer the question, if you use double quotes you not need to concatenate the variable with the dot
$select = "select category_id, category_name from categories where category_name like '%{$category}%'";

You messed up the quotes
"select [...] like '%".$category."%'";
That will become
select [...] like '%something%'
But you should use query parameters, to avoid sql injections

This will be relatively functional:
$select = "select category_id, category_name from categories where category_name like '%"
.mysql_real_escape_string($category)."%'";
However, you'll probably want to additionally escape characters that have special meaning inside of a LIKE, including %
Note also that mysql will not be able to use an index to optimize this query, meaning it won't perform on large databases. You may wish to investigate myISAM fulltext indexes for text search over a large dataset.

Related

Get an array of all columns starting with the same characters.

This is quite difficult to explain in the title, so I'll do my best here. Basically I have a column in a MySQL products table that contains rows like:
FEL10
FEL20
FEL30
PRO05
PRO07
PRO08
VAI12
VAI13
VAI14
These are the categories ("FEL","PRO","VAI") and a identification number of my products ("10", "20" and so on). I need an SQL select query that creates me a textual array like:
FEL*
PRO*
VAI*
With this array I need to create a listbox, that allows me to choose a category (regardless of the identification number). Once I choose a category, let's say PRO*, I will need to do the reverse action: print all the products info related to PRO05, PRO07 and PRO08.
How do you think you can achieve this? I have been trying using the DISTINCT statement but I need to filter only the first characters, otherwise it will be useless. I also tried the SUBSTRING() and LEFT() functions, but they seem not to be working (I get an SQL Syntax error).
--
Thanks for your help as always
What is wrong with?
SELECT distinct left(col, 3) as category FROM `table1`
MySQL LIKE to the resque:
SELECT col1 FROM table1 WHERE col1 LIKE 'FEL%';
This way you have to add all cases using OR.
Alternative - REGEXP:
SELECT col1 FROM table1 WHERE col1 REGEXP '(FEL|PRO|VAI).*'
Then it's just a matter of writing proper regex.
I would use extra col to group your items - to avoid such selecting altogether (which should be quite expensive on bigger dataset).
https://dev.mysql.com/doc/refman/5.1/en/regexp.html#operator_regexp
To get the list of the 3-letter codes use:
select distinct left(combicode, 3)
from mytable;
When a user selects one of the values use this to get all matching entries:
select *
from mytable
where combicode like concat(#category, '%');
(Aside from that: It's a bad idea to have concatenated values in one column. Why not have one column for the category and another for the product code? Then there would be no problem at all.)

Is it possible to treat hyphens and spaces the same in SQL?

So I'm working on a search function for a social networking site, and it searches user posts. Some users like to put hyphens instead of spaces, but I would like for the search function look for both hyphens and spaces in a result.
For example, if they have a post named "SQL-IS AWESOME" and I search for "SQL IS AWESOME", can I still find that post? I tried using 2 sql queries, one for the original search query, and one modified to change all spaces to hyphens.
But if I search "SQL IS-AWESOME" it still won't find it. Is there an easier way?
My current code:
$sql = "SELECT * FROM posts
WHERE (post_title='".$query."'
OR post_title LIKE '%".$query."'
OR post_title LIKE '%".$query."%'
OR post_title LIKE '".$query."%')
".$locquery."
".$cat."
ORDER BY date DESC
LIMIT 18";
As someone has suggested, you could just adapt and use fulltext searching.
If you choose to take this route, you will need to enable fulltext searching on the fields required.
I'll assume you will check post_title and post_body (?), which needs you to run this;
ALTER TABLE `posts` ADD FULLTEXT KEY `post_search` (`post_title`,`post_body`);
When that is done, your search query can easily be edited to become;
$sql = "SELECT * FROM `posts` WHERE MATCH(post_title,post_body) AGAINST '$search'";
If you'd like better matching, it is also possible to give it a score and order by that, which would require code similar to this:
$sql = "SELECT *, MATCH(post_title, post_body) AGAINST ('{$search}') AS score ".
"FROM `posts` WHERE MATCH(post_title, post_body) AGAINST ('{$search}') ORDER BY `score` DESC";
--- NOTES
For the search, you need to work out how you will be searching.
In the last instance I used similar, I simply had a form for the search term (Named "Search") resulting in $_POST['search'] being sent to the server.
I then used;
$search = (array_key_exists('search', $_POST) && is_string($_POST['search'])) ? mysql_real_escape_string($_POST['search'], $c) : FALSE ;
if ($search) {
// Do the fulltext query requires (See above)
}
Since fulltext search will disregard the hyphen, you are left with just spaces, which works great for fulltext, if you opt to use scored results.

Is this MySql Query Statement correct?

I would like to know whether this MySql statement will be executed correctly,
"SELECT sum(price) FROM products WHERE productid IN (SELECT productid FROM shoppingcart WHERE sessionid=".$this->$sessionid.")"
And if not please give me pointers as to where I am wrong.
Thanks
I'm sure you meant
$this->sessionid
not
$this->$sessionid
(the second one returns value of property, which name is stored in sessionid, thus, when $sessionid is 'abcdef', it tries to return value of $this->abcdef property).
Also, enclose in ' AND escape all parameters.
"SELECT sum(price) FROM products WHERE productid IN (SELECT productid FROM shoppingcart WHERE sessionid='".mysql_escape_string($this->sessionid)."')";
i am using sql server but i think error over here is
single quote ' is required for session id
"SELECT sum(price) FROM products WHERE productid IN (SELECT productid
FROM shoppingcart WHERE sessionid='".$this->$sessionid."')"
Seems fine to me.
As #praynay said, I believe you need quotes around the session id.
Also, be very, very sure $this->sessionid will not have a quote character in itself, or that you escape it properly before passing it to MySQL. (Or better yet, use a parameterized query.)

Find Rows in Vertical Line-separated values in MySQl?

Let say i have a field 'category' with the value '1|2|3'. I want to search in mysql such that it will return all rows matching my search parameter into the values of the category.
for example:
$cat_id = 1;
SELECT * FROM `myTable` WHERE cat_id is equal or found in category with values '1|2|3'...
something like that..i do not know how to put it in correct sql query.
Any Ideas? thanks in advance.
Well you could manage it using the MySQL-specific regex operator:
WHERE category RLIKE '(\\||^)'+cat_id+'(\\||$)'
(Assuming MySQL non-standard backslash escapes are enabled, which they are by default.)
However, this kind of query is not indexable and it's generally considered extremely poor schema design to fudge multiple datapoints into one column like that. The usual solution is a join table of myTable to category.
this must be a table "category", not field.
SELECT * from mytable, cattable, where cattable.id=1 and cattable.mid=mytable.id

mysql php query HAVING clause

Im trying to get this query to work but i get this error:
Unknown column 'zips.city' in 'having clause'
`$query = "SELECT
zips.*
FROM
zips
HAVING
zips.city LIKE '%$city%'
AND
zips.stateabbr LIKE '%$state%'
LIMIT 1";
$result = mysql_query($query) or die (mysql_error());`
my zips table has a city column, so im not sure what the problem is, i know im accessing the database because i can run this query with no errors:
$zip1query = "SELECT
zips.*
FROM
zips
WHERE
zips.zip = '$zip'
";
any advice would be much appreciated! thanks!
The having clause doesn't mean the same thing as the where clause : when running a simple query, you should use where -- which is what you did in your second query, that works.
having is used when the condition has to be applied on the result of a group by clause.
Which means that, here, your query should be build this way :
$query = "SELECT zips.*
FROM zips
where zips.city LIKE '%$city%'
AND zips.stateabbr LIKE '%$state%'
LIMIT 1";
With that, if you still have an error about a non-existing or not-found column (at least for city and/or stateabbr), it'll be because that column doesn't exist in your table.
In this case, there is not much we can do : you'll have to check the structure of your table, to determine which columns it contains.
You can check that structure using a web-based tool like phpMyAdmin, or using an SQL instruction such as :
desc zips;
For reference, quoting MySQL's manual page for select :
The SQL standard requires that HAVING
must reference only columns in the
GROUP BY clause or columns used in
aggregate functions. ...
Do not use HAVING for items that
should be in the WHERE clause.
For example, do not write the
following:
SELECT col_name FROM tbl_name HAVING col_name > 0;
Write this instead:
SELECT col_name FROM tbl_name WHERE col_name > 0;
...
The HAVING clause can refer to
aggregate functions, which the WHERE
clause cannot
Try using WHERE instead of HAVING.
The proper way to do it is by using a WHERE clause.
$query = "SELECT
zips.*
FROM
zips
WHERE
zips.city LIKE '%$city%'
AND
zips.stateabbr LIKE '%$state%'
LIMIT 1";
HAVING is to be used when you are GROUPing, see here for an explanation
o jeez sorry guys i figured out the problem, apparently i put a space before city when i named the columns in my table. so i renamed the column and it works thanks anyway chaps! but using the where function instead of having must speed things up alot, thanks guys!

Categories