populate php form fields with mysql array (on click) - php

I'm a php/mysql newbie, working on an invoicing application. I have a summary.php page, in which I'm using php to query a db and render a table with the retrieved data:
< ?php
mysql_connect ... [ snip ] ...
// retrieve all data in the 'Invoices' table ...
$result = mysql_query("SELECT * FROM Invoices") or die(mysql_error());
// ... and store each record in a variable:
$row = mysql_fetch_array($result);
and my table is:
<table class="record-summary">
<form action="/edit.php" method="post">
<tr>
<th ...
[ snip: more table headers ] ...
<?php
$controls = "<input type=\"submit\" value=\"details.php\" /><input type=\"submit\" value=\"edit.php\" />";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td class=\"id\">". $row['ID']. "</td>";
echo "<td class=\"inv\">". $row['invoiceNumber']. "</td>";
[ snip: more data cells ] ...
echo "<td class=\"controls\">". $controls . "</td>";
The last cell (td.controls) in each row contains two submits, one linking to a detail view (details.php), the other to a form page (edit.php). My objective is to populate either page with the values of the record/row. Where I need help is how exactly to use the $row variable to carry this array to e.g., edit.php, and populate the fields in the form (actually I'm fairly certain I have the syntax for the form inputs' value attributes). Both details.php and edit.php have all the data fields in the record represented, though in summary.php only a portion of the fields are displayed (ergo, 'summary.php'). So my questions are:
How do I ensure that when either button is clicked, the $row contains the values of the given record, and how to push the array into either details.php or edit.php?
Many thanks in advance,
src

You can pass the ID to edit.php and details.php but without the form just with two links to edit.php?id=and details.php?id=:
<?php
// $controls = "<input type=\"submit\" value=\"details.php\" /><input type=\"submit\" value=\"edit.php\" />"; <-- is not necessary
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td class=\"id\">details.php | edit.php</td>";
echo "<td class=\"inv\">". $row['invoiceNumber']. "</td>";
// [ snip: more data cells ] ...
// echo "<td class=\"controls\">". $controls . "</td>"; <-- is not necessary
You can grab the data using the id:
//....
if (isset($_GET['id']) && is_numeric($_GET['id']))
{
$id = $_GET['id'];
}
else
{
die("There is no id.");
}
$sql = sprintf("SELECT * FROM Invoices WHERE id = %s", $id);
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($result);

echo "<input type=\"hidden\" name=\"row\" value=\"" . $row . "\"/>";
Include this in your loop and your form's "action" script will be able to access the corresponding $row variable via $_POST['row'].

Related

How to select a specific row from a table to edit or delete

I have implemented a booking system, part of the system involves allowing users to modify or delete a booking. I am able to retrieve bookings from the database based on user's session and id which is displayed in a html table. I have been having trouble selecting a specific row from the html table to edit or delete a booking. I want to be able to select a specific row from the html table which i will then be able to edit or delete that record.
The code below retrieves the bookings and displays it in a table
bookings.php
$sqlquery = "SELECT * FROM bookings1,users WHERE bookings1.userid =
users.userid AND users.username = '".$_SESSION['loggedInUser']."' ";
$results = $mysqli->query($sqlquery);
if ($results->num_rows > 0) {
while ($row = $results->fetch_assoc()){
echo'<form method = "POST" action = "editmot.php" >';
echo'<tr>';
echo "<td>". $row["booking_id"]. "</td>";
echo "<td>". $row["Type"]. "</td>";
echo "<td>". $row["BookingDate"]. "</td>";
echo "<td>". $row["Timeslot"]. "</td>";
echo "<td>". $row["Manufacture"]. "</td>";
echo "<td>". $row["Model"]. "</td>";
echo "<td>". $row["RegistrationNo"]. "</td>";
echo "<td><a href = 'editmot.php' id ='".$row['booking_id']."'> Edit </td>";
echo "<td><a href = 'delete.php' id = '".$row['booking_id']."'> Remove </td>";
echo '</tr>';
echo '</form>';
In the href attribute of the Edit Link, include the Booking_Id as a URL parameter. When the Edit page loads, pick up the booking_id from the URL parameter and fetch the other fields for edit. Like :
echo " <a href = 'editmot.php' . '?EditBookingId=' . $row['booking_id'] "
and then so on and so forth concatenate other things.
Your final href URL should look like :
'http://editmot.php?EditBookingId=24798' or some such.
use this code to edit or delete
for edit
for delete
if(isset($_REQUEST['action']))
if($_REQUEST['action']=="update")
update query
else if($_REQUEST['action']=="delete")
delete query
Instead of using the anchor tag, you could use a submit button and a hidden input field to hold the booking ID, since each booking detail (or row) is in a separate form. You could use something like this in each booking row:
echo "<td><input name='edit' type='submit' value='Edit'>"
. "<input type='hidden' name='booking_id' value='".$row['booking_id']."'></td>";
echo "<td><input name='delete' type='submit' value='Remove'>"
. "<input type='hidden' name='booking_id' value='".$row['booking_id']."'></td>";
And then in editmot.php, process the delete or edit form action:
if (isset($_POST['edit'])) {
// edit video here
}
if (isset($_POST['delete'])) {
// delete video here
}
You need to insert the id in the url so you can get it with the $_GET method in the edit or delete file.
So your anker needs to look something like:
<a href = 'delete.php?id=".$row['booking_id']."'>Delete</a>;
Now when a user go's to that url the url wil look something like:
localhost/delete.php?id=20
Now in your delete.php you can get the id with the $_GET method:
$id = $_GET['id'];
$qry = "DELETE FROM booking1 WHERE id=$id"; //this will delete the row where id is 20

Can't update a selected row by user

I've written this code for a user to edit one row and update it in MySQL, but it always posts the last row no matter which row you have selected (there are 3 rows).
What's the problem?
<?php include("includes/db_connection.php"); ?>
<?php
global $connection;
$sid="s5";
/**select all salesman from store 5**/
$sql ="SELECT * FROM employees WHERE e_type='Salesperson' AND store_assigned='".$sid."';";
/**get the result and put into table, which can be edited by user**/
$result = mysql_query($sql);
echo "<form method='post' action='update_salesman.php'>";
echo "<table border='1'><tr><th>Employee ID</th><th>Name</th><th>Address</th><th>Email</th><th>Job Title</th><th>Store</th><th>Salary</th></tr>";
while ($row = mysql_fetch_assoc($result)) {
echo "<tr><td><input type='text' name='eid' value='".$row['eid']."' readonly /></td>";
echo "<td><input type='text' name='e_name' value='".$row['e_name']."' /></td>";
echo "<td><input type='text' name='e_addr' value='".$row['e_addr']."' /></td>";
echo "<td><input type='text' name='e_email' value='".$row['e_email']."' /></td>";
echo "<td><input type='text' name='e_type' value='".$row['e_type']."' /></td>";
echo "<td><input type='text' name='store_assigned' value='".$row['store_assigned']."'/></td>";
echo "<td><input type='text' name='e_salary' value='".$row['e_salary']."' /></td>";
echo "<td><input type ='submit' value='update' /></td></tr>";
}
echo "</table>";
echo "</form>";
print($sql);
?>
Get the posted data, and update it in MySQL database:
<?php include("includes/db_connection.php"); ?>
<?php
$eid = $_POST['eid'];
$ename = $_POST['e_name'];
$eaddr = $_POST['e_addr'];
$eemail = $_POST['e_email'];
$etype = $_POST['e_type'];
$estore = $_POST['store_assigned'];
$esalary = $_POST['e_salary'];
$sql = "UPDATE employees SET e_name='" . $ename . "', e_addr='" . $eaddr . "', e_email='" . $eemail . "', e_type='" . $etype . "', store_assigned='" . $estore . "', e_salary='" . $esalary . "' WHERE eid='" . $eid . "' ;";
$result = mysql_query($sql);
print("</br>" . $sql);
?>
The result is always this:
UPDATE employees SET e_name='Norah ', e_addr='111 Melwood,PA', e_email='anorahm#gmiil.com', e_type='Salesperson', store_assigned='s5', e_salary='4000.00' WHERE eid='e334' ;
Your problem is twofold. First, when generating the HTML code, you use a while loop to echo the fields. Note that the names of these fields are the same every time the loop runs. (You can see this in the generated HTML (source code). Note that on submitting, one one of the multiple same-named fields will be posted.
Second, in the PHP form handler code, you read the post data and then do one update query, while you may want to update more than one field.
The easiest way to solve this is to make sure that the field names in the HTML form are different for each of the rows, and to use a loop structure when updating the sql table such that there's an update for each row.
even though it may appear fine on the html side, it's clear what's happening on the server side when it gets the form
When the server gets the form it will only see the last record because each record will overwrite the values that come before it resulting in only getting the data from the last record
What you can do is give each set of values its own form (Wouldn't suggest). But with this method, you can leave your code almost as is, just move the form tags into the while loop. OR write the input names as e_name[], etc.
This way it will be passed as an array to the server and you can loop through to get all your values
On the server end, to get the array you would do something like
$e_names = $_POST['e_name']; //Value will be an array

Is it possible to pass a variable of value from associative array, using hidden input, to another page?

I am trying to get the $w['id'] value for a mysql row and pass it to another page using a hidden input field and variable $blog_id. Here is the code for the first page:
$query = "SELECT * FROM blog WHERE username = '$username' ORDER BY created_date DESC;";
$result = $mysqli->query($query);
$rows = resultToArray($result);
// var_dump($rows);
foreach($rows as $r => $w) {
echo "<tr>\n";
echo "<td>{$w['title']}\n";
echo "<td>{$w['id']}\n";
echo "<td>{$w['created_date']}</td>\n";
echo "<td>{$w['updated_date']}</td>\n";
echo "<td style=\"border:none\">{$w['template']}</td>\n";
$blog_id = $w['id'];
echo "<input type=\"hidden\" name=\"id\" value=\"$blog_id\" />\n";
echo "<td style=\"border:none\"><button type=\"submit\" name=\"view\">View</button></td>\n";
echo "<td style=\"border:none\"><button type=\"submit\" name=\"edit\">Edit</button></td>\n";
echo "<td style=\"border:none\"><button type=\"submit\" name=\"delete\"><font color=\"red\">Delete</font></button></td>";
echo "</tr>\n";
}
?>
In my html table the values echo correctly but when I try to grab the $w['id'] value and pass it using, say, the edit button to the next page the value is always the lowest id value in the mysql table.
The code for the critical part in the second page is:
sec_session_start();
$username = $_SESSION['username'];
// $blog_id = $_SESSION['blog_id'];
if(isset ($_POST['edit'])) {
$blog_id = $_POST['id'];
$result = $mysqli->query("SELECT * FROM blog WHERE id = '$blog_id'");
if($result->num_rows > 0) {
$rows = resultToArray($result);
foreach($rows as $r => $w) {
?>
<body id="blog_editor">
<?php var_dump($_POST); ?>
The value of var_dump($_POST) is always ["id"]=>string(2) "43" whereas the foreach loop on the first page produces lots of different IDs.
Does anybody know what I am doing wrong or have an alternative way of doing the same kind of thing which might work?
You use a foreach and echo many different id.
I don't see any SUBMIT button or <form> tag.
What you can do is, inside the foreach loop, create a form with is own button:
<?php
foreach($rows as $r => $w) {
echo '<form action="page.php" ...>
echo ....
echo '<input type="submit">
}
?>
OR if you have multiple results inside one only form then you have to change the name of your element (which will be later give the value to `$_POST['id']) every time the loop loops.
To do this change this line:
echo "<input type=\"hidden\" name=\"id\" value=\"$blog_id\" />\n";
1) to this:
echo "<input type='hidden' name='id".$blog_id."' value='$blog_id' />\n";
and then when you call $_POST you'll have $_POST['idXX'] where XX = number of the ID
2) or TO this to create an array with all IDs on it:
echo "<input type='hidden' name='id[]' value='$blog_id' />\n";
and then $_POST['id'] will be an array

Can you store selected sql query values in the url and then retrive them with $_GET?

I'm trying to make it so that when a users clicks one of the rows,it will take them to a new page whose link is given as the value of the row they selected and then retrieve the value with $_GET["timesub"].
Anyone know how to do this?
mysql_select_db("RRRC", $con);
$result = mysql_query("SELECT * FROM mainreq WHERE roomnum=$loc");
echo "<table border='1'>
<tr>
<th> Submitted </th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td> . $row['timesub'] . </td>";
echo "</tr>";
}
echo "</table>";
Assuming that $row['timesub'] identifies a row in your data set (I doubt it), just fix your echo instruction as:
echo "<td>" . $row['timesub'] . "</td>";
Escaping the html quotes properly.
echo "<td><a href='roomdata.php?timestamp=".$row['timesub']."'>".$row['timesub']."</a></td>";
Close the outer " before the . concatenator, replace the inner " with '
A good practice is to use the row's primary key to reference your get query; but yes - this can be done.
All you have to do is store the get data into a sanitized variable, and perform the required SQL lookup / data display.
EX:
$roomnum=mysql_real_escape_string(preg_replace("/[^a-zA-Z0-9]+/", "", $_GET['roomnum']));
Now, given that "roomnum" is your primary key just look it up and display:
$result = mysql_query("SELECT * FROM mainreq WHERE roomnum='$roomnum'");
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td> . $row['timesub'] . </td>";
echo "</tr>";
}
echo "</table>";

update MySQL resultset through user-interaction and make the changes global for the application

I fetching a result set from a MySQL table and displaying it on the web page as under:
<?php
$link = mysql_connect(....);
mysql_select_db(....);
$sql = "select * from products where category = '" .$_POST['prod_cat']. "'";
$rs = mysql_query($sql, $link);
echo "<form name='prodselect' action='prodlist.php' method='post'>";
echo "<table>";
$rowcount = 1;
while ($row = mysql_fetch_array($rs))
{
echo "<tr>";
echo "<td>" .$row['product_name']. "</td>";
echo "<td><input type='checkbox' name='line_" .$rowcount. "'></td>";
echo "</tr>";
}
echo "</table>";
echo "</form>";
?>
This displays the list of products with checkbox for every product row.
The user will select products using the checkboxes.
I want to display / save the selected products in the "Products for Purchase" list on another web page.
Please help me out.
Thanks.
I can suggest you to create the checkbox like this:
echo "<td><input type='checkbox' name='products[]' value='" .$row['product_id']. "'></td>";
then on the prodlist.php you can get the array $_POST['products']

Categories