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
Related
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';
}
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
I have this code to show my table:
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST">
<table cellspacing='0'>
<?php
if(isset($_GET["ordem"])){
if($_GET["ordem"] == 'descendente'){
echo "<thead><tr><th><a title='Ordenar por título' href='visualizarVoucher.php'>Utilizador</a></th>";
echo "<th>Email</th>";
echo "<th>Voucher</th>";
echo "<th>Categoria</th>";
echo "<th>Preço</th>";
echo "<th>Confirmação</th>";
echo "<th>Enviar mail</th>";
echo "</tr></thead>";
}
elseif($_GET["ordem"] == 'ascendente'){
echo "<thead><tr><th><a title='Ordenar por título' href='visualizarVoucher.php?ordem=descendente'>Utilizador</a></th>";
echo "<th>Email</th>";
echo "<th>Voucher</th>";
echo "<th>Categoria</th>";
echo "<th>Preço</th>";
echo "<th>Confirmação </th>";
echo "<th>Enviar mail</th>";
echo ("</tr></thead>");
}
}
else{
echo "<thead><tr><th><a title='Ordenar por título' href='visualizarVoucher.php?ordem=ascendente'>Utilizador</a></th>";
echo "<th>Email</th>";
echo "<th>Voucher</th>";
echo "<th>Categoria</th>";
echo "<th>Preço</th>";
echo "<th>Confirmação</th>";
echo "<th>Enviar mail</th>";
echo("</tr></thead>");
}
while($stmt->fetch()){
echo("<tbody>");
echo("<tr><td>$nomeUser</td>");
echo("<td>$email</td>");
echo("<td>$nomeVoucher</td>");
echo("<td>$categoria</td>");
echo("<td>$preco</td>");
echo("<td>$confirmacao</td>");
$content = file_get_contents($file,$filePDF);
echo("<td><INPUT TYPE='checkbox' NAME='mail[]' multiple='yes'></td>");
echo("</tr>");
echo("</tbody>");
}$stmt->close(); ?>
I have a checkbox in my table and I would like to know how can I get the values of each rows from the table when i selected the checkbox. I want to send email when the user selected multiple checkbox.
Thanks
It's possible that the code above is a snippet of a larger page, but if not:
You aren't actually wrapping your input elements in an HTML form tag. Doing so will cause the user agent (presumably a browser) to treat each input tag as something to be submitted to your backend form.
You should wrap the tables in a table element; tbody is a child of a table.
Regardless of the above:
It looks like your PHP code above will render the entire tbody each time the statement fetches a new row, which is a bit weird. I'd assume you only want to render a row containing mail options?
To the best of my knowledge, there is no multiple attribute allowed in a checkbox element. You may be thinking of the select element.
You are not setting a value attribute on your checkbox input tag. If the user actually submits a form, you'll either get a set of empty mail[] variables, or nothing at all, I'm not actually sure which.
Consider the code below: Note that the checkboxes have the same name attribute, but different values.
<form method="post">
<table>
<tbody>
<tr>
<td>
<input type="checkbox" name="mail[]" value="val1" id="mail-val1" />
<label for="mail-val1">Value 1</label>
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="mail[]" value="val2" id="mail-val2" />
<label for="mail-val2">Value 2</label>
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="mail[]" value="val3" id="mail-val3" />
<label for="mail-val3">Value 3</label>
</td>
</tr>
</tbody>
</table>
<input type="submit" />
</form>
Given this form, if the user selects all three of the checkboxes and submits, your server will receive a POST request with the payload:
mail[]=val1&mail[]=val2&mail[]=val3
Depending on how PHP parses that response (it's been about a decade since I've dealt with PHP), you'll probably have an array variable accessible to your application:
# mail == ["val1", "val2", "val3" ]
Hope this helps.
I have an html table I've updated to use checkboxes to be able to delete multiple files:
<table>
<thead>
<tr>
<th>Camera Name</th>
<th>Date Created</th>
<th>Video Size</th>
<th>Video Length</th>
<th>
<button type="submit" class="deletebutton" name="delete_video" value="Delete" title="Delete the selected videos" onClick="return confirm('Are you sure you want to delete?')">Delete</button><br>
<input type="checkbox" name="radioselectall" title="Select All" />
</th>
</tr>
</thead>
<tbody>
<?php
for($i=0;$i<$num_videos;$i++)
{
//do stuff
//Note: I'm looping here to build the table from the server
?>
<tr >
<td onclick="DoNav('<?php echo $url; ?>');">
<?php echo $result_videos[$i]["camera_name"]; ?>
</td>
<td onclick="DoNav('<?php echo $url; ?>');">
<?php echo setlocalTime($result_videos[$i]["video_datetime"]); ?>
</td>
<td onclick="DoNav('<?php echo $url; ?>');">
<?php echo ByteSize($result_videos[$i]["video_size"]); ?>
</td>
<td onclick="DoNav('<?php echo $url; ?>');">
<?php echo strTime($result_videos[$i]["video_length"]); ?>
</td>
<td>
<form name="myform" action="<?php echo htmlentities($_SERVER['REQUEST_URI']); ?>" method="POST">
<input type="checkbox" name="radioselect" title="Mark this video for deletion"/>
<input type="hidden" name="video_name" value="<?php echo $result_videos[$i]["video_name"]; ?>" />
</form>
</td>
</tr>
I started with first creating some jquery code to create a select all/deselect all button in the table heading and just a test to show I can find which boxes are checked. That all works:
//selectall checkboxes - select all or deselect all if top checkbox is marked in table header
$("input[name='radioselectall']").change(function()
{
if( $(this).is(':checked') )
{
$("input[type='checkbox']","td").attr('checked',true);
}
else
{
$("input[type='checkbox']","td").attr('checked',false);
}
});
//process checkboxes - which ones are on
$(".deletebutton").click(function() {
$("input[name='radioselect']:checked").each(function(i){
alert(this.value);
});
});
So the part where I'm stuck is I don't know where to go from here. I need to pass all the video_names of all the videos selected (with the checkboxes). video_name is part of a hidden field in my form. So I need to pass that to my php function when the delete button is selected. Not really sure how to tackle this. Hope this makes sense.
Simple solution maybe:
Change your checkboxes to have a value of 1 and a name of $result_videos[$i]["video_name"]; in the table rows, make the form encapsulate the whole table.
Then on submit you can do something like:
foreach ($_POST as $key => $value) {
//Delete $key (the name) where $value == 1
}
Your approach is fine if you want to access the hidden fields through jQuery at a given point but once you submit the form and lose the DOM, the PHP processing page will have no way to relate the selected checkboxes with the hidden fields as there is no consistent naming scheme.
One approach would be to use the loop counter to suffix the two in order to pair them up:
<input type="checkbox" id="radioselect_<?= $i ?>" title="Mark this video for deletion" value="1" />
<input type="hidden" id="video_name_<?= $i ?>" value="<?php echo $result_videos[$i]["video_name"]; ?>" />
This would be good if you want to relate more than the two fields. Otherwise, you could just use the video_name as the value of the checkbox, as Ing suggested.
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'];
// …
}