Trying to build a function that can insert into a SQL database regardless of how many or how few variables there are. Currently my function is not working.
function insert($table, $columns, $results){
global $dbh;
$results = explode(',',$results);
$val= '';
$ex = '';
foreach($results as $result){
$val .= ":" . $result . ",";
$ex = "':" . $result . "' => $result,";
}
$val = rtrim($val, ',');
$ex = rtrim($ex, ',');
$sql = "INSERT INTO $table ($columns) VALUES ($val)";
$q = $dbh->prepare($sql);
$q->execute(array($ex));
}
Called like this: insert('users','email,pwd,forename,surname,level,status',$vals);
Where as I managed to get it working for my Select function.
function check($table,$columns,$results){
global $dbh;
$columns = explode(',',$columns);
$results = explode(',',$results);
$whr= '';
$int = 0;
foreach($columns as $column){
$whr.= " AND " . $column . " = '{$results[$int]}'";
$int += 1;
}
$sql = "SELECT * FROM $table WHERE status != 'D' $whr";
$return = 0;
foreach($dbh->query($sql) as $check){
$return = 1;
}
return $return;
}