使用PDO从mySQL数据库中的表中删除记录

时间:2016-01-30 17:06:49

标签: php html mysql pdo

我一直在尝试从我的数据库中删除一行,但它一直显示我删除但没有删除任何内容请有人知道我的代码有什么问题

我尝试过使用PDO和mysql但是没有删除但会显示已删除 我不知道该怎么做。

MYSQL     

    if($user == $me){
        $sql_delete = "DELETE FROM replys WHERE id = '$id' AND rusername = '$me'";
        echo $sql_delete;
        mysql_query($sql_delete) or die(mysql_error());
        echo "Deleted";
    }
    else{
    }
}
?>

PDO

<?php
session_start();  
if(isset($_POST['DeleteThis'])){

    $db_host = "localhost";
    $db_user = "root";
    $db_pass = "kindom";
    $db_name = "posters";

    try {
        $user = $_SESSION['username'];
        $form = $_POST;
        $id = $form['id']);
        $me = $form['me'];
        if($me == $user){
            $db_conn = new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_pass);
            $db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            $stmt = $db_conn->prepare("DELETE FROM replys WHERE id = :id AND rusername = :user");

//I have tried using this SQL statements  
//$query = "DELETE FROM replys WHERE id = {$id} AND rusername = {$user}"; 
//$query = "DELETE * FROM replys WHERE id = :id AND rusername = :rusername"; 
            $query = "DELETE FROM replys WHERE id = :id AND rusername = :rusername"; 

            $stmt->bindParam(':id', $id); 
            $stmt->bindParam(':rusername', $user);

            $stmt->execute();
            echo "Deleted";
        }
        else{
            //Do nothing
        }
    }
    catch(PDOException $e)
    {
        echo "Error:" . $e->getMessage();
    }
    $db_conn = null;
}
?> 

HTML

<a href="javascript:void(0);" onclick="document.getElementById('deleterp').submit();"><i style="font-size:17px;color:#F00;" class="fa fa-trash"></i></a>
<form id="deleterp" action="" method="POST">
<input type="hidden" name="id" value="<?php echo $rpId;?>"/>
<input type="hidden" name="DeleteThis" value="1"/>
<input type="hidden" name="me" value="<?php echo $rplyuser;?>"/>
</form></div> 

1 个答案:

答案 0 :(得分:0)

<强> PDO

更改

$stmt = $db_conn->prepare("DELETE FROM replys WHERE id = :id AND rusername = :rusername");

$stmt = $db_conn->prepare("DELETE FROM replys WHERE id = :id AND rusername = :user");

喜欢..

<?php
.
.
$stmt = $db_conn->prepare("DELETE FROM replys WHERE id = :id AND rusername = :rusername");
$stmt->bindParam(':id', $id); 
$stmt->bindParam(':rusername', $user);
.
.
?> 

更改

$id = $form['id']);

$id = $form['id'];

没有得到

  

解析错误:语法错误,意外&#39;)&#39;在   第70行/home/umu35534/public_html/questions.php