avatar

目录
PHP编写日常

PHP编写日常

在用PHP,MYSQL写网站的时候时常会碰到一些坑和一些在看到他人代码时恍然大悟的感觉,就想着用这篇文章记录一下

PHP+MYSQL用预处理执行批量删除

以下是自己之前在实现网站删除功能时的一段代码,但很坑的是其中的$del_arr[0](在代码块中间)这一个变量,若将其里面的数字替换成其他的,或者是将中括号删除,这一段代码都将无法实现删除的功能,且保留也只能完成单条删除,但却能按照用户的需求删除(并不是删除第一条)这点很奇怪

<?php    
    require_once 'bookmark_fns.php';  
    require_once 'user_auth_fns.php';  
    session_start();
    check_valid_user();

    $user= htmlspecialchars(trim($_SESSION['valid_user']));

    if(empty($_POST['delete'])){
        throw new Exception('you have nothing to delete');
    }
     else {
        $del_arr= array_filter($_POST['delete']);
        $cot= count($del_arr);
    }


    $conn=db_connect();
    $query="Delete from bookmark where username=? And bm_URL=?";
    $stmt=$conn->prepare($query);
    $stmt->bind_param('ss', $user,$del_arr[0]);
    $stmt->execute();

    $conn->close();

    header('location:delete_form.php');  
    ?>  

在经过网上查询资料后,发现由于预处理在绑定变量时,变量不能为数组,所以之前的代码并不能将整个数组传进去,而只能传进去里面的元素
而以下是修改后的代码,其能很好的完成批量删除这一功能,:

<?php
    require_once 'bookmark_fns.php';
    require_once 'user_auth_fns.php';
    session_start();
    check_valid_user();

    $user= htmlspecialchars(trim($_SESSION['valid_user']));

    if(empty($_POST['delete'])){
        throw new Exception('you have nothing to delete');
    }
     else {
        $del_arr= array_filter($_POST['delete']);
        $cot= count($del_arr);
    }


    $conn=db_connect();
    $query="Delete from bookmark where username=? And bm_URL=?";
    $stmt=$conn->prepare($query);
    for($i=0;$i<$cot;$i++){
        $del=$del_arr[$i];
        $stmt->bind_param('ss', $user,$del);
        $stmt->execute();
    }

    if($stmt->affected_rows!==$cot){
        throw new Exception('the operation is failed');
    }

    $conn->close();

    header('location:delete_form.php');
    ?>
文章作者: f1rry
文章链接: http://yoursite.com/2018/08/19/PHP+Mysql编写日常/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 F1rry's blog