简体   繁体   中英

Deleting from table using PHP and MySQL

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?

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();

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM