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
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
Related
I'm trying to create a restaurant search that will find the restaurant in the database even when the user only inputs part of the whole name.
Here is the code:
First I take the input, sanitize it and then add the % signs to the left and right.
$restaurantNameTest = InputCleaner($_GET["restaurantName"]);
$restaurantName = ('%' . $restaurantNameTest . '%');
Then I run the query:
$result = mysqli_query($conn,
"SELECT restaurantID,restaurant_name, cusine, wait_time
FROM Restaurant
WHERE restaurant_name = '$restaurantName'");
For some reason this isn't working and no results are found unless I type in the name perfectly. Am I doing it wrong?
Use Like instead
$result = mysqli_query($conn,
"SELECT restaurantID,restaurant_name, cusine, wait_time
FROM Restaurant
WHERE restaurant_name LIKE '$restaurantName'");
This is more of an SQL question than a PHP question, but what I believe you need is the LIKE comparison of the WHERE clause.
So change your query to read: ...WHERE restaurant_name LIKE '$restaurantName'");
LIKE will match partial strings, based on the placement of the wildcard (%) character(s).
So a few things to note, first of all to echo what others have said -- you should be using LIKE in your query. On top of that you should really be using MySQLi's prepared statements
So you will want a your code to look something like this:
$sql = "SELECT restaurantID,
restaurant_name,
cusine,
wait_time
FROM Restaurant
WHERE restaurant_name LIKE '%?%'";
$query = $connection->prepare($sql);
$query->bind_param('s'. $restaurantName);
$query->execute();
I'm primarily a PDO user so you may want to double check the above syntax, but it should work.
To re-iterate on your question specifically:
Use LIKE with your wildcards to get the result you're after and not =.
Ok, I can't figure out why this doesn't work at all.
$get_data = mysql_query("SELECT * FROM chatbox ORDER BY ID WHERE message = 'bla'");
while($data = mysql_fetch_assoc($get_data)) {
*blablabla code*
}
This does NOT work. It gives me a
"Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource" error. (with line number ofcourse)
When I remove the "WHERE message = 'bla'" part, it works fine. Tryed with and without ' things around bla and around messages. Message field does excist in my DB, so does the entry bla. Tryed it even with the ID field in my DB, with number 1, does not work at all. What is wrong with this simple line of code. Tryed to look almost everywhere, can't figure it out...
You are using WHERE clause after ORDER BY, it can not be work for you.
Modified Query:
SELECT * FROM chatbox WHERE message = 'bla' ORDER BY ID
You need to follow this sequence when you crease MYSQL SELECT Statement:
SELECT .. COLUMNS .. FROM .. WHERE .. ORDER
SELECT Manual Reference
Side Note:
Please use mysqli_* or PDO instead of mysql_* because this extension deprecated and not available in PHP 7.
Your query is wrong. You are using order by before where condition.
Try this query : "SELECT * FROM chatbox WHERE message = 'bla' ORDER BY ID"
And also migrate from mysql_* to mysqli_*.
I have a table that contains name of movies and other things and in my php page I want to select some of that movies..
$sql3 = "SELECT * FROM Movies where Movies.nameM='{$row['nameM']}';";
This query crashes when the nameM (name of movie) has an apostrophe in its name :/
How can I change this to work well?
Thanks for your help
You may try:
$sql3 = "SELECT * FROM Movies where Movies.nameM='".mysqli_real_escape_string($row['nameM'])."';";
And if you are using the old and deprecated mysql_* functions:
$sql3 = "SELECT * FROM Movies where Movies.nameM='".mysql_real_escape_string($row['nameM'])."';";
As Spudley said you should R&D more. Just to make it a few easier for you
You may use mysql(i)_ real escape functions but if you're using a framework works on top of PDO you don't have a mysql(i)_* connection and can't escape strings using them
i have seen this problem previously on yii or f3 or ...
Mostly the frameworks support the param safe injection.
\Framework::Query("SELECT .... WHERE column=:param", array(':param'=>$value));
But some times you may need to escape the string value manually. To do that with PDO you can acquire the pdo object and use the :
substr($pdo->quote($string, , \PDO::PARAM_STR), 1, -1)
The only note is that the ->quote() also puts the apostrophes around the result which they can get wiped using substr.
Edited to make the codes clear
I have a weird problem please take a look at this query:
select * from myfriend where name like "%n%";
when execute this query on phpMyAdmin the query returned correct results, but when execute it using php no result returned.
please note this query executed in drupal 6.
what is the problem with char "n" and PHP?
Percent signs are used as placeholders in Drupal 6 queries, so you need to escape them:
$query = db_query('select * from myfriend where name like "%%n%%"');
$searchChar = "n";
$query = "SELECT * FROM `myfriend` WHERE `name` LIKE '%" . $searchChar . "%'";
Then use the $query variable in your statement.
Eg:
$mysql->query($query);
mysql_query($query);
Your query is perfect. Give some brief on it. You can check if your connection of database from php to mysql is correct. You can echo that query from php file and run into phpmyadmin if that gives correct output then surely database connectivity problem will be there.
There is absolutely no issues with any character in php.
I'm converting all my sites code from using mysql_* functions to PDO. The PHP documentation on PDO is not clear for my needs. It gives you the functions to use, but does not go into detail to explain them in different scenarios.
Basically, I have a mysql fulltext search:
$sql = "SELECT ... FROM search_table WHERE MATCH(some_field) AGAINST ('{$searchFor}*' IN BOOLEAN MODE)";
The actual statements much longer, but this is what it basically does.
My question is, how would I incorporate this into PDO?
I know you're not meant to use quotes around the place-marker, so do you leave them out in the AGAINST() function? Do I include them? If I leave them out, what happens to the wildcard symbol etc?
$sql = $this->db->prepare("SELECT ... FROM search_table WHERE MATCH(some_field) AGAINST(:searchText IN BOOLEAN MODE");
$sql->bindValue(':searchText', $searchFor . '*');
This is unfortunately a weird exception to the use of query parameters (edit: but apparently not in the most recent point-release of each MySQL branch, see below).
The pattern in AGAINST() must be a constant string, not a query parameter. Unlike other constant strings in SQL queries, you cannot use a query parameter here, simply because of a limitation in MySQL.
To interpolate search patterns into queries safely, use the PDO::quote() function. Note that PDO's quote() function already adds the quote delimiters (unlike mysql_real_escape_string()).
$quoted_search_text = $this->db->quote('+word +word');
$sql = $this->db->prepare("SELECT ... FROM search_table
WHERE MATCH(some_field) AGAINST($quoted_search_text IN BOOLEAN MODE");
Re comment from #YourCommonSense:
You're right, I just tested this on MySQL 5.5.31, 5.1.68, and 5.0.96 (MySQL Sandbox is a wonderful tool), and it seems that these versions do accept query parameters in the AGAINST() clause of a dynamic SQL query.
I still have a recollection of a conflict existing in the past. Maybe it has been corrected in the most recent point-release of each branch. For example, I find these related bugs:
Using a stored procedure parameter in the AGAINST() clause always returns the same result: http://bugs.mysql.com/bug.php?id=3734
Crash or strange results with prepared statement, MATCH and FULLTEXT: http://bugs.mysql.com/bug.php?id=14496
$sql = "SELECT * FROM tablename WHERE MATCH (fieldname) AGAINST (:searchstr IN BOOLEAN MODE) LIMIT {$per_page} OFFSET {$pg_offset}";
try {
$database->prepare($sql);
$database->bindParam(':searchstr', $search);
$database->execute();
$result_array = $database->fetch_array($sql);
} catch (Exception $e) {
echo $e->getMessage();
}