使用连接类插入数据库命令的问题

时间:2019-07-19 01:36:29

标签: php class mysqli

insert into无效。

我尝试了mysqli连接,但是它不起作用。

请检查代码,然后告诉我有什么问题。

<?php
require_once "DBController.php";

class Rate extends DBController
{

function getAllPost()
{
    $query = "SELECT * FROM storedproducts";

    $postResult = $this->getDBResult($query);
    return $postResult;
}

    public function AddRating($rating, $id) {

    $query = $this->conn->prepare("insert into stored_rating ( rating , stored_id) VALUES (?,?)");
   $query->execute([$rating, $id,]);

}


public function getRateAverage($id) {
$query = $this->conn->prepare("SELECT AVG(rating) FROM `stored_rating` WHERE stored_id=?");
$params = array(
        array(
            "param_type" => "i",
            "param_value" => $id
        )
    );    
    $this->bindParams($query,$params);
    $query->->execute();
    $rsult->fetchColumn();
     return $rsult;   

}
// $query = "insert into stored_rating ( rating , stored_id) VALUES (?,?)";
//    $statement->execute([$rating, $id,]);

function updateRatingCount($rating, $id)
{
    $query = "UPDATE storedproducts SET  rating = ? WHERE ID_Stored= ?";

    $params = array(
        array(
            "param_type" => "i",
            "param_value" => $rating
        ),
        array(
            "param_type" => "i",
            "param_value" => $id
        )
    );
    this->updateDB(updateDB,$params);

    }
}

2 个答案:

答案 0 :(得分:0)

似乎需要准备,请使用prepare代替query

 public function AddRating($rating, $id) { 
   $query = $this->conn->prepare("insert into stored_rating ( rating , stored_id) VALUES (?,?)");
   $query->execute([$rating, $id,]);
}

例如:

$stmt = $mysqli->prepare("INSERT INTO myTable (name, age) VALUES (?, ?)");
$stmt->bind_param("si", $_POST['name'], $_POST['age']);
$stmt->execute();
$stmt->close();

查看: https://websitebeaver.com/prepared-statements-in-php-mysqli-to-prevent-sql-injection#insert-update-and-delete

答案 1 :(得分:0)

mysqli_statement->execute()方法不适用于数组参数,仅适用于PDO。您必须先绑定参数,然后执行。

$query = $this->conn->prepare("insert into stored_rating ( rating , stored_id) VALUES (?,?)");
if ($query) { // Remember to check for return value, sometime prepare statment return false.
    $query->bind_param("ss", $rating, $id);
    $query->execute();
}