Created
June 5, 2013 05:07
-
-
Save hidayat365/5711738 to your computer and use it in GitHub Desktop.
dbInsert Helper. Contoh penggunaan array untuk men-generate INSERT statement sehingga kita tidak perlu membuat INSERT statement secara manual
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// database connection parameters | |
$db_host = 'localhost'; | |
$db_port = 5432; | |
$db_name = 'db_name'; | |
$db_user = 'postgres'; | |
$db_pass = '*****'; | |
// try connecting to database | |
$conn_string = "host=$db_host port=$db_port dbname=$db_name user=$db_user password=$db_pass"; | |
$db_conn= pg_pconnect($conn_string) or die(ErrorMessage('Database Offline!')); | |
// insert parameters | |
$table_name = "users_calls"; | |
$value_array = array( | |
"id" => $users_call_id, | |
"user_id" => $_SESSION["user"]["id"], | |
"created_on" => date("Y-m-d"), | |
"updated_on" => date("Y-m-d"), | |
"created_by" => $_SESSION["user"]["id"], | |
"updated_by" => $_SESSION["user"]["id"], | |
"active" => 0, | |
"attempted_call" => 0 | |
); | |
// insert to table users_calls | |
dbInsertRow($db_conn,$value_array,$table_name); | |
/* | |
* Database Query helper | |
*/ | |
function dbQuery($dbconn,$sql) { | |
$rs = pg_query($dbconn,$sql); | |
return $rs; | |
} | |
/* | |
* Insert function helper | |
*/ | |
function dbInsertRow($dbconn,&$value_array,$table_name) { | |
$columns_list = ''; | |
$values_list = ''; | |
$delimiter = ''; | |
foreach ($value_array as $key=>$value) { | |
$columns_list .= $delimiter.$key; | |
if ($value === 0) { | |
$values_list .= $delimiter."0"; | |
} else if ($value != "") { | |
$value = str_replace("'","",$value); | |
$values_list .= $delimiter."'".$value."'"; | |
} else | |
$values_list .= $delimiter."null"; | |
$delimiter = ","; | |
} | |
$query = 'INSERT INTO '.$table_name.' ('.$columns_list.') VALUES ('.$values_list.')'; | |
$result = dbQuery($dbconn,$query); | |
if (!$result) { | |
LogAction("Inserting FAILED with query ==> ".$query); | |
LogAction("Inserting FAILED with message ==> ".dbGetError($dbconn).""); | |
} | |
return $result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment