Following on from a question I asked earlier (which was very helpfully answered - thanks) I have a follow on question.
I managed to put a form into my page which successfully linked to another page with filtered results. I then added another form directly below (as a second search filter) but the second one is not working. The code is:
<p style="margin-left:20px;">Search by:<br />
<form action="ordersfiltered.php" method="post">
order_no: <input type="int" name="order_no" />
<input type="Submit" />
</form>
<form action="ordersfiltered_name.php" method="post">
name: <input type="text" name="name" />
<input type="Submit" />
</form></p>
Like I say, if I enter an order_no into the first box and click 'Submit' then I do get to another page with the result filtered accordingly. But when if I enter a name into the second box, the page I get has all the table headings etc but no results. For reference, the relevant code I have on the "ordersfiltered.php" page is:
$result = mysql_query("SELECT * FROM orders WHERE order_no = " . $_POST["order_no"]);
(NB I realise that I should not use SELECT * - its on my list of things to change). This works fine.
The code I have on "ordersfiltered_name.php" is:
$result = mysql_query("SELECT * FROM orders WHERE name = " . $_POST["name"]);
Any ideas why the first one works but not the second?
Also - I would if possible like to amend it add something like WHERE name LIKE '%...%' in case the user doesn't type the whole thing.
Thanks again.
I assume that it's related to the fact the order_no
is a number and name
is a string. Strings must be wrapped in quotes.
Therefore , change:
$result = mysql_query("SELECT * FROM orders WHERE name = " . $_POST["name"]);
to:
$name = mysql_real_escape_string($_POST['name']);
$result = mysql_query("SELECT * FROM orders WHERE name = '". $name ."'");
You also would need to check that $_POST['name']
doesn't has any quotes.
EDIT 1.You can always use or die(mysql_error())
after your mysql
commands. Then , you'll be able to see the reason why those commands don't work.
EDIT 2. It's extremely dangerous for you to use $_POST[..]
in your query. You should check its value first and make sure you "clean" it up.
EDIT 3.Another note , consider moving to PDO
.
You said that the previously asked question had some helpful answers, though you don't seem to use any of it: Using PHP forms in mysql queries (I'm not going to repeat all the valid points from there...).
That said, you are missing the quotes and escaping of the posted variable:
$result = mysql_query("SELECT * FROM orders WHERE name = '" . mysql_real_escape_string($_POST["name"])) . "'";