Forum Moderators: coopster

Message Too Old, No Replies

Multiple Checkbox $ Post Question

Checkbox $_Post

         

WoodNotOil

1:14 am on Mar 15, 2010 (gmt 0)

10+ Year Member



Hi everyone, I'm new here. Looks like a great forum! I am hoping you can help.

I have a table in my database that stores information about products. I have this information displayed in an html table for users to see. I want to have a check box for each item so that users can choose just a few items to compare. Here is an example of what I want the first table to look like:

<form action="compare.php" method="post">
<table border='2' cellspacing='0' cellpadding='7'>

<?php
$itemlist = mysql_query(
"SELECT id, name, desc, FROM table");

while (list($id, $name, $desc) = mysql_fetch_row($itemlist)) {

echo "
<tr>
<td><input type=\"checkbox\" name=\"itemid[]\" value=\"$id\" /></td>
<td>$name</td>
<td>$desc</td>
</tr>";
}
?>
<input type="submit" name="formSubmit" value="Compare" />
</form></table>



Now I want the same html table to be displayed on the compare.php page but only displaying the items that the user checked the box for.

The following was suggested to me but it doesn't seem to work.


<table border='2' cellspacing='0' cellpadding='7'>

<?php
$query = mysql_query("SELECT * FROM table WHERE id IN(".implode(",", $_POST['itemid']).")");

while ($data = mysql_fetch_row($query)) {

echo "
<tr>
<td>".$data['name']."</td>
<td>".$data['desc']."</td>
</tr>";
}
?>
</table>



I used var_dump and the checked id values are making it through. I get the error: "mysql_fetch_row(): supplied argument is not a valid MySQL result resource in..."

Thanks for any help you can give!

Readie

8:21 am on Mar 15, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Welcome to Webmaster World WoodNotOil

First of all, rename the column "desc" - desc is descending. I am guilty of naming something desc myself once, and it refused to work till I changed that.

I also seem to recall reading that it's a bad idea to name a column "name"

Ok, you can build your SQL string with something like this:

if(strtolower($_POST['formSubmit']) === "compare") {
$sql = 'SELECT * FROM table WHERE 1';
foreach($_POST as $postie) {
if(isset($postie) && $postie != "" && strtolower($postie) != "compare") {
$sql .= ' OR product_name = "' . mysql_real_escape_string($postie) . '"';
}
}
}

Make sure that there is a space before the "OR".
The value of the check boxes needs to be the data you are looking for.
Always use something like mysql_real_escape_string to santise input.

$result = mysql_query($sql);
$rows - mysql_num_rows($result);

$p_table = '<table>
<tr>
<td>Product Name</td>
<td>Product Description</td>
</tr>';

for($i = 0; $i < $rows; $i++) {
$p_name = mysql_result($result, $i, "product_name");
$p_description = mysql_result($result, $i, "description");
$p_table .= '<tr>
<td>' . $p_name . '</td>
<td>' . $p_description . '</td>
</tr>';
}

$p_table .= '</table>';

echo $p_table;

Code has been typed OTF, might have an error or two.

Matthew1980

8:29 am on Mar 15, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



hi there WoodNotOil,

Welcome to the forum!

Always a good place to start with mysql_query() is to add the or die(mysql_error()); to the end of the query, this will then flag up any errors that are coming from there, and as this is developmental you can place error_reporting(E_ALL); at the top aof the file/page that you are working on to flag any error's that are generated when the script executes, make sure that you remove these though when you have finished & go public as these functions can potentially give hackers information about the structure of your site/database.

Also, as you are using $_POST directly in the sql, use the mysql_real_escape_string(); around the $_POST so that the sql is protected against malicious code injection, good coding practice to sanitise the $_POST, you can use strip_tags(); too to deal with html style injections...

With the latter sql query, are you just asking for specific item id's as I personally have never used or heard of IN as a function in mysql or php, maybe someone could enlighten me as I can't find a reference to it?

[EDIT]
As Readie says, there are a few reserved naming conventions, desc & name are among them, more obvious ones are data & var. Semantically though it is best to name things that correspond to what their purpose is, but the more conversant as you get you come to understand this ;-p

Cheers,
MRb

Readie

8:44 am on Mar 15, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



SQL in:

[w3schools.com...]

Oddly enough I was reading that literally 20 minutes ago

Readie

10:40 am on Mar 15, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



To do it while still using the IN operator:

if(strtolower($_POST['formSubmit']) === "compare") {
$sql_in = '';
foreach($_POST as $postie) {
if(isset($postie) && $postie != "" && strtolower($postie) != "compare") {
$sql_in .= '"' . $mysql_real_escape_string($postie) . '", ';
}
$sql = 'SELECT * FROM table WHERE product_name IN(' . rtrim($sql_in, ", ") . ') ORDER BY product_name ASC';
}
}

WoodNotOil

1:30 pm on Mar 15, 2010 (gmt 0)

10+ Year Member



Thanks for the responses guys! However I still can't seem to get it to work. Partly because I am unfamiliar with some of what you are doing with the POST.

Again, what I am trying to do is take the id numbers that are posted in $_POST['itemid'] from the checked boxes and only display the items that match the id. The WHERE will be using the id field in the table to determine this, not the product_name field. To show you what is coming through from the first page, here are the result of:

var_dump($_POST['itemid']);

array(2) { [0]=> string(2) "13" [1]=> string(2) "14" }

Here items 13 and 14 were selected and now only the items with the matching id numbers should be displayed in the html table on the new page.

As simple a solution you can give me would be preferred so I can understand it. Thanks!

Readie

1:45 pm on Mar 15, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Well, what I am doing is simply looping through every value of $_POST and adding the value of the posted item to the SQL string. If it's not product_name then change it to WHERE id

The reason I have these 2 if statements:

if(strtolower($_POST['formSubmit']) === "compare") {
if(isset($postie) && $postie != "" && strtolower($postie) != "compare") {

Is because the value of submit buttons are sent to the $_POST array too.

To help your understanding a bit, try telling the form to post to, say, test.php, and have the contents of test.php be:

<?php

echo '<pre>';
print_r($_POST);
echo '</pre>';

?>

Matthew1980

2:09 pm on Mar 15, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



hi there WoodNotOil,

Are you checking the whole array to see what is being sent from the form, you will need to see if all the elements of the form are being sent, always worth checking as this can prove any typo's ;-p

Also as you are checking the $_POST array (though I think that the functionality is the same) try doing the same check using print_r($_POST); after the form is submitted, this will tell you the name's of the elements that are being sent, always worth a check.

All as Readie is doing there is looping through the data and anything that isnt the submit button is getting added to the IN() function via the concatonated $sql_in .= data block that is being built from the number of item id's that have been passed from the form. Hope thats not too confusing ;-p Then finally he's trimming the data to remove any whitespace from the data sent via $_POST...

[EDIT] With regards to the other functions, they are there to prevent malicious code injection from happening, though, it is only prevention...

$_POST & $_GET sanitising:-

[webmasterworld.com ]
Give this a read, really good for starters ;-p

Cheers,
MRb

WoodNotOil

12:47 pm on Mar 16, 2010 (gmt 0)

10+ Year Member



I finally figured out what the problem I was having with it was. I got it working using the IN, but the mysql_fetch_row returns an array using a number to indicate fields instead of the field names. Any idea why that would happen? Here is what I used that worked:


$arr = $_POST['itemid'];

$sql = implode(", ",$arr);

$query = mysql_query("SELECT * FROM table WHERE id IN($sql)");

while ($data = mysql_fetch_row($query)) {

$p_name = $data['2'];

echo $p_name;
}



I am open to suggestions on how to make this more secure and alternate ways to get the row to not come out as an array. Thanks for the help!

Matthew1980

1:04 pm on Mar 16, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi there WoodNotOil,

Advice: $data is more than likely a reserved word, use an alternative ;-p

Do a print_r($data); to see exactly what is in the array:


while ($sql_return = mysql_fetch_row($query)) {

print_r($sql_return);
}


Hope that gets you on the right footing ;-p
Cheers,
MRb

WoodNotOil

1:09 pm on Mar 16, 2010 (gmt 0)

10+ Year Member



I have it working now using the results of the array. I was just curious if there was a way to get the results not as an array. It was using print_r for each string along the way that clued me into the fact that it was in an array. A very handy command!

Matthew1980

1:43 pm on Mar 16, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi there WoodNotOil,

When retreiving data from a table the format that data is returned in is usually in array format, simply because for ease of use and manipulation. I agree too, as print_r(); is great function, it's a tried and tested way of seeing if the database query is functioning!

There are of course different methods of getting the data, mysql_fetch_array & mysql_fetch_object are one in the same thing, its just the way of accessing the data that alters:-

$sql = mysql_fetch_array($get_sql);

$sql['rowname'];

and

$sql = mysql_fetch_object($get_sql);

$sql->rowname;

for object.

These are just a couple of methods for use in getting data from tables.

Check out [uk.php.net ] for more info

Good luck for the rest of the site.
Cheers,
MRb