0

Seem to be having an error trying to delete a tuble (usernames) from an SQL table using PHP/SQL queries. My current code is as follows:

<html lang="en" >
<body>
<?php
        $conn = new mysqli('localhost', 'myUsername', 'myPassword', 'dbName') or die ('Cannot connect to db');

        $uname=$_POST['uname'];

        $conn->query("DELETE FROM Account WHERE username = $uname");

        echo '<script type="text/javascript">';
        echo 'alert("-ADMIN-\nRemoved user successfully!");';
        echo 'window.location.href = "admin.php";';
        echo '</script>';
?>
</body>
</html>

This exact same code works to delete a post from a website from a differnt table but is not deleting user accounts by username. Any ideas?

3
  • You need to prepare and execute this statement for it to work. $stmt = $conn->prepare('DELETE FROM Account WHERE username = ?'); $stmt->bind_param('s', $_POST['uname']); $stmt->execute(); Commented Dec 9, 2017 at 8:51
  • 1
    you do not need to prepare it for it to work. OP is just a newbie. though preparing the query ensures sql injection attacks are removed. Commented Dec 9, 2017 at 8:53
  • Well if you call opening yourself to an SQL attack - "working", then sure, you can get "working" code by adding single quotes to your query and having raw post data within your SQL. Commented Dec 9, 2017 at 9:14

2 Answers 2

1

presumably $uname is a string and the column username is also a string so you need to quote the variable within the string

$conn->query("DELETE FROM Account WHERE username = '$uname'");

This does however leave your code open to sql injection so you would be better using a prepared statement

$stmt=$conn->prepare("DELETE FROM Account WHERE username = ?" );
$stmt->bind_param('s', $uname );
$stmt->execute();
Sign up to request clarification or add additional context in comments.

Comments

0

Checkout this solution

<?php
$conn = new mysqli('localhost', 'myUsername', 'myPassword', 'dbName') or die ('Cannot connect to db'); 
 $stmt = $conn->prepare('DELETE FROM Account WHERE username = ?');
 $stmt->bind_param('s', $_POST['uname']); 
 $stmt->execute();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.