-
Apr 08, 2008
Laziness, MySQL inserts and updates
For a while I've been using a database class I wrote a while back. Over the past ten months that I've worked at gyro I have been shortening the function names and trying to make different functions so that the things that I had to type were as small as possible. I should probably dive into a framework to do this but I haven't had the time.
So in my database class I came up with two functions for inserting and updating. They are both smaller and save me a bunch of query typing that I used to do.The functions:
<?php
// Function for inserting
function insert($table, $values) {
$query = "INSERT INTO ".$table." (" . implode(', ' , array_keys($values)) . ") VALUES (" . implode(', ' , array_values($values)) . ");";
return mysql_query($query, $this->link);
}
// Function for updating
function update($table, $values, $id) {
$updates = "";
$num = count($array);
$count = 0;
foreach($values AS $key => $value) {
$count++;
if($count == $num ) {
$updates .= $key." = ".$value." ";
} else {
$updates .= $key." = ".$value.", ";
}
}
$query = "UPDATE ".$table." SET ".$updates." WHERE id = $id;";
return mysql_query($query, $this->link);
}
?>Here is how you would use them:
<?php
//The array is set up as 'db_field_name' => 'value to insert'
$values = array(
"title" => "'".$title."'",
"pagename" => "'".$page."'",
"increment" => "'".$increment."'"
);
$db->insert("db_table_here", $values);
//For updating you do the same array and use this $db value
$db->update("db_table_here", $values, $id);
?>It's pretty simple and works pretty well for me, hope someone finds a use for it.
Posted by Mark on 04/08/2008 6:03 PM in PHP Tutorials