0

I have this database I created with a phpMyAdmin client. Specific queries like SELECT * FROM TagData LIMIT 0,10 in my php code runs perfect. But when I add a wildcard to the query like SELECT * FROM TagData WHERE Device_Name LIKE 'Valve%' LIMIT 0,10 it doesn't work. The strange thing is that the exact same SQL works perfect in the phpMyAdmin tool.

This is how I run my query in php:

$query="SELECT * FROM TagData WHERE Device_Name LIKE 'Valve%' LIMIT 0,10";
$tmpResult=mysql_query(sprintf($query));

I have a strong feeling that the quote characters in the $query string are the problem. Can someone please explain me what I am doing wrong and why I am doing this wrong.

The result mysql_error() gives is:

Query was empty

The Stompiest
  • 318
  • 2
  • 15
  • phpMyAdmin is a database **client** not a database. Don't confuse it with MySQL. – Quentin Nov 21 '14 at 11:20
  • 3
    Why `sprintf`? Did you read what [sprintf](http://php.net/sprintf) does? – Mihai Iorga Nov 21 '14 at 11:20
  • "doesn't work" is not "a clear problem statement". Define "doesn't work". Test the return value of `mysql_query`. Make use of `mysql_error`. Look at the actual query you are passing to `mysql_query` (i.e. the return value of `sprintf` (which you shouldn't be using there anyway)). – Quentin Nov 21 '14 at 11:21
  • You are using [an **obsolete** database API](http://stackoverflow.com/q/12859942/19068) and should use a [modern replacement](http://php.net/manual/en/mysqlinfo.api.choosing.php). – Quentin Nov 21 '14 at 11:22
  • Thought that really wasn't need since I thought it was an obvious mistake to see for experienced php sql guys. But I added it anyway. – The Stompiest Nov 21 '14 at 11:27

1 Answers1

0

You dont need sprintf when you dont insert any custom parameters. Just leave it raw.

Your query was emtpy because the string you gave to sprintf was malformed and sprintf returned null/ an empty string.

You need parameters to place in sprintf otherwise this has no use. And % is a control character for sprintf, to escape this you would have to place %% instead of % but my advice here ins aslong as you do not have any parameters, just dont use it!

To make your query work just fire it raw

$query= "SELECT * FROM TagData WHERE Device_Name LIKE 'Valve%' LIMIT 0,10";
$tmpResult = mysql_query($query);

And now, please have a look what sprintf actually does:

http://php.net/manual/en/function.sprintf.php

However please consider upgrading to MySQLi or PHP/PDO extension because MySQL class is outdated, deprecated, unsave, slow and will be removed from PHP in the future.

http://php.net/manual/en/book.mysqli.php

http://php.net/manual/en/book.pdo.php

Steini
  • 2,753
  • 15
  • 24