Hi all,
I have an array:
$type = $_POST[‘style’];
My SQL statement:
$sql = “select * from shops where cat like '%” . $type[0] . “%'”;
I get no results even though my table has it… I checked $type[0] and it is the correct value…
Something wrong with my SQL or is it when I tried to load the results on a table:
$result = mysql_query($sql);
if (!$result)
exit("cannot load the shops");
// else
// echo “loaded”;
// display the shops
echo “<table border=1 width=650 cellspacing=5 cellpadding=5>”;
while ($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['venue'] . "</td>";
echo "</tr>" . "<p>";
}
What went wrong?
Echo out the value of $sql. Does it look ok? Copy and paste it in PHPMyAdmin and see if it works ok.
Be sure to specify the variable $type as an array before hand.
$type = array();
$type[] = $_POST['style'];
OR
Use $type as a string variable and don’t use array in query.
$type = $_POST['style'];
$sql = "select * from shops where cat like '%" . $type . "%'";
Thank you! This works. I echoed and the SQL is working fine. The only problem is the form input value I have set wrongly, that’s why no results found.
The code above is working fine =)
Please be aware that the mysql_* extension is now deprecated as of the current version of PHP and will very likely be removed from the next 5.x version and will likely not be in PHP 6.x (when it eventually is released). You should migrate over to either the mysqli_* extension or to PDO. PDO is a better choice as it doesn’t tie you down so much to a particular database server software.
Once you have migrated you should use Prepared Statements to prevent SQL Injection attacks. Have a read of this article from the PHP manual, it shows how to use prepared statements with PDO and also explains the principle.