Checking value in an array inside one SQL query with WHERE clause - php

I want to know is this practically possible in sql(using php as server-side), where in you have an array of values(numbers), and you try to retrieve data based on values inside that array..
I have a sql table:
posts(
id int(11) primary key,
posts varchar(140),
user_id int(11) foreign key
);
I write a query now to retrieve 'posts':
$query="SELECT * FROM posts WHERE user_id=(**Array of select user_id's**)";
Is there any sql in-built function to check values inside an array? or should I be using PHP for this?
I am actually trying to implement the twitter model of showing posts of people whom we follow.

Yes, this is easily possible. You need to look at MySQL's IN function
Your query would be something like
SELECT * FROM posts WHERE user_id IN (1,2,3,4,5,6)
You can build the bit in between the parentheses in PHP using implode()

SQL can't parse PHP arrays. Try this:
$query="SELECT * FROM posts WHERE user_id IN ({implode(',', $userIDarray)})";

Take a look at this page : WHERE ... IN. You can use the IN operator to check if a certain value exists within an list of values.

Yea you will have to you use following syntax
SELECT 'value'
IN (array)

Related

How to give relational condition in pg_select function

In pg_select function the third argument is a array used to specify the column name and its value.
It works like an and condition if we give more than one key => value.
I have id column in my table I want to fetch the rows which has id value more than 1000.
How to give value in associative array in pg_select function for the above requirement.
I need answer without using pg_query function.
Unfortunately, pg_select is too simple for this. You have to write the full query one way or another.
you can using SQL:
pg_query("select * from table_name where id <1000 ");

sql statement syntax for search

I would like to write an sql statement for search. Here is sample database structure.
For eg, I want to display all records with topic '13'. How can i write sql query for searching 13 from the above structure? Any suggestions?
Can i able to use WHERE Topic LIKE '%13%'? Anything wrong with this?
Try this one:
SELECT * FROM `TABLE_NAME` WHERE `Topic` LIKE "%13%";
It's better and faster to save it in a third table of many-to-many relationship.
If you want to save as per your example (single table), try to save data as eg ",10,13,15,"
always have coma before and after, thus the following sql will exclude 213 and 132 etc
select * from table_name where Topic like '%,13,%'
select * from table where find_in_set("13",topic);
or if topic is not used as a set, you could do ...
select * from table where concat(",",topic) like "%,13,%";
The 2nd isn't real elegant but I've had to do that a couple times.
Because the data isn't really normalized, I used concat to add a comma to the topic field so I could make sure the "like" comparison would pass with a comma before and after the value. I suppose we would also have to remove any unwanted spaces as well for this example, so ultimately it would end up like:
select * from TABLE where concat(",",replace(topic," ","")) like "%,13,%";
Ultimately, we have to know what to expect in the topic column to come up with a query that would always work. In the past, I've had situations where I would add values to a string field (i.e. topic) with a delimiter before and after each value like:
(1)(2)(3)(14)(15)(255)(283)
If you did something like this for the topic field, the query is simple ...
select * from table where topic like "%(13)%";

check if exists in two coma separated values mysqli

I am having an issue where I have a table in a database which stores values in this form 1,3,4,55,6,22,44 and I have an array which is dynamic from the client side it can be like 2,55,33,1,33,99
I want to make a query to select this field if the at least any value matches between the fields.
Like select the field if in the database value there exists 24 and I have 23,24,55,66 from the user array
I think this can be done with find_in_set() or the IN keyword
It is not a good practice to create comma seperated values in a column. Usually people feel that it was the easiest and simplest method, but it is not. Searching and modification will be so hard. Find set can be used if you have a single item to search ; In your case you can do it like this. Implode the array with | and use it in regular expression.
<?php
$arr = Array(2,55,33,1,33,99);
echo 'select * from table where CONCAT(",", `field`, ",") REGEXP ",('.implode("|",$arr).'),"';
?>
For comparing two arrays, you should use:
array_intersect()
after converting table data into array as well.
Reference

Selecting NOT NULL columns from a table

My table is having approximately 80 columns. I am performing the following query on the table.
SELECT * FROM mobile_details WHERE id=4;
It is confirmed that the above query will return only one row. I want to select only the columns which are not having value NULL or empty. How can I do this?
Note: A very inefficient way to do this is to put NOT NULL in every column while SELECTing. But I need a more efficient and effective way (either in PHP code or MySQL query).
Can I do something like this? SELECT * FROM mobile_details WHERE id=4 AND mobile_details.* NOT NULL;
I am using PHP + MySQL + Apache on CentOS server.
You can't change the list of columns programmatically in SQL. There's no syntax for it.
You don't. You can do some trickery, but it's not worth it. Why not just skip the null columns when you are processing the data? It's easy enough to check for in PHP. Also, you shouldn't use SELECT * in production. Select just the columns you want and if you happen to want all of them, list them all.
You should do it in php, use function array_filter to filter the null values.

mysql select query within a serialized array

I'm storing a list of items in a serialized array within a field in my database (I'm using PHP/MySQL).
I want to have a query that will select all the records that contain a specific one of these items that is in the array.
Something like this:
select * from table WHERE (an item in my array) = '$n'
Hopefully that makes sense.
Any ideas would be greatly appreciated.
Thanks
As GWW says in the comments, if you need to query things this way, you really ought to be considering storing this data as something other than a big-ole-string (which is what your serialized array is).
If that's not possible (or you're just lazy), you can use the fact that the serialized array is just a big-ole-string, and figure out a LIKE clause to find matching records. The way PHP serializes data is pretty easy to figure out (hint: those numbers indicate lengths of things).
Now, if your serialized array is fairly complex, this will break down fast. But if it's a flat array, you should be able to do it.
Of course, you'll be using LIKE '%...%', so you'll get no help from any indicies, and performance will be very poor.
Which is why folks are suggesting you store that data in some normalized fashion, if you need to query "inside" it.
If you have control of the data model, stuffing serialized data in the database will bite you in the long run just about always. However, oftentimes one does not have control over the data model, for example when working with certain open source content management systems. Drupal sticks a lot of serialized data in dumpster columns in lieu of a proper model. For example, ubercart has a 'data' column for all of its orders. Contributed modules need to attach data to the main order entity, so out of convenience they tack it onto the serialized blob. As a third party to this, I still need a way to get at some of the data stuffed in there to answer some questions.
a:4:{s:7:"cc_data";s:112:"6"CrIPY2IsMS1?blpMkwRj[XwCosb]gl<Dw_L(,Tq[xE)~(!$C"9Wn]bKYlAnS{[Kv[&Cq$xN-Jkr1qq<z](td]ve+{Xi!G0x:.O-"=yy*2KP0#z";s:7:"cc_txns";a:1:{s:10:"references";a:1:{i:0;a:2:{s:4:"card";s:4:"3092";s:7:"created";i:1296325512;}}}s:13:"recurring_fee";b:1;s:12:"old_order_id";s:2:"25";}
see that 'old_order_id'? thats the key I need to find out where this recurring order came from, but since not everybody uses the recurring orders module, there isnt a proper place to store it in the database, so the module developer opted to stuff it in that dumpster table.
My solution is to use a few targeted SUBSTRING_INDEX's to chisel off insignificant data until I've sculpted the resultant string into the data gemstone of my desires.
Then I tack on a HAVING clause to find all that match, like so:
SELECT uo.*,
SUBSTRING_INDEX(
SUBSTRING_INDEX(
SUBSTRING_INDEX( uo.data, 'old_order_id' , -1 ),
'";}', 1),
'"',-1)
AS `old order id`
FROM `uc_orders AS `uo`
HAVING `old order id` = 25
The innermost SUBSTRING_INDEX gives me everything past the old_order_id, and the outer two clean up the remainder.
This complicated hackery is not something you want in code that runs more than once, more of a tool to get the data out of a table without having to resort to writing a php script.
Note that this could be simplified to merely
SELECT uo.*,
SUBSTRING_INDEX(
SUBSTRING_INDEX( uo.data, '";}' , 1 ),
'"',-1)
AS `old order id`
FROM `uc_orders` AS `uo`
HAVING `old order id` = 25
but that would only work in this specific case (the value I want is at the end of the data blob)
So you mean to use MySQL to search in a PHP array that has been serialized with the serialize command and stored in a database field? My first reaction would be: OMG. My second reaction would be: why? The sensible thing to do is either:
Retrieve the array into PHP, unserialize it and search in it
Forget about storing the data in MySQL as serialized and store it as a regular table and index it for fast search
I would choose the second option, but I don't know your context.
Of course, if you'd really want to, you could try something with SUBSTRING or another MySQL function and try to manipulate the field, but I don't see why you'd want to. It's cumbersome, and it would be an unnecessary ugly hack. On the other hand, it's a puzzle, and people here tend to like puzzles, so if you really want to then post the contents of your field and we can give it a shot.
You can do it like this:
SELECT * FROM table_name WHERE some_field REGEXP '.*"item_key";s:[0-9]+:"item_value".*'
But anyway you should consider storing that data in a separate table.
How about you serialize the value you're searching for?
$sql = sprintf("select * from tbl WHERE serialized_col like '%%%s%%'", serialize($n));
or
$sql = sprintf("select * from tbl WHERE serialized_col like '%s%s%s'", '%', serialize($n), '%');
Working with php serialized data is obviously quite ugly, but I've got this one liner mix of MySQL functions that help to sort that out:
select REPLACE(SUBSTRING_INDEX(SUBSTRING_INDEX(SUBSTRING_INDEX(searchColumn, 'fieldNameToExtract', -1), ';', 2), ':', -1), '"', '') AS extractedFieldName
from tableName as t
having extractedFieldName = 'expressionFilter';
Hope this can help!
Well, i had the same issue, and apparently it's a piece of cake, but maybe it needs more tests.
Simply use the IN statement, but put the field itself as array!
Example:
SELECT id, title, page FROM pages WHERE 2 IN (child_of)
~ where '2' is the value i'm looking for inside the field 'child_of' that is a serialized array.
This serialized array was necessary because I cannot duplicate the records just for storing what id they were children of.
Cheers
If I have attribute_dump field in log table and the value in one of its row has
a:69:{s:9:"status_id";s:1:"2";s:2:"id";s:5:"10215"}
If I want to fetch all rows having status_id is equal to 2, then the query would be
SELECT * FROM log WHERE attribute_dump REGEXP '.*"status_id";s:[0-9]+:"2".*'
There is a good REGEX answer above, but it assumes a key and value implementation. If you just have values in your serialized array, this worked for me:
value only
SELECT * FROM table WHERE your_field_here REGEXP '.*;s:[0-9]+:"your_value_here".*'
key and value
SELECT * FROM table WHERE your_field_here REGEXP '.*"array_key_here";s:[0-9]+:"your_value_here".*'
For easy method use :
column_field_name LIKE %VALUE_TO_BE_SEARCHED_FOR%
in MySQL query
You may be looking for an SQL IN statement.
http://www.w3schools.com/sql/sql_in.asp
You'll have to break your array out a bit first, though. You can't just hand an array off to MySQL and expect it will know what to do with it. For that, you may try serializing it out with PHP's explode.
http://php.net/manual/en/function.explode.php
Select * from table where table_field like '%"enter_your_value"%'
select * from postmeta where meta_key = 'your_key' and meta_value REGEXP ('6')
foreach( $result as $value ) {
$hour = unserialize( $value->meta_value );
if( $hour['date'] < $data['from'] ) {
$sum = $sum + $hour['hours'];
}
}

Categories