I am developing a class for a site that has a lot of mysql querys. The idea of the class is to make it easier ans more unified. The class works but on the insert query it fills every column with the last data entry of the array.
Here is my function:
public function insert($table, $values){
$sql = "INSERT INTO ".$table." (";
$x = 0;
$vals = "";
foreach($values as $col => $val){
$sql .= ($x < (count($values) - 1)) ? $col.", " : $col." ";
$vals .= ($x < (count($values) - 1)) ? "?, " : "? ";
//$vals .= ($x < (count($values) - 1)) ? $val.", " : $val." ";
$x++;
}
$sql .= ") VALUES (".$vals.")";
$stmt = $this->db_connection->prepare($sql);
$x = 0;
foreach($values as $col => $val){
//echo 'bindParam('.($x + 1).', '.$val.', PDO::PARAM_INT);';
$stmt->bindParam(($x + 1), $val, PDO::PARAM_INT);
$x++;
}
//print_r($stmt);
$stmt->execute();
print_r($stmt->errorInfo());
}
I have echoed out the sql which shows no errors:
INSERT INTO accounts (first_name, last_name, email, address, post, country, password ) VALUES (?, ?, ?, ?, ?, ?, ? )
And also the params, which again no error:
bindParam(1, john, PDO::PARAM_INT);
bindParam(2, smith, PDO::PARAM_INT);
bindParam(3, [email protected], PDO::PARAM_INT);
and so on...
This is the outcome in the database:

I cant seem to find where I have gone wrong with this but obviously somewhere i have. I greatly appreciate the help to fix this.
And this is how the function is called:
$this->insert('accounts', array(
'first_name' => $f_name,
'last_name' => $l_name,
'email' => $email,
'address' => $address,
'post' => $zip,
'country' => $country,
'password' => $pass
));
Called for a different table:
$this->insert('newsletter', array( 'name' => $f_name.' '.$l_name, 'email' => $email )
But this one works!! //////// EDIT SOLVED ///////////////// The problem was the ->bindParam Loop, I switched it to this
public function insert($table, $values){
$sql = "INSERT INTO ".$table." (";
$x = 0;
$vals = "";
$querys = array();
foreach($values as $col => $val){
$sql .= ($x < (count($values) - 1)) ? $col.", " : $col." ";
$vals .= ($x < (count($values) - 1)) ? "?, " : "? ";
array_push($querys, $val);
$x++;
}
$sql .= ") VALUES (".$vals.")";
$stmt = $this->db_connection->prepare($sql);
for($x = 0; $x < count($querys); $x++){
$stmt->bindParam(($x + 1), $querys[$x], PDO::PARAM_INT);
}
//print_r($stmt);
$stmt->execute();
print_r($stmt->errorInfo());
}
And it was works fine, not sure why but the foreach loop was causing the error