xavier xavier - 5 months ago 13x
PHP Question

How do I update a specific row in a table using php form?

Please bear with me, I'm not familiar yet with the language. I have a table that lists an applicant record such as applicant number, name and status. I want to update an applicant status either 'hired' or 'failed' on a specific row using a PHP form. However, I'm not sure how to get the specific submit name on its row upon submission. Or if you have a workaround I would appreciate that. Thank you so much for your help.

<!DOCTYPE html>
<h2>Applicant Records</h2>

$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password ="";
$mysql_database = "applicantrecord";

// Create connection
$conn = new mysqli($mysql_hostname, $mysql_user, $mysql_password, $mysql_database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);

$sqli = "SELECT id, firstname, lastname, status FROM applicant";
$result = $conn->query($sqli);

if ($result->num_rows > 0) { ?>
<table class="table">
<th>Applicant No.</th>
// output data of each row

echo "<tbody>";
while($row = $result->fetch_assoc())
{ ?>
<?php echo $row["id"];
$appid = $row["id"];
<?php echo $row["lastname"]; ?>
<?php echo $row["firstname"]; ?>
<?php echo $row["status"]; ?>

<form action="" role="form" method="post" name="form<?php echo $appid; ?>">
<select name="applicant_status">
<option value="Hired">Hire</option>
<option value="Failed">Fail</option>

<button type="submit" class="btn btn-default" name = "submit<?php echo $appid; ?>" data-dismiss="modal">Submit</button>

$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$newappid = $appid;
$newapptstatus = $_POST['applicant_status'];
$connect = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $connect ) {
die('Could not connect: ' . mysql_error());

$sql_sub = "UPDATE applicant ". "SET status = '$newappstatus'".
"WHERE id = '$newappid'" ;
$retval = mysql_query( $sql_sub, $connect );

if(! $retval ) {
die('Could not update data: ' . mysql_error());
echo "<script type= 'text/javascript'>alert('An error occured! Applicant status update failed!');</script>";

echo "<script type= 'text/javascript'>alert('Applicant status updated successfully!');</script>";


<?php }
echo "</tbody>";
echo "</table>";
} else {
echo "0 results";



In your if statement where you check that $_POST['submit'] is set, the index 'submit' does not exist. Thus isset($_POST['submit']) evaluates to false and your query to update the table is never being executed.

The variable $appid is being changed with each row that is added, so when the page is done loading and the submit button is pushed on a certain row, $appid won't necessarily contain the correct row number.

To get around this, you could use a hidden input in your form:

<input name="id" value="<?php echo $appid ?>" type="hidden">

Then you can replace isset($_POST['submit']) with isset($_POST['id']) and set $newappid = $_POST['id'] to get the row number to be changed.