How to display mysql records as preselected checkboxes? - php

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";
}
?>

Related

Posting values to database

I am trying to post some values from checkboxes to my database, at the moment it does post a value, but only the last selected value (I currently have 8 checkboxes). Below is what I am using the get the checkboxes:
<?
$data = mysql_query("SELECT * FROM members WHERE active='Yes' ORDER BY name") or die(mysql_error());
//And we display the results
while($result = mysql_fetch_array( $data ))
{
echo "<input type='checkbox' name='attendees[]'";
echo 'value="' . $result['name'] . '">';
echo " ";
echo $result['name'];
echo "<br>";
}
?>
So they successfully show in my form and I can tick as many as I want however when I check the database, only the last one is showing.
I have been reading around and it seems like I need to store them in an array however this is the bit I am finding hard to understand.
Could anyone help me so that all values selected are shown in the DB and not just the last one?
EDIT: Too long to fit into a comment so here is the code where it adds the values to the DB
<?php
if(isset($_POST['submit']))
{
$date = $_POST['date'];
$score = $_POST['score'];
$attendees = $_POST['attendees'];
$result = mysql_query("INSERT INTO quiz_results (date, score, attendees)
VALUES ('$date','$score','$attendees')",$connect);
echo "<div class='alert alert-info'><b>Event Added!</b> - You'll will now be taken back to the previous page.</div>";
echo "<meta http-equiv=Refresh content=4;url=add-result.php>";
}//end of if($submit).
?>
$attendees = $_POST['attendees'];
$attendees is an array. You can't simply store the PHP array in the database without first transforming it into a string. You could store it as a comma separated list:
if ( is_array($attendees) ) {
$attendees = implode(', ', $attendees);
}
But, what happens when an "attendee" has a name that contains a comma? You could serialize it:
if ( is_array($attendees) ) {
$attendees = serialize($attendees);
}
But, in either case, what happens when you want to filter your data based on attendee? Now you have more problems.
The best way to manage this data (Google: database one-to-many relationships) is to store the attendees in a separate table that looks something like:
quiz_id attendee_id
1 20
1 42
1 50
See my answer at how to select from database based on a match in category? for an example.
Looks like you need to give each checkbox a different name.
$i=0;
while($result = mysql_fetch_array( $data ))
{
echo "<input type='checkbox' name='attendees[$i]'";
$i++
...
and I hope $_POST['attendees'] is an array?
Then when you insert into quiz results, you will need to loop through the arrays and insert one row of elements at a time into the database, you cant just insert arrays directly like that and expect each element to automatically take their own row.
Hope it helps, let me know.
View
<?php
$data = mysql_query("SELECT * FROM members WHERE active='Yes' ORDER BY name");
$html = '';
//And we display the results
while($result = mysql_fetch_array( $data )) {
$html .= sprintf( '<input type="checkbox" name="attendees[]" value="%d"> %s' , $result['id'] , $result['name'] );
}
echo $html;
When you post the form...
<?php
$attendees = isset( $_REQUEST['attendees'] ) ? $_REQUEST['attendees'] : null;
if( !is_null($attendees) && is_array($attendees)){
foreach( $attendees as $attendee){
// do something.. with attendee id
}
echo 'Ids: '.implode(', ', $attendees);
}

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.

PHP echoing MySQL database fields and checkboxes

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>

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"/>

Categories