){outline:none;box-shadow:none;}select::-ms-expand{;}:root,:host{--chakra-vh:100vh;}@supports (height: -webkit-fill-available){:root,:host{--chakra-vh:-webkit-fill-available;}}@supports (height: -moz-fill-available){:root,:host{--chakra-vh:-moz-fill-available;}}@supports (height: 100dvh){:root,:host{--chakra-vh:100dvh;}}
Link to home
Create Account Log in
PHP

PHP

--

Questions

--

Followers

Top Experts

PHP/MySQL C.R.U.D. - How Would I Obtain the ID for a Specific Row?

Good afternoon Experts,

I am using a while loop to fetch the data from the MySQL database. I am not sure if the while loop is throwing me off a little, but I am stumped on how I would go about obtaining the ID for a specific row, so that particular row can be modified/updated/deleted.


Here is an image of my form, and the results it fetches from the database using a while loop.

User generated image

Here is the corresponding code:


<?php
$sqlSuppTracker = "SELECT * FROM supplements
      INNER JOIN users
      ON users.id = supplements.usersID
      WHERE users.id = '$userID'";
$querySuppTracker = mysqli_query($conn, $sqlSuppTracker);
$numberRowsSupps = mysqli_num_rows($querySuppTracker);
if($numberRowsSupps == 1){
   echo "Currently, you have added $numberRowsSupps case to the supplement tracker.";
}elseif ($numberRowsSupps > 1) {
   echo "Currently, you have added $numberRowsSupps cases to the supplement tracker.";
}else {
   echo "You have not added any cases to the supplement tracker.";
require_once("forms/supplementTrackerForm.php");
<table class="tableBorder">
      <th align="left">Case Number:</th>
      <th align="left">Case Type:</th>
      <th align="left">Date Added:</th>
      <th align="left">Supplement:</th>
      <th align="left">Next Supplement:</th>
      <th align="left">Update/Delete:</th>
while ($row = mysqli_fetch_assoc($querySuppTracker)){
      <td align="left" value="<?php echo $row['caseNum']; ?>"><?php echo htmlspecialchars($row['caseNum'], ENT_QUOTES, 'UTF-8'); ?></td>
      <td align="left"><?php echo htmlspecialchars($row['caseType'], ENT_QUOTES, 'UTF-8'); ?></td>
      <td align="left"><?php echo htmlspecialchars($row['dateCreated'], ENT_QUOTES, 'UTF-8'); ?></td>
      <td align="left">
         <?php echo htmlspecialchars($row['initialDate'], ENT_QUOTES, 'UTF-8'); ?>
      <td align="left">
         <?php echo htmlspecialchars($row['supplementDue'], ENT_QUOTES, 'UTF-8'); ?>
      <td><br><br>
         <input type="submit" name="updateFiveDaySupplement" value="Update 5 Day Supplement"><br><br>
         <input type="submit" name="update14DaySupplement" value="Update 14 Day Supplement"><br><br>
         <input type="submit" name="deleteSupplement" value="Delete Supplement">
         <input type="hidden" name="hiddenID" value="<?php echo htmlspecialchars($row['supplements.id'], ENT_QUOTES, 'UTF-8'); ?>"><br><br>
</table>
if(isset($_POST['addCaseToTracker'])){
$caseNumber = "";   
$caseNumber = strip_tags($_POST['caseNumber']);
$caseNumber = str_replace(' ', '', $caseNumber);
$caseType = "";
$caseType = strtoupper(strip_tags($_POST['caseType']));
$fiveDayRule = date("Y-m-d-", strtotime('+5 days'));
$sqlInsertSuppTracker = "INSERT INTO supplements (caseNum, caseType, dateCreated, initialDate, supplementDue, usersID)
      VALUES ('$caseNumber', '$caseType', CURDATE(), CURDATE(), '$fiveDayRule', '$userID')";
// Perform a query, check for error
if (!mysqli_query($conn, $sqlInsertSuppTracker)) {
         echo("Error description: " . mysqli_error($conn));
$caseNumber = "";
$caseType = "";
header('Refresh: 0');

Open in new window

How do I obtain the ID field for a specific row so that row can be modified/deleted?

Zero AI Policy

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


Hi,
Use foreach instead or for loop
https://www.php.net/manual/en/control-structures.foreach.php

Here is the method I'm using (PDO OOP)
         $selectSql=new ASContact();
         $ContactValues = $selectSql->getContact();
         foreach($ContactValues as $ContactValue){
               $contact_id=$ContactValue["contact_id"];
                 echo $contact_id;
           }   

Open in new window


There is no automatic ID for a row.  It has to be a column part of your structure.  Can you show us the structure for that table?

the id is likely whatever makes the row specific. this can be a single or combination of columns. in you case i would guess the case_id is a primary key or unique index which would qualify as such

Reward 1 Reward 2 Reward 3 Reward 4 Reward 5 Reward 6

EARN REWARDS FOR ASKING, ANSWERING, AND MORE.

Earn free swag for participating on the platform.


Here is the MySQL table structure. I need to be able to access the ID for each set of data that is fetched in the while loop, so the user can modify the data associated with that ID.
User generated image


Your 'id' column is the key then.  It has to be part of a "WHERE `id` = 'nnnn'" statement in your SELECT or UPDATE queries.  I usually make it the first column in my display table.

So… I guess the issue is not so much what my SQL statement would be because I know how to hardcore the SQL statement to modify the record "WHERE id = 1," "WHERE id = 2," etc., but I do not know how to dynamically obtain the ID of the corresponding record. I thought I could set a variable equal to the row's ID, but that does not seem like it would work, either. If the variable is set during the WHILE loop, won't the variable be overwritten each time the loop executes, and only contain the ID of the last record of the loop...

Free T-shirt

Get a FREE t-shirt when you ask your first question.

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


You're loading the 'id' with the
$row = mysqli_fetch_assoc($querySuppTracker)

Open in new window

statement along with all the other fields.  You need to attach it to any actions in that row.  I don't see a complete form there that would identify the target page or POST or GET action.

Avatar of Joseph Longo Joseph Longo

ASKER

I'm sure this is easy to do, but I cannot wrap my brain around it...and it's frustrating to me...

I intentionally loaded all of the columns from the database and I know the ID is being loaded from the SQL query. Apart from the form being incomplete, I still don't know how to access a specific ID for a specific row when the data is being processed in a while loop...

So, for the first record ID = 1, and if I set that to a variable $suppRow then each time the while loop runs, won't it be overwritten...??

How do I set a variable to that specific ID in order access the information and update THAT specific row...?


use arrays :

"<input name=fieldname[".$row['id']."] value=...

Reward 1 Reward 2 Reward 3 Reward 4 Reward 5 Reward 6

EARN REWARDS FOR ASKING, ANSWERING, AND MORE.

Earn free swag for participating on the platform.


SOLUTION
Link to home
membership
Log in or create a free account to see answer.
Signing up is free and takes 30 seconds. No credit card required.

Okay, I like the idea of each row containing its own form. However, I cannot get the id field to echo out. When I use this, the value field does not get populated with the records ID:

<input type="hidden" name="hiddenID" value='<?php echo htmlspecialchars($row['supplements.id'], ENT_QUOTES, 'UTF-8'); ?>'><br><br>

Open in new window


However, when I use this, the value does get populated but each value is being set to the user's id, not the supplements.id

<input type="hidden" name="hiddenID" value='<?php echo htmlspecialchars($row['id'], ENT_QUOTES, 'UTF-8'); ?>'><br><br>

Open in new window




SOLUTION
Avatar of Chris Stanyon Chris Stanyon
Link to home
membership
Log in or create a free account to see answer.
Signing up is free and takes 30 seconds. No credit card required.

if you are unsure about the contents of $row, print_r , var_export , and var_dump are your friends.

--

separate forms will work. you can even simplify the code by sticing the id in the action property of the form element. that said beware that the user will not be able to make changes on multiple rows at the same time and validating any form will reload the page and undo user changes so this is probably not your best bet.

unless you want to go ajax, arrays are a much better option. the browsers are agnostic to arrays and php handles them properly.

you can use something like
fieldname[id]
or
data[id][fieldname]


So, I haven't been able to test the form handling out, yet. So, this is just me "thinking out loud," per se. When the user clicks one of the submit buttons, will the form process only the information for that specific form or will every form be processed, too.

For instance, the exact same submit button is created for each form with the same name, etc. So, how will the form be processed when form1 contains the same name for the submit buttons as form2 does?

Free T-shirt

Get a FREE t-shirt when you ask your first question.

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


SOLUTION
Link to home
membership
Log in or create a free account to see answer.
Signing up is free and takes 30 seconds. No credit card required.

Avatar of Joseph Longo Joseph Longo

ASKER

So, I am not sure why, but my form is not being processed for some reason. I do not know why, either...

Here is the corresponding PHP code:

if (isset($_POST['deleteSupplement'])){
   $IDsupplement = $_POST['hiddenSupplementID'];
   $deleteSupplementSQL = "DELETE FROM supplements WHERE supplements.id = '$IDsupplement'";
   if(!mysqli_query($conn, $deleteSupplementSQL)){
      echo("Error description: " . mysqli_error($conn));
   header('Refresh: 0');
}

Open in new window


I am not receiving any error messages, either.

SOLUTION
Link to home
membership
Log in or create a free account to see answer.
Signing up is free and takes 30 seconds. No credit card required.

Here is my entire script, including the HTML:
It does not look like any data is being sent to the form, based off var_dump;
<?php
ob_start();
session_start();
date_default_timezone_set("America/New_York");
require_once("includes/dbh.inc.php");
//THIS GETS SET WHEN THE USER LOGS IN FROM LOGIN.INC.PHP
//$_SESSION['USERNAME'] IS SET BASED OFF THE $USERNAME VARIABLE 
//WHICH GRABS THE USERNAME FROM A MYSQL_FETCH_ARRAY
//IF THE SESSION VARIABLE HAS BEEN SET, THEN THERE IS A CORRESPONDING USERNAME AND PASSWORD
if(isset($_SESSION['username'])){
   $userLoggedIn = $_SESSION['username']; 
   $sql = "SELECT * FROM users WHERE usersUsername='$userLoggedIn'";
   $query = mysqli_query($conn, $sql);
   $results = mysqli_fetch_array($query);
   $userID = $results['id'];
   $usersFName = $results['usersFirstName'];
   $usersLName = $results['usersLastName'];
   $myNumWarrants = $results['usersNum49s'];
   $myNumCases = $results['usersNumCases'];
   $_SESSION['depRank'] = $results['usersRank'];
   $_SESSION['depFirstName'] = $usersFName;
   $_SESSION['depLastName'] = $usersLName;
   $_SESSION['payroll'] = $results['usersPayroll'];
}else {
   header("Location: register.php");
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
   <!--JAVASCRIPT-->
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
   <script src="javascript/bootstrap.js"></script>
   <!--CSS-->
   <link rel="stylesheet" type="text/css" href="css/normalize.css">
   <link rel="stylesheet" type="text/css" href="css/bootstrap.css">
   <link rel="stylesheet" type="text/css" href="css/style.css">
   <script src="https://kit.fontawesome.com/b4bc5cd13e.js" crossorigin="anonymous"></script>
   <title>GEN49</title>
</head>
   <div class="topBar">
      <div class="logo">
         <a href="index.php">GEN49</a>
      <div class="search">
         <form action="search.php" method="get" name="searchForm">
            <input type="text" id="searchTextInput" name="getBondAmount" placeholder="Search Bond Schedule" autocomplete="off" onkeyup="getLiveSearchBonds(this.value, '<?php echo $bond; ?>')">
            <div class="buttonHolder">
               <img src="images/png/magnifying-glass.png">
         </form>
         <div class="searchResults">
         <div class="searchResultsFooterEmpty">
         <span class="depName">
               if($usersFName  == 'KIRK' & $usersLName =='TURNER'){
                  echo "Master of the Universe";
               }else { 
                  echo ucfirst(strtolower($results['usersRank'])) . ' ' . ucfirst(strtolower($results['usersFirstName'])) . ' ' . ucfirst(strtolower($results['usersLastName'])) . ', ' . $results['usersPayroll'] ;
         </span>
         <a href="index.php">
            <i class="fa-solid fa-house-user"></i>
         <a href="#">
            <i class="fa-solid fa-scale-balanced"></i>
         <a href="#">
            <i class="fa-solid fa-copy"></i>
         <a href="#">
            <i class="fa-solid fa-gavel"></i>
         <a href="#">
            <i class="fa-solid fa-gear"></i>
         <a href="handlers/logout.php">
            <i class="fa-solid fa-right-from-bracket"></i>
   <div class="wrapper">
// Report all errors
error_reporting(E_ALL);
$sqlSuppTracker = "SELECT supplements.id as supplementID, users.id as userID, caseNum, caseType, dateCreated, initialDate, supplementDue FROM supplements
      INNER JOIN users
      ON users.id = supplements.usersID
      WHERE users.id = '$userID'";
$querySuppTracker = mysqli_query($conn, $sqlSuppTracker);
$numberRowsSupps = mysqli_num_rows($querySuppTracker);
if($numberRowsSupps == 1){
   echo "Currently, you have added $numberRowsSupps case to the supplement tracker.";
}elseif ($numberRowsSupps > 1) {
   echo "Currently, you have added $numberRowsSupps cases to the supplement tracker.";
}else {
   echo "You have not added any cases to the supplement tracker.";
require_once("forms/supplementTrackerForm.php");
<table class="tableBorder">
      <th align="left">Case Number:</th>
      <th align="left">Case Type:</th>
      <th align="left">Date Added:</th>
      <th align="left">Supplement:</th>
      <th align="left">Next Supplement:</th>
      <th align="left">Update/Delete:</th>
while ($row = mysqli_fetch_assoc($querySuppTracker)){
      <td align="left"><?php echo htmlspecialchars($row['caseNum'], ENT_QUOTES, 'UTF-8'); ?></td>
      <td align="left"><?php echo htmlspecialchars($row['caseType'], ENT_QUOTES, 'UTF-8'); ?></td>
      <td align="left"><?php echo htmlspecialchars($row['dateCreated'], ENT_QUOTES, 'UTF-8'); ?></td>
      <td align="left">
         <?php echo htmlspecialchars($row['initialDate'], ENT_QUOTES, 'UTF-8'); ?>
      <td align="left">
         <?php echo htmlspecialchars($row['supplementDue'], ENT_QUOTES, 'UTF-8'); ?>
      <td><br><br>
         <form class="supplementForm" action="" action="POST">
            <input type="submit" name="updateFiveDaySupplement" value="5 Day Supplement"><br><br><br>
            <input type="submit" name="update14DaySupplement" value="14 Day Supplement"><br><br><br>
            <input type="submit" name="deleteSupplement" value="Delete Case"><br><br><br><br>
            <input type="hidden" name="hiddenUserID" value='<?php echo $row['userID']; ?>'>
            <input type="hidden" name="hiddenSupplementID" value='<?php echo $row['supplementID']; ?>'>
         </form>
</table>
if(isset($_POST['addCaseToTracker'])){
$caseNumber = "";   
$caseNumber = strip_tags($_POST['caseNumber']);
$caseNumber = str_replace(' ', '', $caseNumber);
$caseType = "";
$caseType = strtoupper(strip_tags($_POST['caseType']));
$fiveDayRule = date("Y-m-d-", strtotime('+5 days'));
$fourteenDayRule = date("Y-m-d-", strtotime('+14 days'));
$sqlInsertSuppTracker = "INSERT INTO supplements (caseNum, caseType, dateCreated, initialDate, supplementDue, usersID)
      VALUES ('$caseNumber', '$caseType', CURDATE(), '$fiveDayRule', '$fourteenDayRule', '$userID')";
// Perform a query, check for error
if (!mysqli_query($conn, $sqlInsertSuppTracker)) {
         echo("Error description: " . mysqli_error($conn));
$caseNumber = "";
$caseType = "";
var_dump($_POST); // visualise the incoming data.
if (isset($_POST['deleteSupplement'])){
   $IDsupplement = $_POST['hiddenSupplementID'];
   $deleteSupplementSQL = "DELETE FROM supplements WHERE supplements.id = '$IDsupplement'";
   var_dump($_POST);
   if(!mysqli_query($conn, $deleteSupplementSQL)){
      echo("Error description: " . mysqli_error($conn));