note 17753 added to function.mysql-query
| From: | gregDELETETHIS at laundrymat dot tv | Date: | Fri, 21 Dec 2001 20:54:38 +0000 |
| Subject: | note 17753 added to function.mysql-query | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-23771@lists.php.net to get a copy of this message | ||
I wrote two handy functions that save a lot of code writing time when inserting and updating rows to
mysql.
Heres how they work:
1) You post the form to the php script, the field names you want to save must match the column names
in mysql.
2) You need to include the functions at the top of the php script.
3) If there are fields you dont want to save you define an array called $remove.
Example $remove=array('actionflag');
and the functions will ignore these values.
4) If you need to preprocces any value you must do it like so before you call the function:
$HTTP_POST_VARS[name]=strtoupper($HTTP_POST_VARS[name]);
5) Then either call the insert(tablename,DBname) function or the update(tablename,DBname) function.
The update function updates where the variable $id=the mysql row id. I usually have a hidden field
named id that stores the current mysql row id. Thus you must also have a column named id that auto
increments in the mysql table.
Example: insert('cust_info','clients');
***BELOW ARE THE FUNCTIONS********
<?php
//returns $link the result of mysql_connect
include ('./mysql_connect.php');
//must be included to prevent an error
$remove=array();
//**************INSERT FUNCTION*******
//inserts data in fields that coorisond to the submitted fields
function insert($table,$db)
{
GLOBAL $link;
GLOBAL $HTTP_POST_VARS;
GLOBAL $remove;
foreach ($HTTP_POST_VARS as $key=>$val)
{
if (! in_array($key,$remove))
{
if($p!=1)
{
$z.="$key";
$x.="'$val'";
$p=1;
}
else
{
$z.=", $key";
$x.=", '$val'";
}
}
}
$test="INSERT INTO $table ($z) VALUES ($x)";
$data_insert=mysql_db_query($db,$test, $link);
}
//********UPDATE FUNCTION**********
//updates all fields to database that are on the page where id=$id **assumes primary field called id
function update($table,$db)
{
GLOBAL $link;
GLOBAL $HTTP_POST_VARS;
GLOBAL $remove;
foreach ($HTTP_POST_VARS as $key=>$val)
{
if ( !in_array($key,$remove))
{
if($p!=1)
{
$z.="$key= '$val'";
$p=1;
}
else
{
$z.=", $key= '$val' ";
}
}
}
$test="UPDATE $table SET $z WHERE id='$HTTP_POST_VARS[id]'";
$data_insert=mysql_db_query($db,$test, $link);
}
?>
TO CALL THE FUNCTION FOLLOW THIS EXAMPLE:
$remove=array('actionflag');
insert('cust_info','clients');
thats it enjoy
--
http://www.php.net/manual/en/function.mysql-query.php
http://master.php.net/manage/user-notes.php?action=edit+17753
http://master.php.net/manage/user-notes.php?action=delete+17753
http://master.php.net/manage/user-notes.php?action=reject+17753