Page 1 of 1

creating an array that'll $_POST into a database

Posted: Wed Aug 20, 2003 3:30 am
by hyper_st8
Got this array working that was suggested by Coco, but not sure how you would go around creating an array which doesn't have fixed values that are $_POST into the database

Code: Select all

<?php
<?
$pquery = "SELECT username from users WHERE groupname='$_SESSION[groupname]'"; 
$presult = mysql_query($pquery, $db_conn); 
   echo '<table><tr align="left" valign="top"><td class="main"><b>Job User(s) are for:</b><br />'; 
$x=0; 
while ($prow = mysql_fetch_array($presult)){ 
echo '<input type="checkbox" name="username['.$x.']" value="'.$prow['username'].'">'.$prow['username'].'<br />'; 
$x++; 
} 
echo '</td></tr></table>'; 
?> 

?>

Posted: Wed Aug 20, 2003 3:44 am
by greenhorn666
You could (my 2 cents ;)) leave the $x var out, it is no use

Code: Select all

<?
$pquery = "SELECT username from users WHERE groupname='$_SESSION[groupname]'";
$presult = mysql_query($pquery, $db_conn);
   echo '<table><tr align="left" valign="top"><td class="main"><b>Job User(s) are for:</b><br />';
while ($prow = mysql_fetch_array($presult)){
echo '<input type="checkbox" name="username[]" value="'.$prow['username'].'">'.$prow['username'].'<br />';
}
echo '</td></tr></table>';
?>
Then you have to loop over the username posted var:

Code: Select all

<?
while(list(, $user) = each($_POST["username"])) {
    // Do what is needed for each user here...
    // like echo their names 
    echo $user."<br />";
}
?>
I've used the while, because, if you stick to your $x var, and the user selects the first and 3rd user you'll get an array as such:
$_POST["username"][0] = "first user's name";
$_POST["username"][2] = "3rd user's name";

So you can't really use a for() loop
naming the checkbox as username[] will result in php creating the "ordered" array for you ([0], [1],...)

Don't know if it was really what you were asking for, but in the meantime it's an answer ;)

Posted: Wed Aug 20, 2003 3:59 am
by hyper_st8
thanks for the quick reply, but with the 2nd while loop does it create an array $user that gives the usernames that I need to put into the database.

Posted: Wed Aug 20, 2003 4:13 am
by greenhorn666
No, it loops thru the array, you got the array already:

Code: Select all

<?
$users = $_POST["username"]);
?>
Now $users contains all usernames...

Posted: Wed Aug 20, 2003 4:29 am
by hyper_st8
thanks for your help greenhorn666!