I have a function addIt, which adds data to the database whatever is the name or the number of fields of the table.
this function gets the name of the table, and the fields names, and builds the string of the command, then it scans the POST variables coming from the form.
then it needs to bindParams using a statement , before execution.
foreach($data as $k=>$v){
$stmt->bindParam(':'.$result[$i],$v);
$i++;
}
$data is the table that contains all the $_POST variables. $result is the table that contains all the fields names
if title is the table field's name , then ':'.result[$i] , will be ':title', to be bound with $v (for e.g $v==$_POST['title'])
the foreach is used to repeat the same process for all variables.
but I have the problem , it's that the fields in the tables get the values of the last POST variable .
so if the form sends those variables : $_POST['title'] , $_POST['TEXTE'] , and title="hello" , texte="world"
the fields in the table will take those values : title="world", texte="world"
if you want to see a full version of the class code :
<?php
class add{
/*******************FUNCTION GET FIELDS**********************/
private function getFields($tbl){
try{
require 'global/connection.inc.php';
$cmd='DESCRIBE '.$tbl;
$fields=array();
$i=0;
foreach($pdo->query($cmd) as $r){
if ($r[0]!='views' && $r[0]!='votes'){
$fields[$i]=$r[0];
}
$i++;
}
return $fields;
}
catch(PDOException $e){}
}
/***********************FUNCTION GETDATA************************/
private function getData(){
$data=array();
$i=0;
foreach($_POST as $k){
$data[$i]=$k;
$i++;
}
return $data;
}
/**************************FUNCTION ADDIT************************/
function addIt($tbl){
require 'global/connection.inc.php';
try{
/*********create object add and get Fields names and POST data*****************/
$object=new add();
$result=$object->getFields($tbl);
$data=$object->getData();
/***************Build the sql command*****************************************/
$fields='';
$cmd='INSERT INTO '.$tbl;
$i=0;
foreach($result as $k=>$v){
if ($i<count($result)-1 && $i!=0){
$fields.=$v.',';
}
if ($i==count($result)-1){
$fields.=$v;
}
$i++;
}
$values='';
$i=0;
foreach($result as $k=>$v){
if ($i<count($result)-1 && $i!=0){
$values.=':'.$v.',';
}
if ($i==count($result)-1){
$values.=':'.$v;
}
$i++;
}
$cmd=$cmd.'('.$fields.')VALUES('.$values.')';
echo $cmd.'<br/>';
/**************************bind params and execute command******************************/
$stmt=$pdo->prepare($cmd);
$i=1;
foreach($data as $k=>$v){
$n=$v.'';
$stmt->bindParam(':'.$result[$i],$n); //The problem is here
$i++;
}
$stmt->execute();
}
catch(PDOException $e){echo $e->getMessage();}
}
}
Thank you in advance.