如何从简单的mysqli查询更改为准备好的语句?

时间:2019-07-11 19:06:36

标签: php mysqli prepared-statement

我进行了3次查询(SELECT,INSERT,UPDATE),但是它在当前状态下看起来很丑且不安全。

有什么方法可以通过准备好的语句使这些SELECT,INSERT,UPDATE查询更具可读性和安全性吗?

    $email = $_SESSION['email'];
    $query = "SELECT username FROM users WHERE email='$email'";
    $result = mysqli_query($connect, $query);
    $row = mysqli_fetch_assoc($result);
    $username = $row['username'];

    if(!empty($_POST["comment"])){
    $id = $_GET['id'];
    $sql = "INSERT INTO user_comments (parent_id, comment, username, custom_id) VALUES ('".$_POST["commentID"]."', '".$_POST["comment"]."', '$username', '$id')";
    mysqli_query($connect, $sql) or die("ERROR: ". mysqli_error($connect));

    /// I need this update query to make every inserted comment's ID +1 or can I do this more simple?
    $sql1 = "UPDATE user_comments SET id = id +1 WHERE custom_id = '$id'";
    mysqli_query($connect, $sql1) or die("ERROR: ". mysqli_error($connect));

1 个答案:

答案 0 :(得分:-1)

尝试一下。您可以使用$ex->insert_id来获取last entered ID。当大量插入数据库时​​,这可能会派上用场。我通常使用PDO,因为我发现代码看起来更简洁,但我认为这是我的全部偏好。请记住,->bind_param所指的"isii"行是指您输入的数据类型。因此,在这种情况下,其Integer, String, Integer, Integer(我可能错了)。

$email    = $_SESSION['email'];
$query    = "SELECT username FROM users WHERE email='$email'";
$result   = mysqli_query($connect, $query);
$row      = mysqli_fetch_assoc($result);
$username = $row['username'];

if(!empty($_POST["comment"])){
$id        = $_GET['id'];
$commentID = $_POST["commentID"];
$comment   = $_POST["comment"];

$sql = "INSERT INTO user_comments (parent_id, comment, username, custom_id) VALUES (?, ?, ?, ?)";
$ex  = $connect->prepare($sql);
$ex->bind_param("isii", $commentID, $comment, $username, $id);

if($ex->execute()){
    // query success
    // I need this update query to make every inserted comment's ID +1 or can I do this more simple?

    $lastInsertID = $ex->insert_id;

    $sql1 = "UPDATE user_comments SET id = id + 1 WHERE custom_id = ?";
    $ex1  = $connect->prepare($sql1);
    $ex1->bind_param("i",$lastInsertID);
    if($ex1->execute()){
        // query success
    }else{
        // query failed
        error_log($connect->error);
    }
}else{
    //query failed
    error_log($connect->error);
}