I am working a personal project to learn OOP. I created this generic method to do an insert to a table, but I could not. $dbAttributes
is a list of fields in the table without the id. I pass an object instance, for example, product with properties set such as category_id,product_name, price. The problem comes when I try to bind the values using foreach loop.
I get errors:
SQLSTATE[HY000]: General error: 1366 Incorrect integer value
then after I removed single quote from the placeholder I get:
SQLSTATE[42000]: Syntax error or access violation: 1064
public static function create($obj) {
global $db;
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$dbAttributes = $obj->db_fields;
$colonValues = array();
for($i=0;$i<count(array_values($dbAttributes));$i++){
$colonValues[] = ':'.$dbAttributes[$i];
}
$sql ="INSERT INTO ".$obj::$tableName."(";
$sql .=join(",", array_values($dbAttributes));
$sql .= ") VALUES('";
$sql .= join("','",array_values($colonValues));
$sql .= "')";
try {
$stmt = $db->prepare($sql);
foreach($colonValues as $k=>$value){
$rs = $obj->$dbAttributes[$k];
//if($k!=0){
$stmt->bindParam($value, $rs);
echo gettype($rs)." ". $rs."<br>";//}
}
var_dump($sql);
$numRowsAffected = $db->exec($sql);
} catch (Exception $ex) {
echo $ex->getMessage();
}
}
As you see I am trying to dynamically create SQL and also dynamically bind values. I tried everything and I also read the forum on using back-ticks for table names, it did not solve the problem.