0

I have this code for inserting in DB:

    public function insert($table,$parameters=array()){
    $param="";
    $val=array();
    $insert= str_replace(':', '', array_keys($parameters)); //remove :
    //Build Query
    $query="INSERT INTO {$this->dbinfo["prefix"]}$table";
    if(is_array($insert)){

        $query.=' (`'.implode("`,`",$insert).'`) VALUES (:'.implode(', :',$insert).')';

        $result = $this->db->prepare($query);

        foreach($parameters as $key=>$param) {
          $result->bindParam($key, $param);
        }
    }

    $result->execute();
    if($err=$this->error_message($this->db->errorInfo())) {
        $this->query=strtr($query,$parameters);
        $this->db_error=$err;
        exit;
    }
    ++$this->num_queries;
    $last_id = FALSE;
    $last_id = $this->db->lastInsertId();
return $last_id;        
}

Error handling:

private function error_message($error){
    if(!empty($error[2])){
        return $error[2];
    }
    return FALSE;
}

The call sample can look like:

$this->db->insert("log_url",array(":name"=>"url",":urlid"=>15,":type"=>0));

The example above insert in the database row filled with the last value, in this case 0. When I delete the type, it fill all with 15. Etc... Somewhere in insert function is mistake, but i cannot find it.

Any information helps. Thank you.

Maximi
  • 559
  • 5
  • 18
  • 1
    http://stackoverflow.com/q/1179874/1233508 – DCoder Jan 11 '15 at 12:29
  • Are you binding the query? – Utkarsh Dixit Jan 11 '15 at 12:30
  • @DCoder I'm not sure if I understand well. Bindvalue must be used in this case? In case security is it equivalent (Is only changing ok)? – Maximi Jan 11 '15 at 12:32
  • @Hudixt I want to do correct insert to the database and insert the data from the function. But the issue is, the last data is defined for all in cycle. – Maximi Jan 11 '15 at 12:36
  • 1
    Yes, you need to use `bindValue` in this case. See also http://stackoverflow.com/q/15154328/1233508 for another good explanation. – DCoder Jan 11 '15 at 12:41
  • @DCoder Thank you for good notice, but i think there is bigger issue. Changing to bindValue result no insert to the DB. – Maximi Jan 11 '15 at 12:45
  • 1
    `implode($insert,"`,`")` should be `implode("`,`", $insert)`. You have made this mistake twice. – Eternal1 Jan 11 '15 at 12:46
  • Your error handling code is useless, because you `exit` without logging or displaying any helpful error messages. Change it so you can see the built query, the parameters being bound, and the error message the database gives you. – DCoder Jan 11 '15 at 12:49
  • @DCoder I update me question with improved error and error function. Still no success. Maybe is the insert function still buggy. – Maximi Jan 11 '15 at 13:06
  • `$result->execute();` missing, now solved – Maximi Jan 11 '15 at 13:19

1 Answers1

-1

Answered:

Missing execute

$result->execute();
Maximi
  • 559
  • 5
  • 18