Insert multiple checkboxes into Database Html Php - php

So i have a table, that I load checkbox values into. Once the checkboxes are clicked, I use a submit button to save them into a database. However at the moment I can only Save one row at a time? I need to be able to save all clicked checkboxes into the datbase
For example i have 5 rows. If the checkboxes on row 2 and 3 are checked then they should be saved into the database however right now only the last clicked(row 3) are being saved into the database.
Heres my code so far
Php connect code
<?php
// Get a db connection.
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
$query->select($db->quoteName(array('CV_ID', 'Classifier', 'Value')));
$query->from($db->quoteName('classvalues'));
// Reset the query using our newly populated query object.
$db->setQuery($query);
// Load the results as a list of stdClass objects (see later for more options on retrieving data).
$results = $db->loadObjectList();
?>
Loading table with checkboxes code
<form name="names" id="names" action="<?php echo JURI::current(); ?>" method="post">
<table border="5",th,td, cellspacing="5", cellpadding="5", width="500", align="left">
<tr>
<th>CV_ID</th>
<th>Classifier</th>
<th>Level</th>
</tr>
<?php foreach ($results as $row): ?>
<tr>
<td> <input type="checkbox" id="chk113" name="CV_ID" value="<?php echo $row->CV_ID ?> "/>
<label for="chk113"><?php echo $row->CV_ID ?> </label> </td>
<td> <input type="checkbox" id="chk111" name="Classifier" value="<?php echo $row->Classifier ?>"/>
<label for="chk111"><?php echo $row->Classifier ?></label> </td>
<td> <input type="checkbox" id="chk112" name="Value" value="<?php echo $row->Value ?>"/>
<label for="chk112"><?php echo $row->Value ?></label> </td>
</tr>
<?php endforeach ?>
</table>
<p><input id="submit" name="submit" type="submit" value="Submit Names" /></p>
</form>
Saving
?>
<?
if( (isset($_POST['CV_ID'])) || (isset($_POST['Classifier'])) || (isset($_POST['Value'])) ) {
//first name or last name set, continue-->
$CV_ID = $_POST['CV_ID'];
$Classifier= $_POST['Classifier'];
$Value= $_POST['Value'];
$db =& JFactory::getDBO();
$query = "INSERT INTO SessionTa (CV_ID, Classifier, Value) VALUES ('".$CV_ID."','".$Classifier."','".$Value."');";
$db->setQuery( $query );
$db->query();
} else {
}
?>

each checkbox in your form appears to have the same name. Trying naming them as an array, e.g.
<input type="checkbox" id="chk113" name="CV_ID[]" value="<?php echo $row->CV_ID ?> "/>
Notice the extra '[]'. At that point, you can print_r($_POST) in your saving php file to see the differences. Your db update logic might need to be tweaked as a result

Related

PHP inputbox to database

I am trying to teach myself PHP. I want to know how to interact with a database and insert data from a website and to display the data back into a table on the webpage.
I am trying to let the user edit the results or have them shown in an input box. This way, the user can edit the data and send it back to the database. But, I am stuck. I have tried different ways and none of them seem to work. I'm opened to suggestions.
The bookingid is what the user picks.
I know all table names are not that good but I am learning.
$query = "SELECT * FROM Trip_Booked Where bookingId = $bookingid";
//executes the query
$result = mysqli_query($db,$query);
// create table and display top row
echo "<td>".$row['email']."</td>";
echo "<div align='center'>";
echo "<table cellpadding=2 border=1>";
echo "<tr>";
echo "<td><strong>booking ID</strong></td>";
echo "<td><strong>boatdate</strong></td>";
echo "<td><strong>fromdate</strong></td>";
echo "<td><strong>saleto</strong></td>";
echo "<td><strong>salefrom</strong></td>";
echo "<td><strong>NoOfAdults</strong></td>";
echo "<td><strong>NoOfWheelchair</strong></td>";
echo "<td><strong>NoUnder2</strong></td>";
echo "<td><strong>NoChild3–10</strong></td>";
echo "<td><strong>NoChild11–16</strong></td>";
echo "<td><strong>TotalPassgers</strong></td>";
echo "</tr>";
// print each record one after another
while($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<td>".$row['bookingId']."</td>";
echo "<td>".$row['boatDate']."</td>";
echo "<td>".$row['fromDate']."</td>";
echo "<td>".$row['saleto']."</td>";
echo "<td>".$row['salefrom']."</td>";
echo "<td>".$row['NoOfAdults']."</td>";
echo "<td>".$row['NoOfWheelchair']."</td>";
echo "<td>".$row['NoUnder2']."</td>";
echo "<td>".$row['NoChild3–10']."</td>";
echo "<td>".$row['NoChild11–16']."</td>";
echo "<td>".$row['TotalPassgers']."</td>";
echo "</tr>";
}
echo "</table>";
echo "</div>";
?>
I would like the result be shown in an input box for the user to edit as it will go in a table and check it is pulling the right information from the database.
A very simplified example; double check mysqli usage because I don't use mysqli...
Things to take note of:
Use prepared statements. period.
A common practice is to do all your script stuff, then output HTML. Don't mix logic with presentation.
Pay attention to whether a variable is GET or POST. The reason I used both GET and POST is because I use GET to display a specific record; but POST is used for anything that changes a record.
I use camelCase for variables but lowercase for #id. Just be aware of it, that can be confusing if you're not aware.
I first check if this is a request to update the record. If it is, do the update, then redirect back to the same page in order to prevent resubmissions. (This is only possible if no output has been sent. See point 2)
Using the <?= ?> format is personal preference; I like it because it keeps the HTML code cleaner and makes the PHP as unobtrusive as possible.
Using <form method='{GET | POST}'> with no action simply sends back to the same URL.
// Create connection
$db = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
// first, take action on POST results if this is an update
if($_POST['action']=='update') {
// use prepared query to avoid SQL injection
$query = "UPDATE Trip_Booked SET boatDate=?, fromDate=?, saleto=?, salefrom=?, NoOfAdults=?, NoOfWheelchair=?, NoUnder2=?, NoChild3_10=?, NoChild11_16=?, TotalPassgers=? WHERE bookingId=?";
$result = $db->prepare($query);
$result->bind_param("ssssiiiiiii", $_POST['boatDate'],$_POST_['fromDate'],$_POST_['saleto'],$_POST_['salefrom'],$_POST_['NoOfAdults'],$_POST_['NoOfWheelchair'],$_POST_['NoUnder2'],$_POST_['NoChild3_10'],$_POST_['NoChild11_16'],$_POST_['TotalPassgers'],$_POST['bookingId']);
$result->execute();
// since we don't want post data resent on back button press, redirect back to this page (change url to match)
header("Location: http://www.example.com/?bookingId=" . $POST['bookingId']);
exit;
}
// if not an update, but we do have the booking ID, find the row using BookingId
// use prepared query to avoid SQL injection
if($_GET['bookingId']) {
$query = "SELECT * FROM Trip_Booked Where bookingId = ?";
$result = $db->prepare($query);
$result->bind_param("s", $_GET['bookingId']);
$result->execute();
}
Now, we have everything we need to output the HTML. Remember, PHP is a templating language, so don't be afraid to use it as such.
<!-- language: lang-html -->
// continuing from above
?><html>
<head>
<title>Edit a Booking</title>
</head>
<body>
<h1>Choose a Page</h1>
<form method="get">
<label for="bookingid">Page</label><input type="text" id="bookingid" name="bookingId" />
<input type="submit" value="Go to page" />
</form>
<?php if($_GET['bookingId']): ?>
<!-- better way to enter values: -->
<!-- <div><label for="fieldname">Label</label><input type="text" id="fieldname" name="fieldname" value="{value}" /></div> -->
<h1>Edit Fields</h1>
<form method="post">
<input type="hidden" name="action" value="update" />
<input type="hidden" name="bookingId" value="<?= htmlentities($_GET['bookingId']) ?>" />
<table>
<thead>
<tr>
<th>bookingId</th>
<th>boatDate</th>
<th>fromDate</th>
<th>saleto</th>
<th>salefrom</th>
<th>NoOfAdults</th>
<th>NoOfWheelchair</th>
<th>NoUnder2</th>
<th>NoChild3_10</th>
<th>NoChild11_16</th>
<th>TotalPassgers</th>
</tr>
</thead>
<tbody>
<!-- since this is an edit of only one record, you could use 'if' instead of 'while' -->
<?php while($row = $result->fetch_object())): ?>
<tr>
<th><input type="text" name="bookingId" value="<?= $row->bookingId ?>" /></th>
<th><input type="text" name="boatDate" value="<?= $row->boatDate ?>" /></th>
<th><input type="text" name="fromDate" value="<?= $row->fromDate ?>" /></th>
<th><input type="text" name="saleto" value="<?= $row->saleto ?>" /></th>
<th><input type="text" name="salefrom" value="<?= $row->salefrom ?>" /></th>
<th><input type="text" name="NoOfAdults" value="<?= $row->NoOfAdults ?>" /></th>
<th><input type="text" name="NoOfWheelchair" value="<?= $row->NoOfWheelchair ?>" /></th>
<th><input type="text" name="NoUnder2" value="<?= $row->NoUnder2 ?>" /></th>
<th><input type="text" name="NoChild3_10" value="<?= $row->NoChild3_10 ?>" /></th>
<th><input type="text" name="NoChild11_16" value="<?= $row->NoChild11_16 ?>" /></th>
<th><input type="text" name="TotalPassgers" value="<?= $row->TotalPassgers ?>" /></th>
</tr>
<?php endwhile; ?>
</tbody>
</table>
<input type="submit" value="Edit" />
</form>
<?php endif; ?>
</body>
</html>
You need to output the data into the input fields you want. Small example:
<input type="hidden" name="bookingId" value="<?php echo $row["bookingId"];?>" />
<input type="text" name="NoOfAdults" value="<?php echo $row["NoOfAdults"];?>" />
Using a form action of POST you can then run the UPDATE query using the $_POST['NoOfAdults'] and using the $_POST['bookingId'] as the WHERE

Submitting a specific row of a form which is generated by a loop

This is the code for the admin panel of a certain site. Appointments asked by customers will be shown in this page. The admin will be able to change the appointments based on availability.
<?php
while($row = mysqli_fetch_assoc($result)){
?>
<form action="adminEdit.php" method="POST">
<tr>
<td><input type="text" id="name" value="<?php echo $row['Name'];?>"></input></td>
<td><input type="text" id="address" value="<?php echo $row['Address'];?>"></input></td>
<td><input type="text" id="phone" value="<?php echo $row['Phone'];?>"></input></td>
<td><input type="text" id="license" value="<?php echo $row['Car_License_No'];?>"></input></td>
<td><input type="text" id="engine" value="<?php echo $row['Car_Engine_No'];?>"></input></td>
<td><input type="text" id="date" value="<?php echo $row['Date'];?>"></input></td>
<td><input type="text" id="mechanic" value="<?php echo $row['Mechanic'];?>"></input></td>
<td><input type="submit" name="submit" value="Change"/></td>
</tr>
</form>
<?php
}
?>
Here, each row of data has a corresponding button which will be used for changing or modifying the records of that particular row. Once the admin changes a specific appointment it should get updated in database.
My problem is, all the rows are getting generated by a while loop. Now how can I access a specific row when the change button of that specific row has been clicked ? As the rows are getting generated by a loop, I wont be able to access them bynameoridbecause all of them will have the samenameandid`.
Searched for relevant questions but none of them matched with my scenario. It will be of great help getting an answer. Thanks in advance.
Personally I'd be inclined to take the output from being in the loop for better control over the data and resolving the issue. You're also creating a new form on each loop.
Just loop the DB and create a new variable, then use that variable to output the data in the form.
Example code to show the basic idea, not tested or stating it's complete etc:
while ($row = mysqli_fetch_assoc($result)) {
$someNewVar[$row['id']] = $row;
// The 'id' index would be from DB which identifies individual rows
}
?>
<form action="adminEdit.php" method="POST">
<?php
foreach ($someNewVar as $index => $value) {
?>
<tr>
<td>
<input
type="text"
id="<?php echo $index;?>"
value="<?php echo $value['Name'];?>">
</input>
</td>
<td>
<input
type="submit"
name="submit"
value="Change"/>
</td>
</tr>
<?php
}
?>
</form>
Then you'd need to have the row ID passed from clicking the submit button.
On a side note, this whole approach could be tidied up, and data should be obtained in one file separate to where you output it.
Then in the file which obtains the data you can set the array to something which is also identified in the output file to manage if no data was obtained.
ie
getData.php
while ($row = mysqli_fetch_assoc($result)) {
$dataFromDb[$row['id']] = $row;
}
$someNewVar = !empty($dataFromDb) ? $dataFromDb : false;
showData.php
if ($someNewVar) {
// do the loop and form
} else {
echo 'sorry no data found';
}

PHP handling combined checkboxes and select boxes

I'm working on a form that uploads an image to a server. The form contains checkboxes and select boxes formatted to a <table>. Each table row contains two columns. The First column iterates through a mysql query that displays a list of items (24 items to be exact) that is paired to a checkbox. The 2nd column iterates through a mysql query that displays list of clients.
What needs to be done are as follows:
When the form gets uploaded (via POST or GET) the checkboxes which only have check gets passed.
convert the subs_id (name parameter for the select box) to an array for easy processing for mysql insert.
Code Below. Thanks in advanced!
<form method="post" enctype="multipart/form-data" action="upload2.php">
Name: <input type="text" name="item_desc" value="">
Show Date: <input type="text" name="upload_date" class="date" size="10"> to <input type="text" name="expiry_date" class="date" size="10">
Item: <input type="file" name="item"> Display Length: <input type="number" value="8" name="show_time" size="3" style="width:50px"> secs
<table class="data-list" width="100%">
<tr>
<td>Widget</td>
<td>Client</td>
</tr>
<?php foreach($instance as $item):?>
<tr>
<td><input type="checkbox" id="checkAll"/> <?php echo $item['name']; ?></td>
<td><select id="selectBox" name="subs_id[]">
<option selected="selected" value="none">Select Client</option>
<?php foreach($subs as $client): ?>
<option value="<?php echo $item['id'] . '-' . $client['id']; ?>" client="<?php echo $client['client_name']; ?>" ><?php echo $client['client_name']; ?></option>
<?php endforeach ?>
</select>
</td>
</tr>
<?php endforeach; ?>
</table>
<br>
<input type="submit" value="upload">
</form>
<input type="checkbox" id="checkAll" name='client[]' value ="1" /> <?php echo $item['name']; ?>
name and value is missing
1 .Change your checkbox code to
<input type="checkbox" id="checkAll" name="checkId[]" value="<?php echo $item['name']; ?>"/> <?php echo $item['name']; ?>
Here, I am taking name as array checkId[] and value of checkbox value="<?php echo $item['name']; ?>"
This should work for you.
Your select box is fine. There is no need to change it. you can find value of select box by checking index.
I figured it out. What I did was detect when there was a change on the select box and assign the value of the select box to the check box's value.
$(".selectBox").change(function() {
$(this).parent().siblings().children('input').attr('value',$(this).val());
});
then, on the upload2.php, I used the code below to get the value of only the boxes with check
if(!empty($_POST['checkId'])) {
$filename = $this->unique_filename($this->extract_ext( $_FILES["item"]["name"]));
$folder = dirname(__FILE__) . '/items';
move_uploaded_file($_FILES['item']['tmp_name'],"{$folder}/{$filename}");
foreach($_POST['checkId'] as $check) {
//save to db
$split = explode("-",$check);
$subs_id = $this->use_table('clients')->where('client_name like "' . $split[2] . '%"')->where('site_id=' . $split[1])->fetch();
//$subs_id = $this->query('select * from clients where client_name like "Trinoma%" and site_id=1');
//print_r($subs_id[0][id]);
$data = array(
'item_name'=> 'widgets/' . strtolower(get_class($this)) . '/items/' . $filename,
'show_time'=> $_POST['show_time'],
'instance_id'=> $split[0],
'item_desc'=>$_POST['item_desc'],
'subs_id'=> $subs_id[0][id]
);
$this->use_table(TBL_NAME)->insert($data)->execute();
$mid = $this->last_insert_id();
$this->use_table(TBL_SCHED)->insert(array(
'multirotator_id'=>$mid,
'show_from'=>'00:00',
'show_to'=>'23:59',
'upload_date'=>$_POST['upload_date'],
'expiry_date'=>$_POST['expiry_date']
))->execute();
} //end of foreach
} //end of if(!empty($_POST['checkId']))
and voila! working code for me.

Trying to update dates in database with dynamically created forms

So i've created an administration page that creates X-number of forms based on how many users we have in our database, each of which have a submit button next to them to submit changes to the dates we have in our DBs. My problem is that when I want to get the value of what gets posted I can't extract exactly what I need from what gets posted. It gets saved into an array called and when I print_r the array I get exactly what I want, which is:
[1] => "whatever date they typed in"
(obviously the 1 changes depending on which item they changed the date of)
I need be able to query my datebase by:
UPDATE users SET subdate="whatever they typed in" WHERE id="the array reference number"
I know exactly what I need to do, I'm just not as familiar with SQL as i'd like to be, so any help would be greatly appreciated. Thanks in advance.
Code for reference:
<div class="form-section grid12" id="changedates">
<h1>Change Dates</h1>
<?php
$query = mysql_query("SELECT * FROM users WHERE admin='y'");
?>
<table>
<?php
while($row = mysql_fetch_assoc($query)) {
?>
<tr>
<td>
<h5><?php echo $row['displayname'];?></h5>
</td>
<td>
<form action="" method="POST">
<input type="text" name="subdate[<? echo $row['id'] ?>]" value="<?php echo $row['submissiondate'];?>">
<input type="text" name="nextupdate[<? echo $row['id'] ?>]" value="<?php echo $row['nextupdate'];?>">
</td>
<td>
<input type="submit" value="Set Date" name="setdate">
</form>
</td>
<?php
}
?>
</table>
</div>
You could use foreach...
foreach ($_POST[nextupdate] as $rowId => $time)
{
// do db update
}
Edit: Just realised you have more than one input per form.
Why not name each input with an array name:
<input type="text" name="form_data[<?= $row_id ?>][subdate]">
<input type="text" name="form_data[<?= $row_id ?>][nextupdate]">
In PHP:
foreach ($_POST[form_data] as $rowId => $values)
{
$subdate = $values[subdate];
$nextupdate = $values[nextupdate];
// do SQL stuff
}

PHP - How to submit a form containing input fields that point to different MySQL rows

I am setting up a form using this PHP that loops through all records a user may have:
<?php foreach ($items as $row): ?>
<tr>
<td>
<?php echo form_hidden('id', $row->id); ?>
</td>
<td>
<?php echo '<strong>' . $row->name . '</strong>'; ?>
</td>
<td>
<?php echo form_input('number', $number); ?>
</td>
<td>
<?php echo form_input('registry', $registry); ?>
</td>
<td>
<?php echo form_checkbox('OK', $ok, $ok); ?>
</td>
</tr>
<?php endforeach; ?>
This gives me a form with the following look:
The idea here is that each row belongs to a unique ID/row in the database, and I would like to allow the user to edit all on the same page/form, using a single submit button.
What would be the best way of implementing this?
When this data is submitted, there should be a way of looping through each packet of information (from each user) in my controller. Would this be done via ajax/json?
This does not use codeigntier, but you should be familiar with the general technique before attempting to use CI to shortcut this process. Codeigniter will help you with rendering the form elements, performing validation, escaping your input and performing your query - but it will only help you (do anything) if you understand the basic principles involved. Hope this helps
MARKUP
<form action="/process.php">
<div>
<h2>GORDON</h2>
<input type="text" name="user[1][number]" /> <!-- The number corresponds to the row id -->
<input type="text" name="user[1][registry]" />
<input type="checkbox" name="user[1][ok]" value="1" />
</div>
<div>
<h2>ANDY</h2>
<input type="text" name="user[242][number]" />
<input type="text" name="user[242][registry]" />
<input type="checkbox" name="user[242][ok]" value="1" />
</div>
<div>
<h2>STEWART</h2>
<input type="text" name="user[11][number]" />
<input type="text" name="user[11][registry]" />
<input type="checkbox" name="user[11][ok]" value="1" />
</div>
<input type="submit" />
PHP
$users = $_REQUEST['user'];
foreach ($users as $rowId => $info){
// YOU SHOULD MAKE SURE TO CLEAN YOUR INPUT - THIS IS A GUESS AT WHAT YOUR DATA TYPES MIGHT BE
$id = (int) $rowId;
$number = (int) $info['number'];
$registry = mysql_real_escape_string($info['registry']);
$ok = (int) ($info['ok']);
$q = "UPDATE user SET number = $number, registry = '$registry', ok = $ok WHERE id = $id";
mysql_query($q);
// You may want to check that the above query was sucessful and log any errors etc.
}
There's no need to use ajax mate.
For each put a hidden input with the ID of the row in this format:
<input type="hidden" name="id[<?= $row->id ?>]" value="<?= $row->id ?>" ?>
Do the same for each element in the tr, i.e. name them as
name="number[<?= $row->$id ?>]"
name="registry[<?=$row->$id ?>]"
name="ok[<?=$row->$id ?>]"
and once you post the FORM you can iterate each row with:
foreach ($_POST['id'] as $key => $value) {
echo $_POST['name'][$key];
}
You need to set up input-names as array-names, so you will send the whole form and may iterate over the entries.
e.g.
<?php
echo form_input('userdata[' . $row->id . '][number]', $number);
?>
which would possibly create an
<input name="userdata[1][number]" />
(I don't know where those form-functions came from…)
This will result in an array $_POST['userdata'] which may be iterated via:
foreach($_POST['userdata'] as $userId => $userInputFields)
{
$user = new User($userId);
$user->number = $userInputFields['number'];
// …
}

Categories