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);
}
Related
I am trying to save 'newentryname' as the field name in my code - but I'm always getting an error, when I examine the sql table it saves the first time after refreshing the table, but then after it doesn't save
I am pulling the fields from another table and looping them into the input fields, and I am then trying to get the fieldnames into a loop to put into a string to save in the SQL, to be used elsewhere.
Section 1: This is connects to the separate table inside the same wordpress SQL table - the $wpdb variable is contains the sql connection information
<?php
global $wpdb;
// Add table name as variable to include prefix
$rowname = $wpdb->prefix . 'rowname';
$results = $wpdb->get_results("SELECT * FROM $rowname ");
// $selected = $item['name'];
Section 2: This section of the code echo's out the input fields as checkboxes in a loop
/** Loop through the $results and add each as a checkbox options */
$checked = ' ';
foreach($results as $result) :
$resultid = $result->ID;
$resultrowname = $result->name;
$options.= sprintf("\t".'<input
type="checkbox" ' . '%1$s' . 'value="%3$s" name="newentryname[]" >%3$s'."\n", $checked, $resultid, $resultrowname);
endforeach;
Note: above I'm not sure if the newentryname[] is what is causing the error - I can't tell what information this is is sending to the database ideally I only want it to store the data to be used in Section 3 below:
Section 3: This should be combining the data input from the above table, and adding it to a string, so it can be saved in a single field - but I'm not sure if the code is getting that far.
$fieldname=$item['fieldname'];
// You have to loop through the array of checked box values ...
$newentryname="";
foreach($fieldname as $entry):
$newentryname .= $entry.", ";
endforeach;
echo $options;
?>
EDIT: The above is inside a function
functionname($item)
and the code to insert it into the database is:
$result = $wpdb->insert($table_name, $item);
I am wondering if it's the fieldname 'newentryname' also being submitted to the database, and how would I get around this problem, and how would I submit the data from section three into the database instead
Needed to add $n = 0 and n++ in the foreach loop
$checked = ' ';
$n = 0;
foreach($results as $result) :
$resultid = $result->ID;
$resultrowname = $result->name;
$n++;
$options.= sprintf("\t".'<input
type="checkbox" ' . '%1$s' . 'value="%3$s" name="newentryname[]" >%3$s'."\n", $checked, $resultid, $resultrowname);
endforeach;
and then I replaced this section of the code below:
$fieldname=$item['fieldname'];
// You have to loop through the array of checked box values ...
$newentryname="";
foreach($fieldname as $entry):
$newentryname .= $entry.", ";
endforeach;
echo $options;
With this code, to handle the output and echo out the output so it can be used to be sent elsewhere
$fieldname = $_POST['fieldname'];
foreach($fieldname as $entry):
$output .= $entry.", ";
endforeach;
echo $output;
I still get the error which is because of the way my array structure works, it still doesn't like the array within an array, but to correct the above code the above is what needs to be done.
My form have multiple checkboxes in it (each with the code):
<input type="checkbox" name="id[]" value="<? echo $row['id'] ?>">
when user select id = 2 , 3 and 9 and submit the value. In my update php i am using following code to get selected value
echo "Check box test<pre>" ;
print_r($id);
echo "</pre>";
if(!empty($_POST['id'])) {
foreach($_POST['id'] as $check) {
echo $check."\n";
}
}
// update data in mysql database
$sql="UPDATE table SET display = '2' WHERE id IN ($check)";
i am always getting last selected id updated like 9
but i am not getting result as i wanted like
$sql="UPDATE table SET display = '2' WHERE id IN (2,3,9)";
. please Help what to do. i am very new to php.
You are doing nothing with $check, Make id like this
$ids="";
if(!empty($_POST['id'])) {
foreach($_POST['id'] as $id) {
$ids[] = $id;
}
}
$check = implode(",", $ids);
Because you are iterating the loop and $check will have latest value for the iteration.
foreach($_POST['id'] as $check) {
echo $check."\n";
}
Why can't you try instead ?
$check[] = $_POST['id'];
I think you need to get a better understanding of echo and the diference between server-side and client-side.
What you are looking for is implode
if(!empty($_POST['id'])){
$check = '(' . implode(',', $_POST['id']) . ')';
}
First I want to explain my application:
I have created an application for my QA work. The application generates a document gets saved as a pdf and added to the server. I have a dynamic table in it that gets save to the database using the implode function separating it as with a comma in the same row as the test case on the database.
It all works fine, but when I want to view the test case I am having trouble to figuring out how to get it to display. I have read plenty of scenarios to use the explode but no luck...
<?php include 'app_database/database.php'; ?>
<?php
if(isset($_POST)){
$step = $_REQUEST['step'];
$url = $_REQUEST['url'];
$pass_fail = $_REQUEST['pass_fail'];
$comment = $_REQUEST['comment'];
$sql1 ="UPDATE qa_testing_application SET step='".implode(',',$step)."',url='" . implode(',',$url) . "',pass_fail='" . implode(',',$pass_fail) . "',comment='" . implode(',',$comment) . "' WHERE test_case_name='$test_case_name'";
$result= mysqli_query($database, $sql1) or die(mysqli_error($database));
}
?>
I am inserting it this way. And i would like to retrieve it from the DB.
I would love to display it as follows:
Please see the link http://i.stack.imgur.com/6aglk.jpg
At the moment i am trying to test and figure out how to display it:
Not sure how to implement a for or foreach function in here as well if thats needed.
$countsteps = 0;
$counturls = 0;
$countpass_fails = 0;
$countcomments = 0;
$test_case_number = '21';
$select_tbl=mysqli_query($database,"select * from qa_testing_application WHERE test_case_number='$test_case_number'");
$result = mysqli_query($database, $sql1) or die(mysqli_error($database));
while($fetch=mysqli_fetch_object($result))
{
$step=$fetch->step;
$url=$fetch->url;
$pass_fail=$fetch->pass_fail;
$comment=$fetch->comment;
$steps=explode(",",$step);
$urls=explode(",",$url);
$pass_fails=explode(",",$pass_fail);
$comments=explode(",",$comment);
echo '<td>'.$steps[$countsteps++].'</td>';
echo '<td>'.$urls[$counturls++]."</td>";
echo '<td>'.$pass_fails[$countpass_fails++]."</td>";
echo '<td>'.$comments[$countcomments++]."</td>";
}
So how would I get this to display in a table?
edit:
Oh and this is the error that I get:
Undefined Offset
This error simply says there is no such key exists into given array or you're trying to fetch a value from non-array variable.
To show data into tabular format, you don't need to explode data coming from db. They are already concatenated.
So to show data from db, modify your code as show below:
$test_case_number = '21';
$select_tbl=mysqli_query($database,"select * from qa_testing_application WHERE test_case_number='$test_case_number'");
$result = mysqli_query($database, $sql1) or die(mysqli_error($database));
echo '<table>';
echo '<th>Step</th><th>Url</th><th>Pass/Fail</th><th>Comment</th>';
while($fetch=mysqli_fetch_object($result))
{
echo '<tr>';
echo '<td>'.$fetch->step.'</td>';
echo '<td>'.$fetch->url.'</td>';
echo '<td>'.$fetch->pass_fail.'</td>';
echo '<td>'.$fetch->comment.'</td>';
echo '</tr>';
}
echo '</table>';
I am currently running into an issue, where I have this form consisting of checkboxes. I get the values of user preferences for the checkboxes from a database. Everything works great, and does what is supposed to do, however after I change and check some boxes and then hit the submit button, it will still show the old values to the form again. If I click again in the page again it will show the new values.
The code is shown below with comments.
<form action="myprofile.php" method="post">
<?php $usr_cats=array();
$qry_usrcat="SELECT category_id_fk
FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';";
$result = mysqli_query($conn,$qry_usrcat);
while($row = mysqli_fetch_array($result)){
$usr_cats[] = $row[0]; // getting user categories from db stored in array
}
$query_allcats="SELECT category_id,category_name, portal_name
FROM categories
INNER JOIN portals on categories.portal_id=portals.portal_id
ORDER BY category_id;"; // select all category queries
$result = mysqli_query($conn,$query_allcats);
while($row = mysqli_fetch_array($result)){
echo $row['portal_name'] . "<input "; //print categories
if(in_array($row['category_id'], $usr_cats)){ // if in array from db, check the checkbox
echo "checked ";
}
echo "type='checkbox' name='categories[]' value='";
echo $row['category_id']."'> ". $row['category_name']."</br>\n\t\t\t\t\t\t";
}
?>
<input type="submit" name="submit" value="Submit"/>
<?php
$qry_del_usrcats="DELETE FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';"; //delete all query
if(isset($_POST['submit'])){
if(!empty($_POST['categories'])){
$cats= $_POST['categories'];
$result = mysqli_query($conn,$qry_del_usrcats); //delete all
for ($x = 0; $x < count($cats); $x++) {
$qry_add_usrcats="INSERT INTO `user_categories` (`user_id_fk`, `category_id_fk`)
VALUES ('".$_SESSION['user_id']."', '".$cats[$x]."');";
$result = mysqli_query($conn,$qry_add_usrcats);
}
echo "success";
}
elseif(empty($_POST['categories'])){ //if nothing is selected delete all
$result = mysqli_query($conn,$qry_del_usrcats);
}
unset($usr_cats);
unset($cats);
}
?>
I am not sure what is causing to do that. Something is causing not to update the form after the submission. However, as i said everything works great meaning after i submit the values are stored and saved in the DB, but not shown/updated on the form. Let me know if you need any clarifications.
Thank you
Your procedural logic is backwards and you're doing a bunch of INSERT queries you don't need. As #sean said, change the order.
<?php
if(isset($_POST['submit'])){
if(isset($_POST['categories'])){
$cats= $_POST['categories'];
// don't do an INSERT for each category, build the values and do only one INSERT query with multiple values
$values = '';
for($x = 0; $x < count($cats); $x++) {
// add each value...
$values .= "('".$_SESSION['user_id']."', '".$cats[$x]."'),";
}
// trim the trailing apostrophe and add the values to the query
$qry_add_usrcats="INSERT INTO `user_categories` (`user_id_fk`, `category_id_fk`) VALUES ". rtrim($values,',');
$result = mysqli_query($conn,$qry_add_usrcats);
echo "success";
}
elseif(!isset($_POST['categories'])){ //if nothing is selected delete all
// you may want to put this query first, so if something is checked you delete all, so the db is clean and ready for the new data.
// and if nothing is checked, you're still deleting....
$qry_del_usrcats="DELETE FROM user_categories WHERE user_id_fk='".$_SESSION['user_id']."';"; //delete all query
$result = mysqli_query($conn,$qry_del_usrcats);
}
unset($usr_cats);
unset($cats);
}
?>
<form action="myprofile.php" method="post">
<?php $usr_cats=array();
$qry_usrcat="SELECT category_id_fk FROM user_categories WHERE user_id_fk='".$_SESSION['user_id']."';";
$result = mysqli_query($conn,$qry_usrcat);
while($row = mysqli_fetch_array($result)){
$usr_cats[] = $row[0]; // getting user categories from db stored in array
}
$query_allcats="SELECT category_id,category_name, portal_name FROM categories INNER JOIN portals on categories.portal_id=portals.portal_id ORDER BY category_id;"; // select all category queries
$result = mysqli_query($conn,$query_allcats);
while($row = mysqli_fetch_array($result)){
echo $row['portal_name'] . "<input "; //print categories
if(in_array($row['category_id'], $usr_cats)){ // if in array from db, check the checkbox
echo "checked ";
}
echo "type='checkbox' name='categories[]' value='";
echo $row['category_id']."'> ". $row['category_name']."</br>\n\t\t\t\t\t\t";
}
?>
<input type="submit" name="submit" value="Submit"/>
Typically this occurs due to the order of your queries within the script.
If you want to show your updated results after submission, you should make your update or insert queries to be conditional, and have the script call itself. The order of your scripts is fine, but you just need to do the following:
Take this query:
$qry_del_usrcats="DELETE FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';"
and put it inside the if statement so it looks like this:
if (isset($_POST['submit'] {
$qry_del_usrcats="DELETE FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';"
$result = mysqli_query($conn,$qry_del_usrcats);
[along with the other updates you have]
}
Also, you will need to move this entire conditional above the form itself; typically any updates, inserts, or deletes should appear year the top of the form, and then call the selects afterward (outside of the conditional)
I am trying to combine two things which are already know how to do, but can't figure out how to combine them. Here is what I want to achieve:
I have a database with locations and events. There are several events in each location. I will be using PHP to query the database and output the code needed to display search results. I want something similar to the below:
<div id="location">
<p>Location1</p>
<div id="event">Event1</div>
<div id="event">Event2</div>
<div id="event">Event3</div>
</div>
<div id="location">
<p>Location2</p>
<div id="event">Event4</div>
<div id="event">Event5</div>
<div id="event">Event6</div>
</div>
I know that I can use select distinct to get the unique value of each location, and know that I can use a normal select statement to get all the events, however how do add all the events inside the location div?
My current PHP looks like this:
$sql ="SELECT location, event from events";
$res = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($res)){
$location = $row['location'];
$event = $row['event'];
echo "<div id="location">
<p>$location</p>
<div id="event">$event</div>
</div>";
}
My current code adds duplicates of the same location with 1 unique event in each. Even if I use select distinct I get the same results. How do I group the events have have the same location?
I think you should write something like:
$sql ="SELECT location, event from events";
$res = mysql_query($sql) or die(mysql_error());
$prevlocation = "";
while($row = mysql_fetch_assoc($res))
{
$location = $row['location'];
$event = $row['event'];
if ( $prevlocation != "" ) // Close previous div if needed
{
echo "</div>";
}
if ( $location != $prevlocation )
{
echo "<div id='location'><p>$location</p>";
$prevlocation = $location;
}
else
{
echo "<div id='event'>$event</div>";
}
}
echo "</div>"; // Close last div
If you have join of two tables, let's assume that your query looks like this:
$sql ="SELECT * FROM events
JOIN locations ON
locations.id=events.loc_id";
And then, within one loop, get events and location arrays:
$res = mysql_query($sql) or die(mysql_error());
$locations = array();
$events= array();
while($row = mysql_fetch_assoc($res))
{
$location = $row['location'];
$event = $row['event'];
$loc_id=$row['loc_id'];
$id=$row['id'];
$events[]=$loc_id.'%'.$event;
if(!in_array($id.'%'.$location,$locations)) { // avoid duplicate entries
$locations[]=$id.'%'.$location;
}
}
And, another loop (+loop inside loop):
for($i=0;$i<count($locations);$i++) {
$location=explode('%',$locations[$i]);
echo "<div class='location'>\n
<p>$location[1]</p>\n";
for($j=0;$j<count($events);$j++) {
$event=explode('%',$events[$j]);
if($event[0]==$locations[$i][0]) {
echo "<div class='event'>".$event[1]."</div>";
}
}
echo "</div>";
}
Not so elegant, but it is working, and produces valid HTML. :)
First, i wanted to make two associative arrays, and to compare keys, but i couldn't, because i couldn't convert ID keys to strings, so i made it with explode (% is separator between key and value).