Hi guys I need to search for a data in the database like 123.456.789
how can I search it even if I only entered 123456789 ?
I need to escape the special characters from the database so that even if i search for 123456789 it can also display values like 123.456.789.
Here is my query:
SELECT *
FROM clients
WHERE REPLACE(phone, '.', '') LIKE ".$searchtext."
... where searchtext is the number im looking for. It should return all values that match regardless of whatever special characters are present.
#Kiel
Here is the sample table & query. Please see if this can help you. Not sure about your table structure.
CREATE TABLE `clients` (
`id` int(11) NOT NULL,
`phone` varchar(255) NOT NULL
) ENGINE=InnoDB;
INSERT INTO `test`.`clients` (
`id` ,
`phone`
)
VALUES (
'1', '123.456.789'
), (
'2', '123.456.785'
);
mysql> select * from clients where replace(phone,'.','') = '123456789';
+----+-------------+
| id | phone |
+----+-------------+
| 1 | 123.456.789 |
+----+-------------+
Hope this help !
select phone from table_name
where replace (cast (phone as text) , '.','') like '%123456789%'
You could use MySQL's REPLACE() function:
SELECT * FROM my_table WHERE REPLACE(my_column, '.', '') = '123456789';
But if my_column just contains integers, you should really change it to one of MySQL's integer types.
Replace() is the best function to do this :
Select * from TableName where Replace(ColumnName,'escaping character','replaced character')='your Search option'
for your case escaping character is dot(.), replaced character is '' and search option is '123456789'
Related
I want to create a table that will output the data from mysql database that was recently added.
Example :
+-----+---------+-----------+---------------+-------------+
| id | item_id | item_name | borrowed_date | expiry_date |
+-----+---------+-----------+---------------+-------------+
| B01 | N01 | book | 12/05/2017 | 10/06/2017 |
+-----+---------+-----------+---------------+-------------+
I have tried using ORDER BY but it does not output according to newly added row.
<?php
include"connection.php"; //contain $conn
$query = "SELECT * FROM `database` ORDER BY item_id ASC ;";
$result = mysqli_query($conn,$query);
?>
The output was not according to newly added data
Set your id column to auto increment
Give your table another name than Database.
Then use:
SELECT * FROM `yourtable` ORDER BY `id` DESC LIMIT 0,1;
I suggest including one column (like a primary key) that's set to AUTO_INCREMENT. That way you can sort in descending order (DESC) by that ID to get the latest entry.
Something like this:
CREATE TABLE `database` (
id MEDIUMINT NOT NULL AUTO_INCREMENT,
[other columns here]
PRIMARY KEY (id)
);
And then:
SELECT * FROM `database` ORDER BY `id` DESC LIMIT 0,1;
Incidentally, I'm not sure if your table is really named "database". If so, I suggest not using a reserved word. It will work since you're using backticks, but it might be a good idea to change it anyway for various reasons.
My table is:
After Query:
SELECT * FROM `table` WHERE `identifier` LIKE '000123_%'
I get:
How to get the row with highest suffix, i.e: 000123_5 with query.
Why dont create the function SPLIT_STRING at your DB like this:
CREATE FUNCTION `SPLIT_STRING`(
str VARCHAR(255) ,
delim VARCHAR(12) ,
pos INT
) RETURNS VARCHAR(255) CHARSET utf8 RETURN REPLACE(
SUBSTRING(
SUBSTRING_INDEX(str , delim , pos) ,
CHAR_LENGTH(
SUBSTRING_INDEX(str , delim , pos - 1)
) + 1
) ,
delim ,
''
);
And later you can call her from your query to get the last characters:
-- Example table
CREATE TABLE `test`(
`keywords` VARCHAR(255) DEFAULT NULL
) ENGINE = INNODB DEFAULT CHARSET = utf8;
INSERT INTO `test`(`keywords`)
VALUES
(
'keyword 1,keyword 2, keyword 3, keyword 4'
);
-- Example query
SELECT
-- keyword 1
SPLIT_STRING(`keywords`,',',1) AS keyword_1,
-- keyword 4, NOT trimmed
SPLIT_STRING(`keywords`,',',4) AS keyword_4,
-- keyword 4, trimmed
trim(SPLIT_STRING(`keywords`,',',4)) AS keyword_4_trimmed
FROM `test`;
Using it at your example:
SELECT SPLIT_STRING(`identifier`,'_',2) as identifier2,* FROM `table`
WHERE `identifier` LIKE '000123_%'
ORDER BY SPLIT_STRING(`identifier`,'_',2) DESC
In this particular answer, you could use RIGHT(identifier,1) to take the rightmost character. Then you would take the MAX() of the right to find the highest. However, if the suffix would end up being 1 or more characters then you would need to find the right regex to capture the characters that come after the last underscore and then take the MAX() of that group.
You can try this query, where you pick the highest value by comparation from all the right side values of the varchar 'identifier'. My code may not work exactly as I don't have a pc here. Good luck!
SELECT *, select RIGHT(identifier,1) as rvalue FROM `table` WHERE `identifier` LIKE '000123_%' and rvalue >= ALL (SELECT RIGHT(identifier,1) as rvalue FROM `table`) t
If it's just for a single group of rows you can apply:
order by char_length(identifier) desc, identifier desc
limit 1
Longer string means larger numbers...
I'm writing a PHP router, which lookups page's id in database with such query
SELECT `id` FROM `pages` WHERE '/about/test' REGEXP `url` ORDER BY `url`
from such table
id type_id url name lookup
1 0 /about/[^/]* NULL NULL
2 1 /about/company NULL NULL
So it gets id 2 on '/about/company' and id 1 on /about/whatever on first row of result
I'm looking for the best way to retrieve the wildcard values from MySQL, e.g. get ID of '/about/[^/]+' entry and 'test' as second argument when passing '/about/test'; and get only ID when passing '/about/company'
Simply, i want to get variadic number of columns, where first column return ID and others - wildcard values in right order
Let me assume that you have a flag that specifies if something is a wildcard pattern or a simple comparison.
If you want all matches, you can do:
SELECT `id`
FROM `pages`
WHERE '/about/test' REGEXP `url` AND url_has_wildcard = 0
UNION ALL
SELECT `id`
FROM `pages`
WHERE '/about/test' REGEXP `url` AND url_has_wildcard = 1 AND
NOT EXISTS (SELECT 1
FROM pages
WHERE '/about/test' REGEXP `url` AND url_has_wildcard = 0
);
You can define such a flag using -- what else -- a regular expression. Say, something like this:
WHERE '/about/test' REGEXP `url` AND
(url REGEXP '^[a-zA-Z0-9/]*$') -- or whatever the valid characters are
If you want only one row returned, you can do:
SELECT `id`
FROM `pages`
WHERE '/about/test' REGEXP `url`
ORDER BY (url REGEXP '^[a-zA-Z0-9/]*$') DESC
LIMIT 1;
I want to execute a query where I can find one ID in a list of ID.
table user
id_user | name | id_site
-------------------------
1 | james | 1, 2, 3
1 | brad | 1, 3
1 | suko | 4, 5
and my query (doesn't work)
SELECT * FROM `user` WHERE 3 IN (`id_site`)
This query work (but doesn't do the job)
SELECT * FROM `user` WHERE 3 IN (1, 2, 3, 4, 6)
That's not how IN works. I can't be bothered to explain why, just read the docs
Try this:
SELECT * FROM `user` WHERE FIND_IN_SET(3,`id_site`)
Note that this requires your data to be 1,2,3, 1,3 and 4,5 (ie no spaces). If this is not an option, try:
SELECT * FROM `user` WHERE FIND_IN_SET(3,REPLACE(`id_site`,' ',''))
Alternatively, consider restructuring your database. Namely:
CREATE TABLE `user_site_links` (
`id_user` INT UNSIGNED NOT NULL,
`id_site` INT UNSIGNED NOT NULL,
PRIMARY KEY (`user_id`,`site_id`)
);
INSERT INTO `user_site_links` VALUES
(1,1), (1,2), (1,3),
(2,1), (2,3),
(3,4), (3,5);
SELECT * FROM `user` JOIN `user_site_links` USING (`id_user`) WHERE `id_site` = 3;
Try this: FIND_IN_SET(str,strlist)
NO! For relation databases
Your table doesn't comfort first normal form ("each attribute contains only atomic values, and the value of each attribute contains only a single value from that domain") of a database and you:
use string field to contain numbers
store multiple values in one field
To work with field like this you would have to use FIND_IN_SET() or store data like ,1,2,3, (note colons or semicolons or other separator in the beginning and in the end) and use LIKE "%,7,%" to work in every case. This way it's not possible to use indexes[1][2].
Use relation table to do this:
CREATE TABLE user_on_sites(
user_id INT,
site_id INT,
PRIMARY KEY (user_id, site_id),
INDEX (user_id),
INDEX (site_id)
);
And join tables:
SELECT u.id, u.name, uos.site_id
FROM user_on_sites AS uos
INNER JOIN user AS u ON uos.user_id = user.id
WHERE uos.site_id = 3;
This way you can search efficiently using indexes.
The problem is that you are searching within several lists.
You need something more like:
SELECT * FROM `user` WHERE id_site LIKE '%3%';
However, that will also select 33, 333 and 345 so you want some more advanced text parsing.
The WHERE IN clause is useful to replace many OR conditions.
For exemple
SELECT * FROM `user` WHERE id IN (1,2,3,4)
is cleaner than
SELECT * FROM `user` WHERE id=1 OR id=2 OR id=3 OR id=4
You're just trying to use it in a wrong way.
Correct way :
WHERE `field` IN (list_item1, list_item2 [, list_itemX])
I have a table which has a single entry. I have to get those column values whose values are not null. Please suggest me query for MySQL so I can implement this. My table is :
In this table 3 columns have Null values. So I don't want these columns, query should return values which in not null.
Can I get the column name also? Like I want to get name of the column i.e min_p5 whose value is not null. So I can break the column name into strings and use 5 in my calculation. Please suggest me answer.
I think this is what you need:
Assuming your table name to be "orders" [pls change it accordingly]
$q="show columns from orders";
$res=mysql_query($q) or die(mysql_error());
$arr_field=array();
while($row=mysql_fetch_object($res)){
$field=$row->Field;
$q1="select ".$field." from orders where ".$field."!=0"; //if string then '0'
$res1=mysql_query($q1) or die(mysql_error());
if(mysql_num_rows($res1)>0){
$arr_field[]=$field;
}
}
$q="select ";
foreach($arr_field as $field){
$q.=$field.",";
}
$q=rtrim($q,",");
$q.=" from orders";
$res=mysql_query($q) or die(mysql_error());
while($row=mysql_fetch_object($res)){
foreach($arr_field as $field){
print($field."==".$row->$field."<br/>");
}
}
Run this and I hope you will get an idea...
SELECT *
FROM table
WHERE YourColumn IS NOT NULL;
Source: MySQL SELECT only not null values
select * from table where column_name is not null
Try following query for solve your problem,
select * from table
where column_name IS NOT NULL
It seems like you want to return:
| POINT_ID | BUS_ID | MIN_P5 | MIN_P15 |
|----------|--------|--------|---------|
| P101 | B101 | 1000 | 3000 |
because you want to exclude columns that have a zero value. It is not too easy to do this in MySQL because you need to use prepared statements:
SELECT
CONCAT(
'SELECT CONCAT(\'SELECT \',
CONCAT_WS(\',\',',
GROUP_CONCAT(
CONCAT(
'CASE WHEN EXISTS(SELECT * FROM TABLENAME WHERE ',
`column_name`,
'!=\'0\') THEN \'',
`column_name`,
'\' END')
),
'),\' FROM tablename\') FROM tablename INTO #final_sql'
)
FROM `information_schema`.`columns`
WHERE `table_schema`=DATABASE()
AND `table_name`='tablename'
INTO #sql;
PREPARE stmt FROM #sql;
EXECUTE stmt;
PREPARE finalstmt FROM #final_sql;
EXECUTE finalstmt;
Please see fiddle here. If your columns are numbers and not strings, maybe some minor fixes are needed. However, I would suggest you to try a different approach or to rethink about your table structure.