While running this script in php 8.0 I receive no errors however in php 8.2 I receive a blank alert window after attempting to delete a record. and the delete query within the 'recordToDelete' elseif conditional below isn't removing the record. The issues appears to be somewhere within the second conditional where the post variable recordToDelete exists.

The other delete queries under the other conditional statements are working with their own respective post variables. I had checked the whole script for deprecated functions however I'm not seeing anything? Again it works in 8.0 but not above.

<?php session_start();
//db connect script

function getSlug($text)
{
    $text = preg_replace('~[^\\pL\d]+~u', '-', $text);
    $text = trim($text, '-');
    $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
    $text = strtolower($text);
    $text = preg_replace('~[^-\w]+~', '', $text);
    if (empty($text)) {
        return 'n-a';
    }
    return $text;
}

if (isset($_POST["content_txt"]) && strlen($_POST["content_txt"]) > 0) { //check $_POST["content_txt"] is not empty

//sanitize post value, PHP filter FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH Strip tags, encode special characters.
    $contentToSave = filter_var($_POST["content_txt"], FILTER_SANITIZE_NUMBER_INT);

$slug = preg_replace('/[^A-Za-z0-9-]+/', '-', $contentToSave);

// Insert sanitize string in record
$insert_row = $mysqli ->query("INSERT INTO steam_lessons (idmember, title, slug, lessontype, cat, subject, visible, price) VALUES('" . $_SESSION["memberid"] . "','" . $contentToSave . "','" . getSlug($contentToSave) . "','" . $_POST["lessontype"] . "','" . $_POST["cat"] . "','" . $_POST["subject"] . "',1,'" . $_POST["pricequick1"] . "')");

 if ($insert_row) {
        //Record was successfully inserted, respond result back to index page
        $my_id = $mysqli->insert_id; //Get ID of last inserted row from MySQL

    $q3 = "select * from steam_lessons WHERE lessonid = " . $my_id . "";
    $r3 = mysqli_query($con, $q3) or die(mysqli_error());

    $a3 = mysqli_fetch_array($r3);

    echo '<ul><li style="list-style-type: none;" id="item_' . $my_id . '">';
    echo
        '<div style="background-color: #DEE6DB; padding: 15px; border-top: 2px solid white; display: block; position: relative; height: auto;">';

    echo
        "<span style=\"margin-bottem: 10px; font-size:1.3em;\"><a href=\"lesson-plans.php?lessonplans=" . $a3['lessonid'] . "&slug=" . $a3['slug'] . "\"><b>" . $a3['title'] . "</b></a> | <a href=\"lesson-plans.php?lessonplans=" . $my_id . "&slug=" . $a3['slug'] . "&mode=edit\"><b>Edit</b></a> |<a href=\"#\" class=\"del_button\" id=\"del-" . $my_id . "\">Delete</a></span><br>";
    echo '<div class="group">
<div class="left">';
    if ($a3["imagelesson"] != "") {
        echo '<img src="images/large/' . $a3["imagelesson"] . '">';
    } else {
        echo '<img src="images/lessonplans.jpg">';
    }

    echo '</div>';
    echo '';

    echo $contentToSave . '</li></ul>';
    $mysqli->close(); //close db connection
} else {

    //header('HTTP/1.1 500 '.mysqli_error()); //display sql errors.. must not output sql errors in live mode.
    //header('HTTP/1.1 500 Looks like mysql error, could not insert record!');
    exit();
}
} elseif (isset($_POST["recordToDelete"]) && strlen($_POST["recordToDelete"]) > 0
    && is_numeric($_POST["recordToDelete"])) {

//do we have a delete request? $_POST["recordToDelete"]

//sanitize post value, PHP filter FILTER_SANITIZE_NUMBER_INT removes all characters except digits, plus and minus sign.
$idToDelete = filter_var($_POST["recordToDelete"], FILTER_SANITIZE_NUMBER_INT);

//delete raw lesson image file

$sqlz =
    "SELECT lessonid, imagelesson, video, zipfile FROM steam_lessons WHERE lessonid = " . $idToDelete . "";
$result = $mysqli->query($sqlz);

$root = str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT']);

while ($rowx = $result->fetch_array(MYSQLI_ASSOC)) {
    unlink('' . $root . '/images/thumbs/' . $rowx['imagelesson'] . '');
    unlink('' . $root . '/images/large/' . $rowx['imagelesson'] . '');
    unlink('' . $root . '/images/large/' . $rowx['video'] . '');
    unlink('' . $root . '/zips/' . $rowx['zipfile'] . '');
}

//delete all raw upload files from directory
$sql = "SELECT idlesson, filename FROM steam_downloads WHERE idlesson = " . $idToDelete . "";
$resultx = $mysqli->query($sql);
while ($a1 = $resultx->fetch_array(MYSQLI_ASSOC)) {
    unlink('' . $root . '/uploads/' . $a1['filename'] . '');
}

//delete all db entries of uploads
$result2 = mysqli_query($con, $sql);
$a2 = mysqli_fetch_assoc($result2);
$query = "DELETE FROM steam_downloads WHERE idlesson=" . $a2['idlesson'] . "";
mysqli_query($con, $query);

//try deleting record using the record ID we received from POST
$delete_row = $mysqli->query("DELETE FROM steam_lessons WHERE lessonid=" . $idToDelete);
$delete_row2 = $mysqli->query("DELETE FROM steam_lessons_shared WHERE idlesson=" . $idToDelete);
//$delete_row3 = $mysqli->query("DELETE FROM steam_lessons_saved WHERE idlesson=" . $idToDelete);

if (!$delete_row) {
    //If mysql delete query was unsuccessful, output error
  //  header('HTTP/1.1 500 Could not delete record!');
    exit();
}

$mysqli->close(); //close db connection
$con->close(); //close db connection
} elseif (isset($_POST["recordToDeletex"]) && strlen($_POST["recordToDeletex"]) > 0
    && is_numeric($_POST["recordToDeletex"])) {

//sanitize post value, PHP filter FILTER_SANITIZE_NUMBER_INT removes all characters except digits, plus and minus sign.
$idToDelete =
    filter_var($_POST["recordToDeletex"], FILTER_SANITIZE_NUMBER_INT);

//try deleting record using the record ID we received from POST
$delete_row = $mysqli->query("DELETE FROM steam_lessons_shared WHERE idlesson=" . $idToDelete);
$mysqli->close(); //close db connection

} elseif (isset($_POST["recordToDeletey"]) && strlen($_POST["recordToDeletey"]) > 0
    && is_numeric($_POST["recordToDeletey"])) {

//sanitize post value, PHP filter FILTER_SANITIZE_NUMBER_INT removes all characters except digits, plus and minus sign.
$idToDelete =
    filter_var($_POST["recordToDeletey"], FILTER_SANITIZE_NUMBER_INT);

//try deleting record using the record ID we received from POST
$delete_row = $mysqli->query("DELETE FROM order_item WHERE order_plan=" . $idToDelete);
$mysqli->close(); //close db connection


} elseif (isset($_GET["approve"]) && strlen($_POST["recordToDelete"]) > 0 &&
    is_numeric($_POST["recordToDelete"])) {
//do we have a delete request? $_POST["recordToDelete"]

//sanitize post value, PHP filter FILTER_SANITIZE_NUMBER_INT removes all characters except digits, plus and minus sign.
$idToDelete = filter_var($_POST["recordToDelete"], FILTER_SANITIZE_NUMBER_INT);

//try deleting record using the record ID we received from POST
$delete_row = $mysqli->query("UPDATE steam_lessons SET visible = 1 WHERE lessonid=" . $idToDelete);

echo $delete_row;

//die();

if (!$delete_row) {
    //If mysql delete query was unsuccessful, output error
    //header('HTTP/1.1 500 Could not delete record!');
    exit();
}
$mysqli->close(); //close db connection
} else {
    //Output error
    //header('HTTP/1.1 500 Error occurred, Could not process request!');
    //exit();
}

?>

    Is there anything in your server's error logs? Have you checked with the browser to see if it is actually receiving a 500 response?
    What happens in PHP 8.1? There may be something relevant here or here.

    Are you really intending $_POST['content_txt'] to only contain integers?

    Is there any significance in that you have two branches that check recordToDelete, with one checking if $_POST['recordToDelete'] is set and the other checking $_GET['approve']?

    Is there some reason you use mysqli_query($con, $query) instead of $mysqli->query() at a few points? Is there some reason you have two db connections?

    Also, you really need to learn to use prepared statements.

    In passing, if you're not going to be using the value of a column returned by a SELECT statement you don't need to include it in the columns returned. "SELECT filename FROM steam_downloads WHERE idlesson=?" will work just fine.

    (Oh, and one more aside, one of your spans has a style of "margin-bottem"...)

      The preceding javascript (alert(thrownError) is what is throwing the alert error message below which is calling the response.php script, so not exactly a 500 error code as I originally thought.

      I did a var dump on $_POST["recordToDelete"] in the response.php file to see if the post variable was not null, and it appears to be fine as it showed the integer number of the record.

      I changed FILTER_SANITIZE_STRING to FILTER_UNSAFE_RAW when passing $_POST['content_txt'], as FILTER_SANITIZE_STRING is no longer supported in 8.3. When selecting my delete link to remove item div from list, I'm still getting the javascript empty alert window. I'm assuming this is occuring because there is some conflict with the coding in response.php.

      
      //##### Send delete Ajax request to response.php #########
          $("body").on("click", "#responds .del_button", function(e) {
               e.preventDefault();
               var clickedID = this.id.split(\'-\'); //Split ID string (Split works as PHP explode)
               var DbNumberID = clickedID[1]; //and get number from array
               var myData = \'recordToDelete=\'+ DbNumberID; //build a post data structure
      
          $(\'#item_\'+DbNumberID).addClass( "sel" ); //change background of this element by adding class
          $(this).hide(); //hide currently clicked delete button
      
              jQuery.ajax({
              type: "POST", // HTTP method POST or GET
              url: "response.php", //Where to make Ajax calls
              dataType:"text", // Data type, HTML, json etc.
              data:myData, //Form variables
              success:function(response){
                  //on success, hide  element user wants to delete.
                  $(\'#item_\'+DbNumberID).fadeOut();
              },
              error:function (xhr, ajaxOptions, thrownError){
                  //On error, we alert user
                  alert(thrownError);
              }
              });
      });
      

        Your code is vulnerable to an SQL Injection Attack.

        • NEVER EVER put variables in your query
        • NEVER EVER trust user supplied data
        • Use Prepared Statements

          In your browser's developer tools, network tab, for the ajax request, what is the status code and what is the response body?

          If you are going to use filter_var() you must test the returned value, otherwise forget about using them. They can return a false, null, or expected value. The only time you would use the returned value is if there is an expected value. You don't have any logic to do this. If you switch to using prepared queries, you don't need to use these anyways. If using the msyqli extension seems overly complicated when dealing with prepared queries, it is. This would be a good time to switch to the much simpler and better designed PDO extension.

          Rather than using var_dump() on the post data, what does using it on $idToDelete show?

          Are the files unlinked or does that branch of conditional logic do nothing. i.e. get skipped over? Can you echo a test message inside that logic and see it in the browser's response body for the ajax call?

          Exceptions are used for mysqli errors for the connection, query, exec, prepare, and execute calls by default in php8+, so none of the discrete database error handling logic you have now in the code will get executed upon an error, and should be removed. Execution transfers to php's exception error handling upon an error, where php will produce an uncaught exception error with the raw database error information in it. This will get reported and displayed or logged based on php's error_reporting, display_errors, and log_errors settings. You need to specifically set these up to either report and display all php errors or to report and log all php errors, which will now include the uncaught database error information. I suspect that what php is doing upon an error, has changed due to the error_reporting, display_errors, and log_errors settings on your system, and this is reason for the difference in operation, not because of the change in php version.

          The or die(mysqli_error()) calls are both incorrect (mysqli_error requires the connection as a parameter) and when using exceptions for database errors will never get executed upon an error, and should be removed in any case.

            Write a Reply...