Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

handy script for updating and inserting tables

Status
Not open for further replies.

hos2

Programmer
May 6, 2002
418
NL
Since I'm programming a lot with mysql and php I got tired of changing 2 or 3 pages when I wanted to add a field. So at least for the insert and update statements I don't have to change anything anymore. I only have to add a field in the database and add it to the form.

this example will only work for a htmlform which will affect only 1 table. the names of the fields in the htmlform must be the same as the fieldnames in your table.

Code:
sqlaction.php3
<?php 
include $DOCUMENT_ROOT.&quot;/cgi-bin/connopen.php3&quot;;

// the key is passed through the url with the name of the keyfield
list($tablekey, $keyvalue) = each($HTTP_GET_VARS);


//array for attaching the keynames to the corresponding tablenames fill in your own table names and keyfields
$tablearray=array();
$tablearray[arid]='artisttable';
$tablearray[clid]='clienttable';
$tablearray[orid]='ordertable';
$tablearray[orlid]='orderlinestable';


//loop through the posted variables
//formfieldnames must be corresponding to tablefieldnames

while ( list($field, $value) = each ($HTTP_POST_VARS)) {
	if ($field <> &quot;Submit&quot; ){
	$fieldlines=$fieldlines .$field .&quot;='&quot; .$value .&quot;',&quot;;
	}
    }

$fieldlines=substr($fieldlines,0,strlen($fieldlines)-1); // get rid of the last ,


if (!empty($keyvalue)) //if no key in the url then consider it an insert statement 
	{
	$query=&quot;UPDATE &quot; . $tablearray[$tablekey] .&quot; SET &quot; . $fieldlines . &quot; WHERE &quot; . $tablekey .&quot;='$keyvalue'&quot;;
	}
	else
	{
	$query=&quot;INSERT INTO &quot; . $tablearray[$tablekey] . &quot; SET &quot;. $fieldlines;
	}

$rs=mysql_query($query,$conn);	

print (&quot;
<html><body><table>
<tr><td>$query<br></td></tr> 
</table>
</BODY>
</HTML>
&quot;);
mysql_close($conn);
?>

so if I want to update the artisttable the action would be
sqlaction.php3?arid=7

ps (!empty($keyvalue)) statement and method for having update and insert statements in one page is copied from o'reillys web database applications book page 334
and the code is here stripped to a minimum but working
 
You may also want to check out MyPHPAdmin. I use it alot. It s very helpfull, and best of all... FREE!

Thank you!!!

Mike Kovacic

&quot;&quot;&quot; &quot;&quot;&quot;
(o) (O)
\____/
 
is that something else than phpmyadmin ???
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top