0

I can not return results with the php scritp that quires the database and echos results? All i get is fetched data successfully. Any help would be great and thanks.

<form action="#" method="get">
search: <input type="text" name="Id"><br>  
<input type="submit" value="delete">
</form>

<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = '#####';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$search = $_GET['search'];
if($_GET){
$sql = 'SELECT Id, Employee_Name, 
           Employee_Email
    FROM Blog
    WHERE Id LIKE "%$sql%"';

 mysql_select_db('test');
 $retval = mysql_query( $sql, $conn );
 if(! $retval )
 {
 die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "Tutorial ID :{$row['Id']}  <br> ".
     "Title: {$row['Employee_Name']} <br> ".
     "Author: {$row['Employee_Email']} <br> ".
     "--------------------------------<br>";
} 
echo "Fetched data successfully\n";
}
mysql_close($conn);
?>
1
  • 1
    Terrible escaping practices: you should use mysql_real_escape_string. Second, mysql extension will be deprecated, you should be using some PDO. Third, your placeholder variable $sql seems should be $search. Commented Apr 8, 2014 at 21:58

2 Answers 2

1

Double quotes don't work in SQL queries. This:

$sql = 'SELECT Id, Employee_Name, 
       Employee_Email
FROM Blog
WHERE Id LIKE "%$sql%"';

Should be this:

$sql = "SELECT Id, Employee_Name, 
       Employee_Email
FROM Blog
WHERE Id LIKE '%$search%'";

Also, it's time to stop using the deprecated mysql functions. Switch to mysqli for MySQL, and switch to PDO if you want to interface with MySQL and other types of databases (MSSQL, Oracle, etc.).

Sign up to request clarification or add additional context in comments.

Comments

1

You have:

$search = $_GET['search'];
^^^^^^^---one variable name

Then have:

$sql = 'SELECT Id, Employee_Name, 
           Employee_Email
    FROM Blog
    WHERE Id LIKE "%$sql%"';
                    ^^^^--- wrong variable name

e.g. using the wrong variable name, plus having a gaping wide-open SQL injection attack vulnerability.

You're using $sql within the string that DEFINES $sql, so that inner $sql is empty, and your query will be WHERE Id LIKE "%%", which will match everything.

2 Comments

I have made the changes and now when I search it returns all listings in my database instead of the id number I am searching for. Any ideas would be great. Thanks for all the help, you guys really are great.
Figured it out. I changed my like statement on an accident and it was looking for something that was not in the data base.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.