0

Following is my query and I would like to call PHP substr(); within Mysqlquery. Apparently, substr(ident.secondName, -2, 2) is working, but substr(ident.FirstName, 0, 2) is not working. Thank you in an advance!

mysqli_query($con, "select * from ident where ident.FirstName LIKE '%$first_name%' 
OR substr(ident.FirstName, 0, 2) = '$first_two' OR ident.FirstName IS NULL AND
(ident.SecondName LIKE '%$second_name%' OR substr(ident.SecondName, -2, 2) 
= $second_two' OR ident.SecondName IS NULL)");
user3226210
  • 1
  • 1
  • 3
  • you cannot mix php functions and mysql variables together.If you want to use php functions then use php variable,otherwise use mysql functions with mysql varaible only.In your query you are trying to use a php function `substr` with mysql varaibles which is wrong – krishna Feb 11 '14 at 06:39

6 Answers6

3

No you cannot use a PHP function in a MySQL query, see the MySQL function reference for strings instead. MySQL also happens to have a SUBSTR function which is why the first case works.

Hamish
  • 22,860
  • 8
  • 53
  • 67
2

No. You can not use PHP function within mysql.

Monirul Islam
  • 985
  • 1
  • 8
  • 23
0

You're going to pass the query to you Mysql instance, it won't recognize the PHP code. So it's a no.

Joel Hernandez
  • 1,817
  • 4
  • 18
  • 27
0

you can use substring function for this

NLSaini
  • 257
  • 1
  • 10
0

Use MySQL function SUBSTRING(): http://www.w3resource.com/mysql/string-functions/mysql-substring-function.php or use MySQL variables: How to declare a variable in MySQL?

If you want to do it with PHP you will have to get the data first to fill variables and apply functions.

Community
  • 1
  • 1
Ed Capetti
  • 339
  • 2
  • 10
0

Why not use function 'SUBSTRING' in MySql?

SUBSTRING('stackoverflow', 1, 5)
result : stack

SUBSTRING('stackoverflow', -13, 5)
result : stack

SUBSTRING('stackoverflow', 6)
result : overflow

SUBSTRING('stackoverflow', -8)
result : overflow