The PHP mysql_query
function takes two arguments. The first argument is the query string. The second argument is the connection.
Reference: http://php.net/manual/en/function.mysql-query.php
As @Barmar notes in a comment below, the second parameter to mysql_query
is optional. So the answer above likely has no bearing on the observed behavior.
As far as debugging the issue, I recommend that you first switch to using mysqli_ or PDO. And then add code to check for the return from function calls; test whether the connection to the database is successful or not. Test whether the execution of a query is successful or not.
And enable PHP error reporting. If there's an error happening, you want to know about it. Don't have your code put its pinky finger to the corner of its mouth and Dr.Evil style
Scott Evil: Wait, aren't you even going to watch them? They could get away!
Dr. Evil: No no no, I'm going to leave them alone and not actually witness them dying, I'm just gonna assume it all went to plan. What?
NOTES:
As indicated in the documentation, the mysql_ interface functions are deprecated (and removed in PHP 7.) New development should use either mysqli_ or PDO. There are mysqli_ functions that correspond to most of the deprecated mysql_ functions, though there are some differences. Note the order of parameters is different for mysqli_query.
This is the documentation for the mysqli_query function:
http://php.net/manual/en/mysqli.query.php
Also, best practice is to use prepared statements with bind placeholders. If we absolutely have a need to include potentially unsafe values into the SQL text, then when we do that, the values must be properly escaped. There are functions available specifically designed for this:
Reference: http://php.net/manual/en/mysqli.real-escape-string.php
(NOTE: That's a reference to the mysqli_ function. Do not mix the mysql_ and mysqli_ interface functions; use one or the other. (Actually, don't use mysql_ at all, just use mysqli_.)
If we supply values through bind placeholders in prepared statements, those do not need to be escaped.
$search = $_GET['query'];
if(!$dbh = mysqli_connect('localhost', 'user', 'password', 'database') {
// connect failed
die( mysqli_connect error() );
}
// static SQL text, not vulnerable to SQL Injection
$sql = "SELECT * FROM unblocked_search WHERE title LIKE CONCAT('%', ? , '%')";
if(!$sth = mysqli_prepare($dbh, $sql)) {
// prepare failed
die( mysqi_error($dbh) );
} else {
mysqli_stmt_bind_param($sth,'s',$search);
if( mysqli_stmt_execute($sth) ) {
$result = mysqli_stmt_get_result($sth);
while( $row = mysqli_fetch_array($result, MYSQLI_ASSOC) ) {
echo "\n<br> $row['name'] <br> $row['description'] ";
}
} else {
// execute failed
die( mysqli_error($dbh) );
}
}
NOTE: We are using die
as a placeholder, in place of more appropriate error handling (logging information, returning an error page to the user, etc.