I have a form using a POST method, upon enter a name and clicking search, it is supposed to display the information from the database, with the term you used.
index.php
<form action="search.php" method="POST">
<input type="text" name="search" /><br/><br/>
<input type="Submit" value="Search" />
</form>
Search.php
<?php
if (!$_POST) {
include('index.php');
} else {
?>
<h1>Server name<br />Official ItemDB!</h1>
<br />
<?php
$search = $_POST["search"];
MySQL_connect("localhost", "pernix_items", "#");
MySQL_select_db("pernix_items");
$result = mysql_query("SELECT * FROM items WHERE name LIKE '%" . mysql_real_escape_string($search) . "%'");
while($row = mysql_fetch_array($result));
{
?>
<table border="1">
<?
echo '<tr>';
echo '<td>'.$row['id'] . '</td>';
echo '<td>' . $row['name'] . '</td>';
echo '<td>' . $row['desc'] . '</td>';
echo '</tr>';
}
}
?>
</tr>
</table>
I added the mysql_error(); function to dertime where I was going wrong, to this
$result = mysql_query("SELECT * FROM items WHERE name LIKE '%" . mysql_real_escape_string($search) . "%'" or die(mysql_error()));
and gives me this
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /home1/pernix/public_html/tools/item-list/search.php on line 21
My line 21 of search.php
while($row = mysql_fetch_array($result));
So I added another or die print error.
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1
Any ideas?
Although resolved in the comments, reposting it here as a whole answer.
First the or die()
line is wrong, as the die statement is executed inside the mysql_query
and not as supposed to when and if the query fails, as it should be:
$result = mysql_query("SELECT * FROM items WHERE name LIKE '%" . mysql_real_escape_string($search) . "%'") or die(mysql_error());
Secondly you have an extra semicolon right after the while()
line making, which should be removed to look like:
while($row = mysql_fetch_array($result))
{}
Last and most importantly you should really convert this code to mysqli
or pdo
as the mysql
extension is deprecated as of PHP 5.5.0, and will be removed in the future.