Reputation: 47
i have this code which i use to print some fields from the database.
My problem is that i get this error about foreach invalid argument supplied and a mysql fetch array problem.
The code is this:
foreach( $checked1 as $key => $value){
echo "<th> $value </th>";
}
echo "</tr></thead>";
while($row = mysql_fetch_array($result)){
Where $checked1
is an array
$checked1 = $_POST['checkbox'];
What's the problem here?
The whole code:
<?php
echo "<div id='table-3'>";
if(isset($_POST['Submit'])) {
echo "<pre>";
$checked1 = $_POST['checkbox'];
$checked = implode(',', $_POST['checkbox']);
}
$con = mysql_connect('localhost','user','passwd');
mysql_query("SET NAMES UTF8");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db_name", $con);
$result = mysql_query("SELECT $checked FROM hostess");
echo "<table >";
echo "<thead><tr>";
if(is_array($_POST['checkbox'])){
foreach( $checked1 as $key => $value){
echo "<th> $value </th>";
}
echo "</tr></thead>";
} else {
echo "Checkbox is not an array.";
}
while($row = mysql_fetch_array($result)){
echo "<tr>";
foreach($checked1 as $key => $value){
if($value == 'photo'){
echo "<td> <img src=foto/photo1/".$row[$value] . "></td>";
} else if($value == 'photo2'){
echo "<td><img src=foto/photo2/".$row[$value] . "></td></td>";
}
else if( $value == 'photo2' && $value == 'photo'){
echo "<td> <img src=foto/photo1/".$row[$value] . "></td>";
echo "<td><img src=foto/photo2/".$row[$value] . "></td></td>";
}
else{
echo "<td>" . $row[$value] . "</td>";
}
}echo "</tr>";
}
echo "</table>";
Upvotes: 0
Views: 294
Reputation: 111
What is your $_POST['checkbox'] called in your HTML form? It should be something like:
<input type="checkbox" name="checkbox[]" value="1" />
Check to make sure your checkbox values are coming through as arrays. Do the following:
if(is_array($_POST['checkbox'])){
// contiue with foreach...
} else {
echo "Checkbox is not an array.";
}
Upvotes: 1
Reputation: 29462
Either $_POST['checkbox']
is not defined (no checkbox checked while sending form) or is not an array (input name does not contain []
in the end);
You should always check if variable contain what you want before performing any operation on it, ex:
if(is_array($checked1)){
foreach( ... ){
}
}
$result = mysql_query(' ... ');
if(!$result){
die(mysql_error());
}
Upvotes: 1