Find a string inside the column name using MySQL query - php

I'm trying to write a select query for searching string in the particular column.
For example :
+----+------+-------------------------------+
| id | name | alternate |
+----+------+-------------------------------+
| 1 | Test | Test,Tests,test,tests,te,test |
| 2 | Demo | Demo.demo,dem,Dem |
+----+------+-------------------------------+
etc...
I just want to write a query for checking the submitted value name in the column name alternate
For example : I will submit the name test and it should check exists or not with the column name alternate that contains

use FIND_IN_SET()
$query = SELECT * FROM tablename WHERE FIND_IN_SET('test', alternate);
if(mysql_num_rows($query) > 0){
//if test was found
} else {
// test not found
}
for more information here

Try this query in mysql:
SELECT ID,NAME,ALTERNATE,
CASE WHEN (FIND_IN_SET(name, alternate) > 0)
THEN 'TRUE' ELSE 'FALSE' END RESULT FROM TABLE1;
SQL Fiddle

try this
select count(*) as total from tablename where alternate LIKE %test%
if the total value returned is greater than zero then string test exist in alternate column

One way of doing it is using the String function INSTR to check whether the Substring exists in the String or not. You can even pass a variable in Substring and String to check.
SELECT IF(INSTR(alternate,'test')! = 0,'Exists', 'Not Exists') as SearchResult FROM table;
Documentation can be found at:
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_instr

Related

How get from stored procedure specific the count(*) column as string or integer

I call in Laravel a function to call a MySQL stored procedure to get the count of records of 1 table. I get successfully the column count(*) and the value of count, but the problem is, that i wanna return only the value as number or string and i dont know how.... Here is my code:
$counted = DB::select('call count_user'); // get count from stored procedure
return $counted; // returns exactly: | # | count(*) |
// | 1 | 5 |
i wanna return something like:
return $counted['count']
Thank you very much for every help!
Add an alias to the selected value, as you would do any other query in MySQL, by using the as keyword in your select method.
$counted = DB::select('CALL count_user AS count');
return $counted['count'];

MYSQL: List all column names where their values = "Yes"

I have a table like so:
User_Id Column1 Column2 Column3
1 Yes No Yes
2
I want to use mysql query to list all the column names (there are more than 3) which match the User_Id '1' and have a value of 'Yes'.
I get an error:
Trying to get property 'num_rows' of non-object
Here is what I have tried:
<?php $myStats = $mysqli->query("SELECT COLUMN_NAME FROM user_services.columns WHERE myColumn = 'Yes'");
if ($myStats->num_rows > 0) {
// output data of each row
while($row = $myStats->fetch_assoc()) {
$rows[] = $row; }
return $rows; ?>
Please can someone show me where I am going wrong?
Thanks in advance.
The CONCAT_WS function comes in handy here:
SELECT CONCAT_WS(',', IF(Column1='Yes', 'Column1', NULL),
IF(Column2='Yes', 'Column2', NULL),
IF(Column3='Yes', 'Column3', NULL)) AS columns
FROM user_services.columns
WHERE User_Id = 1;
If you have more than 3 columns, then you may add more terms to above CONCAT_WS call. Your problem mainly seems to be a SQL one, so I won't add any PHP code.
Note that your design might be better off if your column strings were spread across rows, rather than columns. For instance, consider the following alternative:
User_Id | number | val
1 | 1 | Yes
1 | 2 | No
1 | 3 | Yes
Then, if you wanted all column numbers which were yes for user 1, you could simply do:
SELECT
User_Id,
GROUP_CONCAT(number ORDER BY number) columns
FROM yourTable
WHERE
User_Id = 1
GROUP BY
User_Id;

I can not get expected output by like operator, where field store multiple integer value [duplicate]

I have a field COLORS (varchar(50)) in a my table SHIRTS that contains a comma delimited string such as 1,2,5,12,15,. Each number representing the available colors.
When running the query select * from shirts where colors like '%1%' to get all the red shirts (color=1), I also get the shirts whose color is grey (=12) and orange (=15).
How should I rewrite the query so that is selects ONLY the color 1 and not all colors containing the number 1?
The classic way would be to add commas to the left and right:
select * from shirts where CONCAT(',', colors, ',') like '%,1,%'
But find_in_set also works:
select * from shirts where find_in_set('1',colors) <> 0
FIND_IN_SET is your friend in this case
select * from shirts where FIND_IN_SET(1,colors)
Take a look at the FIND_IN_SET function for MySQL.
SELECT *
FROM shirts
WHERE FIND_IN_SET('1',colors) > 0
This will work for sure, and I actually tried it out:
lwdba#localhost (DB test) :: DROP TABLE IF EXISTS shirts;
Query OK, 0 rows affected (0.08 sec)
lwdba#localhost (DB test) :: CREATE TABLE shirts
-> (<BR>
-> id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> ticketnumber INT,
-> colors VARCHAR(30)
-> );<BR>
Query OK, 0 rows affected (0.19 sec)
lwdba#localhost (DB test) :: INSERT INTO shirts (ticketnumber,colors) VALUES
-> (32423,'1,2,5,12,15'),
-> (32424,'1,5,12,15,30'),
-> (32425,'2,5,11,15,28'),
-> (32426,'1,2,7,12,15'),
-> (32427,'2,4,8,12,15');
Query OK, 5 rows affected (0.06 sec)
Records: 5 Duplicates: 0 Warnings: 0
lwdba#localhost (DB test) :: SELECT * FROM shirts WHERE LOCATE(CONCAT(',', 1 ,','),CONCAT(',',colors,',')) > 0;
+----+--------------+--------------+
| id | ticketnumber | colors |
+----+--------------+--------------+
| 1 | 32423 | 1,2,5,12,15 |
| 2 | 32424 | 1,5,12,15,30 |
| 4 | 32426 | 1,2,7,12,15 |
+----+--------------+--------------+
3 rows in set (0.00 sec)
Give it a Try !!!
If the set of colors is more or less fixed, the most efficient and also most readable way would be to use string constants in your app and then use MySQL's SET type with FIND_IN_SET('red',colors) in your queries. When using the SET type with FIND_IN_SET, MySQL uses one integer to store all values and uses binary "and" operation to check for presence of values which is way more efficient than scanning a comma-separated string.
In SET('red','blue','green'), 'red' would be stored internally as 1, 'blue' would be stored internally as 2 and 'green' would be stored internally as 4. The value 'red,blue' would be stored as 3 (1|2) and 'red,green' as 5 (1|4).
select * from shirts where find_in_set('1',colors) <> 0
Works for me
If you're using MySQL, there is a method REGEXP that you can use...
http://dev.mysql.com/doc/refman/5.1/en/regexp.html#operator_regexp
So then you would use:
SELECT * FROM `shirts` WHERE `colors` REGEXP '\b1\b'
You should actually fix your database schema so that you have three tables:
shirt: shirt_id, shirt_name
color: color_id, color_name
shirtcolor: shirt_id, color_id
Then if you want to find all of the shirts that are red, you'd do a query like:
SELECT *
FROM shirt, color
WHERE color.color_name = 'red'
AND shirt.shirt_id = shirtcolor.shirt_id
AND color.color_id = shirtcolor.color_id
You can achieve this by following function.
Run following query to create function.
DELIMITER ||
CREATE FUNCTION `TOTAL_OCCURANCE`(`commastring` TEXT, `findme` VARCHAR(255)) RETURNS int(11)
NO SQL
-- SANI: First param is for comma separated string and 2nd for string to find.
return ROUND (
(
LENGTH(commastring)
- LENGTH( REPLACE ( commastring, findme, "") )
) / LENGTH(findme)
);
And call this function like this
msyql> select TOTAL_OCCURANCE('A,B,C,A,D,X,B,AB', 'A');
1. For MySQL:
SELECT FIND_IN_SET(5, columnname) AS result
FROM table
2.For Postgres SQL :
SELECT *
FROM TABLENAME f
WHERE 'searchvalue' = ANY (string_to_array(COLUMNNAME, ','))
Example
select *
from customer f
where '11' = ANY (string_to_array(customerids, ','))
All the answers are not really correct, try this:
select * from shirts where 1 IN (colors);

How to update the colum value when we find the same argument in MySQL with php code

For example:
I want to find if MySQL table have this argument or not
$arg1="dog",$arg2="cat"
here is MySQL table
data1 | data2 | count
------+-------+------
dog | cat |
after search all the table
if I found table with this value
update the count columns +1
Is any better idea with php or MySQL ?
Is the count columns need to give a initial value?
This looks like a job for MySQL, you should just run a query like this one :
Update table_name
SET count = count + 1
WHERE data1 = 'dog'
AND data2 = 'cat'
If you want, you could give the count column a default value 0, but its not mandatory.
Upade via php :
<?php
mysql_connect('host','username','password') or die(mysql_error());
mysql_query("THE ABOVE QUERY") or die(mysql_error());
?>

Ip address compare in database

I am trying to solve a problem that could compare 2 columns in a table.
the table is as follows
------------------------------------------
| from | to | Country |
------------------------------------------
| 25.0.0.1 | 25.255.255.255 | denmark |
------------------------------------------
| 68.0.0.1 | 68.255.255.255 | USA |
My problem is i have a ip of 25.195.32.0 and i want to compare this to the from and to column and return the country name.
You can use INET_ATON to get a numeric value of the IPs to compare.
SELECT country FROM table
WHERE INET_ATON('25.195.32.0') BETWEEN INET_ATON(from) AND INET_ATON(to)
http://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_inet-aton
You can find using IN() try condition according you use AND or OR
WHERE from IN('your_ip') OR to IN('your_ip')
select * from db.table
Then in php (assuming you've run the quest and stored results):
$lookupIP;
for($i=0;$i<$db->getRowCount();$i++) {
$partsFROM = explode(".", $FROM);
$partsTO = explode(".", $TO);
$partsLOOKUP = explode(".",$lookupIP);
if(
$partsLOOKUP[0] >= $partsFROM[0] && $partsLOOKUP[0] <= $partsTO[0]
&& $partsLOOKUP[1] >= $partsFROM[1] && $partsLOOKUP[1] <= $partsTO[1]
&& etc..
) return $Country
}
Not particularly efficient or elegant but you get the idea.
As i interpret from the question, you can use some mask and get the base ip address and then compare it. To use the mask and get base ip, you need to learn something about different classes (A, B, C, D) used from addressing.
Refer this link http://www.subnet-calculator.com/
INET_ATON gives desired solution on IPV4 addresses.
Apart from that, you can also try HEX version of the IP to compare in between.
SELECT HEX( input_ip_value )
BETWEEN HEX( from_ip_column )
AND HEX( to_ip_column )
Example:
mysql> select #i:=hex('25.195.32.0'),
-> #f:=hex('25.0.0.1'),
-> #t:=hex('25.255.255.255'),
-> #i between #f and #t is_between;
+------------------------+---------------------+------------------------------+------------+
| #i:=hex('25.195.32.0') | #f:=hex('25.0.0.1') | #t:=hex('25.255.255.255') | is_between |
+------------------------+---------------------+------------------------------+------------+
| 32352E3139352E33322E30 | 32352E302E302E31 | 32352E3235352E3235352E323535 | 1 |
+------------------------+---------------------+------------------------------+------------+
Select a range:
SELECT Country FROM table_name WHERE ip_address >= from AND to <= ip_address
If you can use a script (eg php) you could select the entire table and make a mask to the IP. Something like:
We can know what belongs to the network address 192.168.129.3/18 ip as
follows:
ip_en_binario = decbin (ip2long ("192.168.129.3"));
mascara_en_binario = decbin (ip2long ("255.255.192.0"));
resultado_en_binario $ = $ & $ mascara_en_binario ip_en_binario;
miss long2ip (bindec ($ resultado_en_binario));
The result returned us this script is 192.168.128.0, which is the network address to which the IP belongs 192.168.129.3/18.
Then, you can do a 'SELECT' of your network with "from" and "to" fields.
Transform IP into integer, then compare integer is simple. MySQL offers the inet_aton function to do so.
select Country from table_name where inet_aton($ip) between inet_aton(`from`) and inet_aton(`ip`);
For performance, you should transform column from, to to integer manully. eg. add to columns from_n, to_n. then your SQL will be like this:
select Country from table_name where inet_aton($ip) between `from_n` and `to_n`
If you are not using MySQL, you should transform $ip into integer $ip_n first (using something like Python's socket.inet_aton), then replace inet_aton($ip) with $ip_n.
use this query
select Country from table_name where from=to;

Categories