1

Having a bit of trouble, I have created a form to deleted a record from a linked MySQL database using PHP that works, but I am having an problem with how to make an error display if a uadnumber value for example already exists.

<form name="deleterecord" action="indexdelete.php" method="post">
  UAD Username: <br/><input type="text" name="uadnumber" /><br/>
  <input type="submit" onclick="return deletedatabase();" value="Delete" />
</form>

<?php
  // find the values from the form
  $uadnumber = $_POST['uadnumber'] ;
?>

<?php
    $con=mysqli_connect($db_hostname,$db_username,$db_password,$db_database);
    // Check connection
    if (mysqli_connect_errno())
      {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }
    $retval = mysqli_query($con,"DELETE FROM users WHERE uadnumber='$uadnumber'");
    if(!$retval<0)
    {
      die('Could not delete data: ' . mysql_error());
    }
    echo "Deleted all linked data from user $uadnumber successfully"."<br><br>";
    echo "<hr>";
    echo "Below is the remaining users within the database";

    mysqli_close($con);

    ?>
magi4000
  • 399
  • 2
  • 10
  • 20
  • Unless you have globals on (which I hope you don't) you aren't retrieving the POST data. Add this line `$uadnumber = $_POST['uadnumber'];` above `$retval`. Also read this - http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?rq=1 – SamV Mar 15 '14 at 10:36
  • Sorry I forgot to add this in, I already had it in the webpage because linked back to the webpage that uses the form – magi4000 Mar 15 '14 at 10:37

1 Answers1

3
if (isset($_POST["uadnumber"])) {
    $uadnumber = (int)$_POST["uadnumber"];
    $db = new mysqli($db_hostname,$db_username,$db_password,$db_database);

    if ($db->query("SELECT uadnumber FROM users WHERE uadnumber='".$uadnumber."'")->num_rows > 0) {
        if ($db->query("DELETE FROM users WHERE uadnumber='".$uadnumber."'")->affected_rows > 0) {
            echo 'Desired rows have been removed.';
        } else {
            echo 'No rows have been removed.';
        }
    } else {
        echo 'There are no rows identified by given value.';
    }
}
Sates
  • 408
  • 1
  • 5
  • 21