PHP Insert Row into Database Function Script
Written on Monday July 16th 2007 at 12:20 pm
Hey programmers! I know some of you visit my site, and a few have asked me the best way to insert a row into a database. Well, here is a function that I created in just a few minutes. It is very simple, all you need is to create an array that has the keys and corresponding values of the database you want to insert the row in. The code is below, and I also included an example of the array.
Here is the function code, feel free to change it as needed.
This is how you would use it...
Happy coding!
Here is the function code, feel free to change it as needed.
function insertRow($table,$array){
foreach($array as $key => $value){
$string1 .= "".addslashes($key).", ";
$string2 .= "'".addslashes($value)."', ";
}
$preString = "INSERT INTO $table ($string1) VALUES ($string2)";
$postString = str_replace(")", ")", $preString);
$insert = "".$postString."";
if($add = mysql_query($insert)){
return true;
}else{
return false;
}
}
This is how you would use it...
$fields = array(
"user_login" => $_POST['user_login'],
"user_pass" => $_POST['user_pass'],
);
if(insertRow('tableName', $array)){
echo "Database Query executed successfully";
}else{
echo "Error, please try again";
}
Happy coding!
1 Comment
On Tuesday July 24th 2007 at 6:22 pm Guest said
Flippin' sweet
Add a comment or Login
Recent Blog Posts
- Join me on Blog Action Day to end Poverty
- PHP CSS Compressor
- Jack Nicholson was pushing for hydrogen cars in the 70s
- Bill Gates Retires Today
- New Weezer Video!
- Homer Simpson Written in CSS
- Dr. Martin Luther King Jr.
- Digg Justice / Xbox Moron
- Microsoft + Open Source ??
- New Facebook Application
Guest