php – CodeIgniter Call to undefined method prepare-ThrowExceptions

Exception or error:

I am very new to CI framework . I am working on a project and everything goes well until I try to edit a row in the db with a form. I get this error

Message: Call to undefined method CI_DB_mysqli_driver::prepare()

Here is my code in my controller.

  public function edit($id) {
    $alimente = $this->db->query('select alimente.id, alimente.name FROM alimente  WHERE id = "' . $id . '" order by name desc')->result();
    $content = $this->parser->parse('alimente/edit_alimente', array("ALIMENTE" => $alimente), true);
    $TITLE = "Modifica";
    $array = array('TITLE' => $TITLE, 'CONTENT' => $content);
    $this->parser->parse('TEST', $array, false);
}

public function edit_done() {
    $name = $this->input->post("name");
    $id = $this->input->post("id");

    $query = $this->db->prepare("update alimente set name = '" . $name . "' where id = '" . $id . "'")->result();
    $query->execute($name, $id);

    redirect("alimente");

And here is my view file

<form method="post" action="{SITE_URL}/alimente/edit_done">

    <div class="form-group">

        {ALIMENTE}    
        <label> Id aliment</label>
        <input type="text" name="id" value= "{id}" readonly="true"class="form-control" />
        <label> Nume aliment</label>
        <input type="text" name="name" value= "{name}" class="form-control" />
        <br>
        {/ALIMENTE}
    </div>

    <input type="submit" value="Modifica" name=" modifica" class="btn btn-primary" /> 

</form>

If I change prepare to query the end result is a boolean but the edit happens, I get this error message

Message: Call to a member function result() on boolean

How to solve:

Since CodeIgniter does not support prepared statements, you could modify your code like this to use the PDO object to run your prepared statements :

public function edit_done() {
    $name = $this->input->post("name");
    $id = $this->input->post("id");

    $query = $this->db->conn_id->prepare('update alimente set name = ? where id = ?');
    $query->execute($name, $id);

    redirect("alimente");

Leave a Reply

Your email address will not be published. Required fields are marked *