PHP echoing MySQL database fields and checkboxes - php

I've got this code designed to echo a list of people from a specific location. You can then group all these people by checking boxes next to their names and submitting the form which will update the database with the new group. It all sounds pretty simple. But unfortunately the database is set up using a lot of tables that are associated with one another. So it gets a bit complicated. Here's what I have so far:
<?php
//Query the database for the Location ID of the currently logged in user
$query1 = mysql_query("SELECT * FROM `Location` WHERE Name = '".$_SESSION['Location']."'");
$array1 = mysql_fetch_array($query1);
//Query the database for the all the participants in this location, make an array of the results and then implode the array
$query2 = mysql_query("SELECT idParticipant FROM `Participant/Location` WHERE idLocation = ".$array1['idLocation'].";");
$column1 = array();
while($row = mysql_fetch_array($query2)){
$column1[] = $row['idParticipant'];
}
$values = implode(' OR ', $column1);
//Query database for all first names where the particpant ID's equal those of the above $values
$query3 = mysql_query("SELECT firstName FROM `Participant` WHERE idParticipant = $values;");
$columnFirstName = array();
while($row = mysql_fetch_array($query3)){
$columnFirstName[] = $row['firstName'];
}
foreach($columnFirstName as $value){
echo "<input type='checkbox' name='check[]' id='' value='' />";
echo $value."<br><br>";
}
?>
<input type="submit" name="submit" value="Save New Group">
</form>
So the above code echoes out all the first names in that location and adds a check box beside it. The problem is I need the second names to appear beside the first names too. AND I need to get the ID's of each person to put in the value for the checkbox.
I'm not sure how I can do this... I think I need to make a second query for the second names then tweak my foreach loop...and I'll probably need a whole new foreach loop for the id's, won't I?

This is what I needed to do:
$query3 = mysql_query("SELECT * FROM `Participant` WHERE idParticipant = $values;");
$columnFirstName = array();
$columnSecondName = array();
$columnID = array();
while($row = mysql_fetch_array($query3)){
$columnFirstName[] = $row['firstName'];
$columnSecondName[] = $row['secondName'];
$columnID[] = $row['idParticipant'];
}
for($i=0;$i<count($columnFirstName);$i++) {
$firstName = $columnFirstName[$i];
$secondName = $columnSecondName[$i];
$id = $columnID[$i];
echo "<input type='checkbox' name='check[]' id='$id' value='$id' />";
echo $firstName." ";
echo $secondName."<br><br>";
}
?>
<input type="submit" name="submit" value="Save New Group">
</form>

Related

insert multiple rows into sql database at once through php input form

I am trying to record the results of a car race, but I want to be able to enter all of the results for the race at once (rather than doing it one by one) but I just cannot seem to get it to work.
Code below:
INPUT FORM:
{
$reID = $row['reID'];
$racerID = $row['racerID'];
echo "<tr>";
echo "<td>$reID<input type='hidden' name='reID' value='$reID'>";
echo "<td>$racerID<input type='hidden' name='racerID' value='$racerID'>";
echo"<td><input type='text' name='rank'>";
echo"<td><input type='text' name='timetaken'>";
}
SQL INSERT FORM:
$rank=$_POST['rank'];
$timetaken=$_POST['timetaken'];
$reID=$_POST['reID'];
$racerID=$_POST['racerID'];
$sql = mysql_query("INSERT INTO Racing (rank, timetaken, reID, racerID) VALUES ('$rank', '$timetaken', '$reID', '$racerID')");
$result = mysql_query($sql);
How this works is, I will select a race, then a specific event within that race, then that will display all the racers and I can enter their rank and time taken. At the same time the hidden inputs (racer no and raceevent will go into the database for each result too).
So I am trying to just enter all the ranks and timetaken for all racerIDs at once, can someone help me complete that please.
Thanks.
EXTRA:
$reID = $_GET['reID'];
$result = mysql_query("SELECT * FROM RaceEventRacer WHERE reID = $reID");
while ($row = mysql_fetch_assoc($result))
First of all u have to fix some issues with ur php form generation...
all of ur input elements are going to have the same name attribute...
correct it first
-use something like this
$cv=0;
while () {
.......................
.......................
echo "<input name='racer_'.$cv>"; // in each repetition new name value, not the same
$cv++;
}
Instead of having name='reID' you should have name='reID[]', the same withthe other fields. And the future code would look like this:
$ranks = $_POST['rank'];
$timetakens = $_POST['timetaken'];
$reIDs = $_POST['reID'];
$racerIDs = $_POST['racerID'];
$sql = "INSERT INTO Racing (rank, timetaken, reID, racerID) VALUES";
$values = array();
foreach($ranks as $key => $rank) {
$values[] = "('$rank', '{$timetakens[$key]}', '{$reIDs[$key]}', '{$racerIDs[$key]}')";
}
$sql .= implode(', ', $values);
$query = mysql_query($sql);

How do I extract variables from dynamic array and create an update query?

I have a form that is dynamically created based off multiple mysql tables. This form sends to an external page for processing.
this means that my $_POST data will always be different. I need to extract the post array, strip it down and create a query.
here's the print_r of the Posted array:
Array ( [userid] => 1 [modid1] => on [fid1] => on [fid3] => on [fid5] => on [fid7] => on [fid8] => on [modid3] => on )
as you can see I have three parts to this userid, modid, and fid. the catch is, the only way I could pass the id's I need is to name the fields that. So each modid and fid are rows in the db. the number after that is the id that needs updating, and of course "on" is from the check box.
so end result would be something like:
to give a better idea here's how I would write the query normally
for modid1:
UPDATE table SET var = var WHERE modid = 1
for fid1
UPDATE table SET var = var WHERE fid = 1
heres the code that generated this array:
<form id="ajaxsubmit" method="post" action="modules/users/updaterights.php">
<?php
$modsql = mysql_query("SELECT * FROM modules")or die("Mod failed " .mysql_error());
while($row = mysql_fetch_array($modsql))
{
echo '<div class="rights">';
echo "<ul>";
$userid = safe($_POST['user']);
$id = $row['id'];
$sql = mysql_query("SELECT * FROM modpermissions WHERE userid = '$userid' AND modid = '$id'")or die("Mod died " .mysql_error());
$sql2 = mysql_fetch_array($sql);
$modper = $sql2['modpermission'];
if($modper == 1){
echo '<li><input type="checkbox" name="modid'.$row["id"].'" checked> <b>'.$row["name"].'</b></li>';
}
if($modper == 0){
echo '<li><input type="checkbox" name="modid'.$row["id"].'"> <b>'.$row["name"].'</b></li>';
}
if($row['features'] == 1)
{
echo "<ul>";
$sql = mysql_query("SELECT * FROM features WHERE modid = '$id'")or die("Features loop failed " .mysql_error());
while($row2 = mysql_fetch_array($sql))
{
$userid2 = safe($_POST['user']);
$id2 = $row2['id'];
$sql3 = mysql_query("SELECT * FROM fpermissions WHERE userid = '$userid2' AND fid = '$id2'")or die("features died " .mysql_error());
$sql4 = mysql_fetch_array($sql3);
$fper = $sql4['fpermission'];
if($fper == 1){
echo '<li><input type="checkbox" name="fid'.$row2["id"].'" checked> '.$row2['feature'].'</li>';
}
if($fper == 0){
echo '<li><input type="checkbox" name="fid'.$row2["id"].'"> '.$row2['feature'].'</li>';
}
}
echo "</ul>";
}
echo "</ul>";
echo '</div>';
}
?>
<p><input type="submit" id="submit" value="Submit" class="button"> <input type="reset" class="reset" value="Reset Form"> </p>
</form>
its a mess I know, im learning. If someone can understand my question and point me in the right direction to accomplish what Im attempting I would be grateful.
First thing to do is to store the old value as well as having the check box (using a hidden field).
I would also suggest as a minimum using a fixed character as a delimeter in your field names so you can explode the field name to easy get the part that is the id.
Also consider using joins rather than looping around one result, and for each one doing another query.
Your output script would look something like this:-
<form id="ajaxsubmit" method="post" action="modules/users/updaterights.php">
<?php
$userid = safe($_POST['user']);
$modsql = mysql_query("SELECT modules.id, modules.features, modules.name, modpermissions.modpermission
FROM modules
LEFT OUTER JOIN modpermissions
ON modules.id = modpermissions.modid
AND modpermissions.userid = '$userid'")or die("Mod failed " .mysql_error());
$PrevModuleId = 0;
while($row = mysql_fetch_array($modsql))
{
if ($PrevModuleId != $row['id'])
{
if ($PrevModuleId != 0)
{
echo "</ul>";
echo '</div>';
}
echo '<div class="rights">';
echo "<ul>";
$PrevModuleId = $row['id'];
}
echo '<li><input type="checkbox" name="modid_'.$row["id"].'" '.(($row['modpermission'] == 1) ? "checked='checked'" : "").'><input type="hidden" name="modid_old_'.$row["id"].'" value="'.$row['modpermission'].'"> <b>'.$row["name"].'</b></li>';
if($row['features'] == 1)
{
echo "<ul>";
$sql = mysql_query("SELECT features.id, features.feature, fpermissions.fpermission
FROM features
INNER JOIN fpermissions
ON features.id = fpermissions.fid
AND fpermissions.userid = $userid
WHERE modid = '$id'")or die("Features loop failed " .mysql_error());
while($row2 = mysql_fetch_array($sql))
{
echo '<li><input type="checkbox" name="fid_'.$row2["id"].'" '.(($row2['fpermission'] == 1) ? "checked='checked'" : "").'><input type="hidden" name="fid_old_'.$row2["id"].'" value="'.$row2['fpermission'].'"> '.$row2['feature'].'</li>';
}
echo "</ul>";
}
}
if ($PrevModuleId != 0)
{
echo "</ul>";
echo '</div>';
}
?>
<p><input type="submit" id="submit" value="Submit" class="button"> <input type="reset" class="reset" value="Reset Form"> </p>
</form>
You can then loop through each entry on the $_POST array, explode the key based on the _ character, check when the values have changed and if needs be do an update Or possibly you can use an INSERT instead, but using ON DUPLICATE KEY update type syntax (this way you can update many rows with different values easily).
Note you also need to put the userid value somewhere in your form (probably as another hidden field) so you have the value to process with the updates.

Display checked checkbox record from database

I have looked through similar problems and solution but somehow only half way help me with my problem. I'm trying to make a form to checked more than one record from MySQL database and display the checked record to another page. Somehow I managed to do the page with check boxes but I don't know how to display the record checked. It can only display the first row of the record or all the records regardless which box are checked.
This is checkbox page
$columns = count($fieldarray);
//run the query
$result = mysql_query(
"SELECT * FROM request_item
ORDER BY request_item.IllNo DESC LIMIT 0, 6") or die(mysql_error());
$row = mysql_num_rows($result);
while($row=mysql_fetch_array($result))
{
{
$rows[] = $row['IllNo'];
}
foreach($rows as $value);
echo "";
echo " ";
echo $row['IllNo'];
echo "";
}
echo "";
?>
This is display record checked
$columns = count($fieldarray);
//run the query
$result = mysql_query(
"SELECT * FROM request_item
ORDER BY request_item.IllNo DESC LIMIT 0, 6") or die(mysql_error());
$row = mysql_num_rows($result);
while($row=mysql_fetch_array($result))
{
$rows[]=$row['IllNo'];
foreach($rows as $value);
if ($rows= 'checked') {
echo "";
echo $value;
}
Any help are welcome. Thank you.
There's actually a lot of problems with that script including syntax errors, calling the wrong variable name, form not opening where it should, invoking PHP after you already have, etc...
To get a good answer to you, you should share what make $row['IllNo'] should equal to indicate if it should be checked or not.
I reformatted it a bit and this may give you a good start.
<form NAME ="form1" METHOD ="POST" ACTION ="dari.php">
<table>
<?php
$columns = count($fieldarray);
//run the query
$result = mysql_query("SELECT * FROM request_item ORDER BY request_item.IllNo DESC LIMIT 0, 6") or die(mysql_error()) ;
$row = mysql_num_rows($result);
while($row=mysql_fetch_array($result)) {
echo "<tr><td>";
echo "<Input type = 'Checkbox' Name ='ch1' value ='ch1'";
// check checked if it is. this will be checked if $row['IllNo'] has a value
// if there were a condition to make it checked, you would put the condition
// before the ?
echo $row['IllNo'] ? ' checked' : '';
echo ' />';
echo $row['IllNo'];
echo "</td></tr>";
}
?>
</table>
<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Choose your books">
</FORM>

inserting checkbox values to database

I have a php form with some textbox and checkboxes which is connected to a database
I want to enter all the details into the database from the form.All the textbox values are getting entered except the checkbox values.I have a single column in my table for entering the checkbox values and the column name is URLID.I want to enter all the selected checkbox(URLID)values to that single column only ,separated by commas.I have attached the codings used.can anyone find the error and correct me?
NOTE: (The URLID values in the form is brought from the previous php page.those codings are also included.need not care about it)
URLID[]:
<BR><?php
$query = "SELECT URLID FROM webmeasurements";
$result = mysql_query($query);
while($row = mysql_fetch_row($result))
{
$URLID = $row[0];
echo "<input type=\"checkbox\" name=\"checkbox_URLID[]\" value=\"$row[0]\" />$row[0]<br />";
$checkbox_values = implode(',', $_POST['checkbox_URLID[]']);
}
?>
$URLID='';
if(isset($_POST['URLID']))
{
foreach ($_POST['URLID'] as $statename)
{
$URLID=implode(',',$statename)
}
}
$q="insert into table (URLID) values ($URLID)";
You really should separate your model from the view. It's 2011, not 2004 ;o
if (isset($_POST['checkbox_URLID']))
{
// Notice the lack of '[]' here.
$checkbox_values = implode(',', $_POST['checkbox_URLID']);
}
$URLIDs = array();
while($row = mysql_fetch_row($result))
{
$URLIDs[] = $row[0];
}
foreach ($URLIDs as $id)
{
?>
<input type="checkbox" name="checkbox_URLID[]" value="<?php echo $id; ?>" /><?php echo $id; ?><br />
<?php
}
?>
<input type="submit"/>

How to display mysql records as preselected checkboxes?

I have a table column called post_tags within a table called posts where assigned tags are stored separated by the # symbol. I also have a table called tags where all tag names are stored. I would like to design my database in a more normalized way but for the purpose I am trying to achieve this is the easiest option.
Anyway, I want to display on the screen all the entries from the tags table as checkboxes, so I do:
$query = mysql_query("SELECT * FROM tags ORDER BY name");
while ($row = mysql_fetch_assoc($query)) {
$tag = $row['name'];
echo "<input type='checkbox' name='tags[]' value='$tag' />\n";
}
Next I want to have the tags that are assigned to a particular post be preselected. For example, if I have a post with the following in it's post_tags column:
party#beaches#dolphins#
I want the "party", "beaches" and "dolphin" checkboxes to be checked by default (while the checkboxes for the other options are unchecked). How can this be done?
try the two results and the in_array() function.
<?php
$tags = mysql_query("SELECT * FROM tags ORDER BY name");
$post_tags = "party#beaches#dolphins#";
$arr_tags = explode("#", $post_tags);
while ($row = mysql_fetch_assoc($query)) {
$check = in_array($arr_tags, $row['name'])? 'checked="checked"' : "";
echo '<input type="checkbox" name="tags[]" value="'.$row['name'].'" '.$check.' />';
echo "\n";
}
?>
UPDATE
Because of Jeff question on performance, I looked for faster solutions and using isset() is faster so this would do a faster lookup of the values. the array_flip() is 3 time less taxing than in_array():
<?php
$tags = mysql_query("SELECT * FROM tags ORDER BY name");
$post_tags = "party#beaches#dolphins#";
$arr_tags = array_flip(explode("#", $post_tags));
while ($row = mysql_fetch_assoc($query)) {
$check = isset($arr_tags[$row['name']])? 'checked="checked"' : "";
echo '<input type="checkbox" name="tags[]" value="'.$row['name'].'" '.$check.' />';
echo "\n";
}
?>
The first thing to do is see if there is any existing data. So run that query and put the result of that table cell into lets say $checkedstring if not then put your default string in.
<?php
$checkedstring = "party#beaches#dolphins#";
//Pull from DB if exsists and set $checkedstring to that value
///
$checkeditems = explode ( "#" , $checkedstring);
$checked = array();
foreach($checkeditems as $item)
{
$checked[$item]=true;
}
$query = mysql_query("SELECT * FROM tags ORDER BY name");
while ($row = mysql_fetch_assoc($query))
{
$tag = $row['name'];
$checkedstatus = '';
if($checked[$tag])
{
$checkedstatus = "checked='checked'";
}
echo "<input type='checkbox' name='tags[]' value='$tag' $checkedstatus />\n";
}
?>

Categories