I make 2 function with same use to take over PDO Preapred Statement, but both of not work .
Function 1 :
function doSave($array, $table) {
if (count($array) == 0) {
throw new Exception('Array cant be empty');
} else {
global $connect;
//prepare the query first
$prepare_1 = 'INSERT INTO' . ' ' . $table . ' '; //start preparing
$columns = array();
foreach ($array as $key => $value) {
$columns[] = ':' . $key; //gets all columns and add commas
}
foreach ($array as $key => $value) {
$keye[] = $key; //gets all columns and add commas
}
$keyes = implode(', ', $keye);
$column = implode(', ', $columns);
//now you can combine everything and prepare
$stmt99 = $connect->prepare($prepare_1 .'('.$keyes.')'. ' VALUES (' . $column . ')');
//remember to add the values. also test this section as its not tested
foreach ($array as $key => $value) {
$test[] = "':" . $key ."' => ". $value;
}
$tests = implode(', ', $test);
$stmt99->execute($tests);
}
}
When i insert the data i got no error and no data get insert to my database
Function 2 :
function doSave($array, $table) {
if (count($array) == 0) {
throw new Exception('Array cant be empty');
} else {
global $connect;
//prepare the query first
$prepare_1 = 'INSERT INTO' . ' ' . $table . ' '; //start preparing
$columns = array();
foreach ($array as $key => $value) {
$columns[] = ':' . $key; //gets all columns and add commas
}
foreach ($array as $key => $value) {
$keye[] = $key; //gets all columns and add commas
}
$keyes = implode(', ', $keye);
$column = implode(', ', $columns);
//now you can combine everything and prepare
$stmt99 = $connect->prepare($prepare_1 .'('.$keyes.')'. ' VALUES (' . $column . ')');
//remember to add the values. also test this section as its not tested
foreach ($array as $key => $value) {
$test[] = '$stmt99->bindparam('.'":' . $key .'",'. $value.'); ';
}
$tests = implode(' ', $test);
$tests;
$stmt99->execute();
}
}
i got error when use this function :
SQLSTATE[HY093]: Invalid parameter number: no parameters were bound
This How i use the function :
$array = array('categoryName' => $categoryName, 'categorySort' => $categorySort);
doSave($array, 'category');
This the source of the array :
if (!empty($_POST["categoryName"])) {
$categoryName = ($_POST["categoryName"]);
if (!preg_match("/^[a-zA-Z ]*$/",$categoryName)) {
$errMsg = "<div class='alert alert-danger text-center'><strong>Hanya boleh huruf.</strong></div>";
}
}
if ($_POST["categorySort"] == $check['categorySort']) {
$errMsg = "<div class='alert alert-danger text-center'><strong>Urutan sudah digunakan.</strong></div>";
}else{
$categorySort = ($_POST["categorySort"]);
if (!is_numeric($_POST['categorySort'])) {
$errMsg = "<div class='alert alert-danger text-center'><strong>Hanya boleh angka.</strong></div>";
}
}
What possibly go wrong from this 2 function both function for same use. Function 1 (named param) Function 2 (bindparam) ?