Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SELECT where row value contains string MySQL

Tags:

php

mysql

How can I select a row in my MySQL DB where the value of a column contains 'XcodeDev' for example?

I tried:

SELECT * FROM Accounts WHERE Username LIKE '$query'

But it only selects a row were the Username value is exactly the same to the query.

What can I do to achieve what I want?

like image 791
max_ Avatar asked Jun 22 '11 23:06

max_


People also ask

How do you check if a field contains a string in MySQL?

MySQL query string contains using INSTRINSTR(str, substr) function returns the index of the first occurrence of the substring passed in as parameters. Here str is the string passed in as the first argument, and substr is the substring passed in as the second argument.

How do I select a specific field in MySQL?

If you want to select only specific columns, replace the * with the names of the columns, separated by commas. The following statement selects just the name_id, firstname and lastname fields from the master_name table.


4 Answers

Use the % wildcard, which matches any number of characters.

SELECT * FROM Accounts WHERE Username LIKE '%query%'
like image 111
Matt Ball Avatar answered Oct 04 '22 02:10

Matt Ball


This should work:

SELECT * FROM Accounts WHERE Username LIKE '%$query%'
like image 35
jncraton Avatar answered Oct 04 '22 03:10

jncraton


My suggestion would be

$value = $_POST["myfield"];

$Query = Database::Prepare("SELECT * FROM TABLE WHERE MYFIELD LIKE ?");
$Query->Execute(array("%".$value."%"));
like image 20
Marcelo Avatar answered Oct 04 '22 01:10

Marcelo


SELECT * FROM Accounts WHERE Username LIKE '%$query%'

but it's not suggested. use PDO

like image 27
dynamic Avatar answered Oct 04 '22 02:10

dynamic