So here's what I basically want to do. I have display a list of members and each of them have a check box next to it.
Just like this:
[ ] Spongebob
[ ] Patrick
[ ] Squidward
[ ] Sandy
[ ] Mr. Krab
[ OK ]
Whenever I select a number of members, and click OK, it will lead to a print page. In that print page, I want the members to be listed in two columns like this:
Spongebob | Patrick |
Squidward | Sandy |
Mr. Krab |
So far, I've only done it to be in a single column.
Here is my current code:
if(isset($_POST['ok'])){
if(!empty($_POST['check_list'])) {
$check_list = $_POST['check_list'];
foreach ($check_list as $selected){
$sql = mysql_query("SELECT * FROM addmember WHERE id = '".$selected."' ORDER BY id");
$limit = 2;
$count = 0;
echo "<table>";
while ($row = mysql_fetch_array($sql)){
$name = $row ['name'];
if ($count < $limit){
if ($count == 0){
echo "<tr>";
}
echo "<td>$name";
}else{
$count = 0;
echo "</tr><tr><td>
$name</td><tr>";
}
$count++;
}
echo "</tr></table>";
}
echo '<script>window.print();</script>';
}
else{
echo "<script>alert('Please select at least one member.');</script>";
echo "<script>window.history.go(-1)</script>";
}
}
Any suggestion and advice is very appreciated.. Thank you very much.
I think that your while is not necessary, because you only need one row. You have overcomplicated things a bit.
You need to check
$count
is 0 - start row$count == $limit
or is last item of all - end rowAnd thats it. Between just echo <td>
with $name
.
So try this:
if(isset($_POST['ok'])){
if(!empty($_POST['check_list'])) {
$check_list = $_POST['check_list'];
$itemsCount = count($check_list);
$limit = 2;
$count = $doneCount = 0;
echo "<table>";
foreach ($check_list as $selected){
$sql = mysql_query("SELECT * FROM addmember WHERE id = '".$selected."' ORDER BY id LIMIT 1");
$row = mysql_fetch_array($sql);
$name = $row['name'];
// Start new row
if ($count == 0){
echo "<tr>";
}
// Echo name
echo "<td>".$name."</td>";
// End row, increment counters
if (++$count == $limit || $itemsCount == ++$doneCount ){
$count = 0;
echo "</tr>";
}
}
echo "</tr></table>";
echo '<script>window.print();</script>';
}
else{
echo "<script>alert('Please select at least one member.');</script>";
echo "<script>window.history.go(-1)</script>";
}
}
++$count
increments by one and then returns it, so we compare and increment all in one. See PHP: Incrementing/Decrementing Operators.
Don't use mysql_*
functions anymore, cause they are deprecated. Instead use MySQLi or PDO.
Futher reading: