I have an array that is created from a mysqli query.
The array then goes through a for loop to display a table.
Within the table there is a form submit that needs to take the selected row and pass the information into a variable to be modified.
I tried to take a screenshot, but I just joined and have no rep. In theory, the user needs to be able to select Modify and the array elements for that row need to pass into text input boxes with a preset value of $row[$j][0] where $j is fixed based on the row selected to modify.
Here is what this part of the code looks like.
if (isset($_POST['Select']) &&
isset($_POST['Search']))
{
$Select = get_post($con,'Select');
$Search = get_post($con,'Search');
if ($Select == "Invalid")
{
echo "<br /><br />Please select a search catagory";
}
else if ($Search == NULL)
echo "<br /><br />Please enter search field";
else
{
$query = "SELECT * FROM table WHERE $Select LIKE '$Search%'";
$result = mysqli_query($con,$query);
if (!mysqli_query($con,$query)) {
die('Error: ' . mysqli_error($con));
}
$rows = mysqli_num_rows($result);
echo "<table id='myTable' class='tablesorter'>
<thead><tr>
<th>Modify</th>
<th>Field1</th>
<th>Field2</th>
<th>etc...</th>
</tr></thead><tbody>";
for ($j = 0 ; $j < $rows ; ++$j)
{
$row = mysqli_fetch_row($result);
$modrow[$j] = $row;
echo <<<_END
<tr>
<td><form action="Lookup.php" method="post"><input type="submit" value="Modify" /><input type="hidden" name="submitted" value="$modrow[$j]"</form></td>
<td>$row[0]</td>
<td>$row[1]</td>
<td>etc...</td>
</tr><br />
_END;
}
echo "</tbody></table>";
if (isset($_POST['submitted']))
{
echo <<<_END
<form action="Lookup.php" method="post"><pre>
Field1 <input type="text" name="Field1" size="50" **value="$modrow[$j][0]"** />
...more of the same...
From what I gather, you're wanting to pass a request to the server containing some form of identifier for the row so that you may create a form for users to modify that row's data. Sorry if I misunderstood - I would ask first if I understood you correctly as a comment, but don't have enough rep.
You can use an id to submit to the server.
<button type="submit" name="modify" value="<?= $theRowsId ?>">Modify</button>
Think of the values of name and value attributes as a function/method and value being passed respectively.
Now when Modify is clicked, you can get retrieve the ID, perform a query for the ID and populate the input with the rows data.
$rowId = $_POST['modify'];
Related
I have done a form which retrieves data from the database. This form allows you to display the list of students from the database but the problem is I cannot correctly input their scores individually. It does allow to insert scores but unfortunately, it only accepts the last score from the last student and inputs the same score to all students.
These are my codes:
FORM code
if ($result->num_rows > 0) { // output data of each row
while($row = $result->fetch_assoc()) {
if($row['status']=='p'){
<form name="result" method="post">
<?php { //this form will display the set of students
echo $row['lastname'] . ', ' . $row['firstname'];
echo '<input type="hidden" name="selected[]" value="'.$row['reviewee_idnumber'].'"/>'; ?>
<input type="text" name="score" required="required" size="20" placeholder="Score"/><br><br>
<?php echo '</br>';
}
} //if statement
} //while statement
?>
<input type="submit" name="submit" value="Submit"/>
<input type="hidden" name="code" value="<?php echo $code;?>"/>
<input type="hidden" name="subject" value="<?php echo $subject;?>"/>
<input type="hidden" name="items" value="<?php echo $items;?>"/>
<input type="hidden" name="date" value="<?php echo $date;?>"/>
</form>
This is where I insert my code into the database
if(isset($_POST['submit'])){
$code = $_POST['code'];
$subject = $_POST['subject'];
$items = $_POST['items'];
$date = $_POST['date'];
$score = $_POST['score']; //get score
$update = mysql_query("INSERT INTO exam (exam_code, subject, date, total_item)
VALUE ('$code','$subject', '$date', '$items')");
if(!empty($_POST['selected'])) {
$checked_count = count($_POST['selected']);// Counting number of checked checkboxes.
//echo "You have selected following ".$checked_count." option(s): <br/>";
foreach($_POST['selected'] as $selected){ // Loop to store and display values of individual inputs.
$updatedata="INSERT INTO result (score, exam_code, reviewee_idnumber)
VALUE ('$score', '$code', '$selected')";
if(#mysql_query($updatedata,$dbc)){
print '<p> successful!</p>';
}else{
print '<p> failed. '.mysql_error().'</p>';
}
It should display list students (which is fine) and right beside their name is a blank space that will accept their score (which doesn't work).
Because <form name="result" method="post"> is inside the while loop, you actually have multiple forms in your page. The submit button acts only on the last form, that's why only the last student's score gets updated.
Also, because there are multiple input elements with the same name, only a single value is sent in the POST request. A solution for this would be to include the student's ID in the name:
name="score'.$row['reviewee_idnumber'].'"
You need to update the form processing logic accordingly.
name =<?php echo "'score.$row['reviewee_idnumber']'" ?>
This is what the page looks like:
And this is what the database looks like:
Now, I had this all working with textfields. (When you press save, the text fields get inserted in the bogie_nr.
Now, I don't want to have text fields but checkboxes.
So, if I select the first 2 checkboxes, and press save. I want the database to insert the number 1 by the axle_nr 1 and 2.
Now, I want the first 2 boxes to be disabled (So you can't check them again).
Now when you select the 3rd and 4th box, and press save. I want the database to insert the number 2 by the 3rd and 4th axle_nr.
When everything is filled in, I want a button that redirects me to a new page.
How do I do this?
Code (for the checkboxes only):
<tr>
<?php
$show_axle = $database->bogies($_GET['train_id']);
foreach($show_axle as $bogiebox){ ?>
<input type='hidden' name='bogie_id[<?php echo $bogiebox['bogie_id']?>]' value='<?php echo $bogiebox['bogie_id']?>'>
<td>
<input type='checkbox' id="bogie_axle_fields" name='bogie_nr[<?php echo $bogiebox['bogie_id']?>]' placeholder = "enter bogie number">
</td>
<?php
}
?>
</tr>
Function:
function bogies($id){
$sql = "SELECT * FROM bogie WHERE train_id = :id2";
$sth = $this->pdo->prepare($sql);
$sth->bindParam(":id2", $id, PDO::PARAM_STR);
$sth->execute();
return $sth->fetchAll();
}
EDIT:
Behind my save button is right now a page: end_result.php . Right there I have a function:
function update_bogie($id) {
$sql = "UPDATE bogie SET bogie_nr = :bogie_nr WHERE bogie_id = :bogie_id";
$sth = $this->pdo->prepare($sql);
$sth->bindParam(':bogie_id', $id, PDO::PARAM_INT);
$sth->bindParam(":bogie_nr", $_POST['bogie_nr'][$id], PDO::PARAM_STR);
$sth->execute();
}
This updates the bogie table (Works when I change the checkboxes to textfields)
What i want now:
Checkboxes. When I check the first 2 boxes, and press save. I want the number 1 to be inserted 2 times for axle 1 and 2 in the database.
After that, I want the first 2 boxes to be disabled selected. So you can't select them once again.
EDIT:
What the ids look like:
THE ALMOST WORKING EDIT:
Okay, so the checkboxes now insert in the database. Also they are disabled when they are inserted in the database.Only a few problems now:
When i insert them for the first time. The value = 1. But on the
2nd insert it also is 1. while it should be 2.
I need to refresh the page in order to see wich select boxes are
disabled. I want this to happen immediately.
When i insert new values. the old (Disabled one) go back to NULL. But it should keep the old value.
Code i have now:
<form method='POST'>
<input type="hidden" value="true" id="y" name="y">
<div id="axle_bogie_border">
<div id="train_adjusted">
<h2>
Train
</h2>
</div>
<table id="distance_margin">
<div id="bogiebox">
<tr>
<?php
$x = 1;
foreach($show_axle as $bogiebox){ ?>
<input type='hidden' name='bogie_id[<?php echo $bogiebox['bogie_id']?>]' value='<?php echo $bogiebox['bogie_id']?>'>
<td>
<?php
if($bogiebox['bogie_nr'] == ''){
?>
<input type='checkbox' id="bogie_axle_fields" value="<?= $x ?>" name='bogie_nr[<?php echo $bogiebox['bogie_id']?>]' placeholder = "enter bogie number"></td>
<?php
}
else{
?>
<input type='checkbox' id="bogie_axle_fields" checked disabled value="<?= $x ?>" name='bogie_nr[<?php echo $bogiebox['bogie_id']?>]' placeholder = "enter bogie number"></td><?php } }
?>
</tr>
</div>
</table>
<input type='submit' id="add_train_button1" value='Save'>
<?php
if(isset($_POST['y'])){
$validbogies = false;
//validate
if(($_POST['bogie_id']) >0){
if($_POST['bogie_id'] >0){
$validbogies = true;
}elseif($_POST['bogie_id'] <= 0){
echo "Error!";
}
else{
echo "Error!." . "<br>";
}
}else{
echo "Error!" . "<br>";
}
//If valid, then insert.
if($validbogies){
foreach($_POST['bogie_id'] as $id) {
$update_axle = $database->update_bogie($id);
}
$x++;
unset($_POST['y']);
echo "Yea! Things have been moved to the database :)";
}
}
?>
</div>
</form>
And the function is still the same as the old one.
EDIT:
Here a example:
<?php
$show_axle = $database->bogies($_GET['train_id']);
// First question : When everything is filled in,
// i want a button that redirects me to a new page.
if(count($show_axle) == 4)
echo "<button type=\"button\" onClick=location.href=''>Click Me!</button>";
// Second question :
// WE display the missing checkboxes
// We will display until we found the first value axle_nr
// (i.e. the checkbox the user click last time)
// when we found we need to move to the next value of axle_nr
else
{
$j = 0;
for($i = 0; $i < 4; ++$i)
{
if($show_axle[$j]['axle_nr'] != ($i + 1))
{
echo "<input type='hidden' name='bogie_id[" .
$bogiebox['bogie_id']. "]' value='" .
$bogiebox['bogie_id'] . "'><td>";
echo "<input type='checkbox' id='bogie_axle_fields'
name='bogie_nr[" . $bogiebox['bogie_id'] .
"]' placeholder='enter bogie number'></td>";
}
else
++$j;
}
?>
That should do it (mb some mistakes on echo but algorithm is ok).
In the code behind your save button try this: (I am assuming the id's for your checkboxes are like this: bogie_nr[455]
function update_bogie($id) {
$sql = "UPDATE bogie SET bogie_nr = :bogie_nr WHERE bogie_id = :bogie_id";
$sth = $this->pdo->prepare($sql);
$sth->bindParam(':bogie_id', $id, PDO::PARAM_INT);
if(isset($_POST['bogie_nr' . '[' . $id .']' ]){
$sth->bindParam(":bogie_nr", $_POST['bogie_nr' . '[' . $id .']' ], PDO::PARAM_STR);
}
else {
$sth->bindParam(":bogie_nr", 'NULL', PDO::PARAM_STR);
}
$sth->execute();
}
EDIT FOR CORRECT NUMBER:
Mitch to get your number try doing a query like this:
SELECT COUNT(*)
FROM bogie
WHERE train_id = #youridhere;
This will return you the amount of bogies you already have for that train, just do +1 or +2 depending on how many elements you are adding (use a counter in your for loop) and you have your correct number to insert
I have this code so far, which reads a simple table with 3 varchar fields:
<?php
//db connection code...
// select database
mysql_select_db($db) or die ("Unable to select database!");
// create query
$query = "SELECT * FROM Sheet1";
// execute query
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
// see if any rows were returned
if (mysql_num_rows($result) > 0) {
// yes
// see if any rows were returned
if (mysql_num_rows($result) > 0) {
// yes
// print them one after another
echo "<html><body><table cellpadding=10 border=1>";
while($row = mysql_fetch_assoc($result)) {
echo "<tr>";
echo "<td>".$row['stickerID']."</td>";
echo "<td>" .$row['stickerName']."</td>";
echo "<td>".$row['stickerSection']."</td>";
echo "<td>"?>
<form name="some form" action="editform.php" method="post">
<input type="checkbox" name="<?php echo $row['stickerID'] ?>" value=" <?php echo $row['stickerStatus'] ?> ">
<?php "</td>";
echo "</tr>";
}
echo "</table></body></html>";
echo " " ?>
<input type="submit" name="editWish" value="Edit">
</form>
<?php " ";
} else {
// no
// print status message
echo "No rows found!";
}
// free result set memory
mysql_free_result($result);
// close connection
mysql_close($connection);
?>
The database has 4 fields, 3 varchar and 1 int with current value of 0. I checked the page source code and confirmed each checkbox name is the stickerID. Now I will post this to the editform.php which I must create. What Im wondering is how should I write the update sql so that it takes into account each new value selected by the user in the form?
This is my idea, but how to I do it for every checkbox?
editform.php
<?php
//update multiple records
//UPDATE user_items SET stickerStatus = $_POST["stickerStatus"] WHERE stickerID = $_POST["stickerID"];
?>
First question: use mysql_fetch_assoc() instead of mysql_fetch_row(). That will return an associative array instead of an enumerated one.
Second question: read up on HTML forms and form handling.
The answer to the question in the comments:
// The <form> tag should only be echoed once.
echo '<form name="some form" action="editform.php" method="post">';
while($row = mysql_fetch_assoc($result)) {
echo "<tr>";
echo "<td>".$row['stickerID']."</td>";
echo "<td>" .$row['stickerName']."</td>";
echo "<td>".$row['stickerSection']."</td>";
echo "<td>"?>
<input type="hidden" name="status_<?php echo $row['stickerID"; ?>" value="0">
<input type="checkbox" name="status_<?php echo $row['stickerID'] ?>" value="<?php echo $row['stickerStatus'] ?> ">
<?php "</td>";
echo "</tr>";
}
// You need a submit button to send the form
echo '<input type="submit">';
// Close the <form> tag
echo '</form>';
Using a hidden input with the same name as the checkbox makes sure a value for the given input name is sent to the server. The value of a checkbox that's not checked will not be sent. In that case the hidden input will be used.
You can get the submitted values in editform.php as follows:
<?php
foreach ($_POST as $field => $value) {
if (strpos($field, 'status_')) {
// Using (int) makes sure it's cast to an integer, preventing SQL injections
$stickerID = (int) str_replace('status_', '', $field);
// Again, preventing SQL injections. If the status could be a string, then use mysql_real_escape_string()
$stickerStatus = (int) $value;
// Do something with the results
}
}
Do
print_r($row)
to find out exactly how your row arrays are constructed and work from there.
For your comparison operator, use
$row[3] === 0
instead of
$row[3] == 0
This will return true if both the value and data type match rather than just the value.
0 can mean the Boolean false aswell as the numeric value 0
I've created a textbox so when the admin types a name and clicks submit, it will shows a list of retrieved data from the database.
<form method="post" action="">
<?php
$teacherName = $_POST['teacherName'];
if ($_POST['submitted'] == 1) {
if($teacherName != ""){
$getName = mysql_query("SELECT name, user_id FROM members WHERE name = '$teacherName'");
$teacherdetails = mysql_fetch_array($getName);
$teachername = $teacherdetails['name'];
$teacher_id = $teacherdetails['user_id'];
if($teachername != ""){
print $teachername . "<br/>";
} else {
print "Give a valid name <br/>";
}
}
}
if ($teachername == ""){ ?>
Teacher name:<input type="text" size="20" name="teacherName"><input type="hidden" name="submitted" value="1"><br/>
<input type="submit" value="Submit" />
<?php $getModule = mysql_query("......");
while ($row2 = mysql_fetch_array($getModule)) { ?>
<input type="checkbox" name="modules[]" value="<?php print $row2["module_id"]?>"/> <?php print $row2["module_name"] . '<br/>'; } ?>
</div><br/> <?php } ?>
<input type="submit" value="Submit" />
</form>
Below I wrote this code (in the same script):
<?php
$modules = $_POST['modules'];
for($i = 0; $i < count($modules); $i++){
$module=mysql_query("INSERT INTO module (module_id,user_id) VALUES ('$modules[$i]','$teacher_id')");
}
?>
but for some reason when I call the variable "$teacher_id" (which is the value I retrieved before from the database. It works fine in the form) it returns nothing. It's null but I can't understand why.
Am I doing something wrong?
First off, put the PHP outside the form tags, at the top.
Secondly, the data you are receiving could be an array; with more than one result set;
do this just incase it it returned as that;
foreach($teacherdetails AS $teacher) {
//also set the values of the variables here
echo $teacher['name'];
echo $teacher['user_id'];
}
Regarding the last bit, is the $teacher_id successfully printing a result?
Also, where is the modules being input and posted from?
New to PHP and reading through Robin Nixon's PHP, MySQL, Javascript book. I am having trouble with an example of inserting and deleting data using a PHP script, specifically with how the author uses $_POST.
The example is a pretty simple add records/delete records of books with multiple inputs. Here's the code:
if (isset($_POST['delete']) && isset($_POST['isbn']))
{
$isbn = get_post('isbn');
$query = "DELETE FROM classics WHERE isbn='$isbn'";
if (!mysql_query($query, $db_server))
echo "DELETE failed: $query<br />" .
mysql_error() . "<br /><br />";
}
if (isset($_POST['author']) &&
isset($_POST['title']) &&
isset($_POST['category']) &&
isset($_POST['year']) &&
isset($_POST['isbn']))
{
$author = get_post('author');
$title = get_post('title');
$category = get_post('category');
$year = get_post('year');
$isbn = get_post('isbn');
$query = "INSERT INTO classics VALUES" .
"('$author', '$title', '$category', '$year', '$isbn')";
if (!mysql_query($query, $db_server))
echo "INSERT failed: $query<br />" .
mysql_error() . "<br /><br />";
}
echo <<<_END
<form action="sqltest.php" method="post"><pre>
Author <input type="text" name="author" />
Title <input type="text" name="title" />
Category <input type="text" name="category" />
Year <input type="text" name="year" />
ISBN <input type="text" name="isbn" />
<input type="submit" value="ADD RECORD" />
</pre></form>
_END;
$query = "SELECT * FROM classics";
$result = mysql_query($query);
if (!$result) die ("Database access failed: " . mysql_error());
$rows = mysql_num_rows($result);
for ($j = 0 ; $j < $rows ; ++$j)
{
$row = mysql_fetch_row($result);
echo <<<_END
<pre>
Author $row[0]
Title $row[1]
Category $row[2]
Year $row[3]
ISBN $row[4]
</pre>
<form action="sqltest.php" method="post">
<input type="hidden" name="delete" value="yes" />
<input type="hidden" name="isbn" value="$row[4]" />
<input type="submit" value="DELETE RECORD" /></form>
_END;
}
mysql_close($db_server);
function get_post($var)
{
return mysql_real_escape_string($_POST[$var]);
}
?>
When you refer to an element in $_POST with if (isset($_POST['delete']) && isset($_POST['isbn'])), where delete and isbn are used as names multiple times, how does $_POST know which element to reference to delete? I assume that since you can only delete one record at a time, the element in the array will automatically point to the one that's already set. However, how does the second condition of isset($_POST['isbn']) know which "isbn" element to check for? Does the && make the $_POST['isbn'] "inherit" the correct row?
Thanks for the help! And apologies for any possible misuse of the vocab. Still getting used to everything.
Your question is actually well thought out. And the example given in the book seems quite sloppy to me. I am assuming in later chapters he will delve into the use of arrays in $_POST values. But anyway, here is the key to the functionality of the whole script:
for ($j = 0 ; $j < $rows ; ++$j)
{
$row = mysql_fetch_row($result);
echo <<<_END
<pre>
Author $row[0]
Title $row[1]
Category $row[2]
Year $row[3]
ISBN $row[4]
</pre>
<form action="sqltest.php" method="post">
<input type="hidden" name="delete" value="yes" />
<input type="hidden" name="isbn" value="$row[4]" />
<input type="submit" value="DELETE RECORD" /></form>
_END;
}
See that <form action="sqltest.php" method="post">? And see that closing </form>? And note that they are being rendered each time the for ($j = 0 ; $j < $rows ; ++$j) loop happens? There is one individual form element for each line. That is messy code, but it works. When one clicks submit on each individual listing, the wrapping form responds & parses the variables nested inside it.
Like I said, sloppy code. But works. And it’s because if you have 30 ISBNs listed this program will spit out 30 individually wrapped <form> items. Uggh! Seriously if the book does not address arrays later on in a way that addresses this face-palm of a coding mess find a new book.
Since there are multiple forms, the input elements of only one form are submitted.
So basically, sqltest.php receives only one array of $_POST containing ['delete'] and ['isbn'] with the corresponding values only once.
You can check this out by using print_r($_POST) in sqltest.php.