WeberDev.com PHP and MySQL Code

LOG IN
BEGINNER GUIDES  |  PHP CLASSES  |  CODE SEARCH  |  ARTICLES SEARCH  |  PHP FORUMS  |  PHP MANUAL  |  PHP FUNCTIONS LIST  |  WEB SITE TEMPLATES
Start typing to search for PHP and MySQL Code Snippets and Articles Search
Submit a code Example / Snippet Submit Your Code
Search Engine Optimization Monitor SEO Monitor
Web Site UpTime Monitor UpTime Monitor
WeberDev's Monthly code contest PHP Code Contest
Your Personal Examples List My Favorite Examples
Your Personal Articles List My Favorite Articles
Edit Account Info Update Your Profile
PHP Code Search
Web Development Forums
Learn MySQL Playing Trivia
PHPBB2 Templates
Web Development Index
PHP Web Logs (BLogs)
Web Development Resources
Web Development Content
PHPClasses
PHP Editor
PHP Jobs
Vision.To Design
Ajax Tutorials
PHP Programming Help
PHP/MySQL Programming
Webmaster Resources
Webmaster Forum
XML meta language
website builder
Submit Site
Forex Trading Online forex trading platform

Go Back Add a Comment Send this example to a friend Add this Article to your personal favoritest for easy future access to your favorite Code Examples and Articles. Submit a code example Print this code example.
BACK ADD A COMMENT SEND TO A FRIEND ADD TO MY FAVORITES ADD CODE EXAMPLES PRINT
Title : Add, Edit & Update All in one Contact Management Form
Categories : PHP, MySQL, Databases Click here to Update Your Picture
bastien koert
Date : Feb 26th 2005
Grade : 4 of 5 (graded 4 times)
Viewed : 8316
File : No file for this code example.
Images : No Images for this code example.
Search : More code by bastien koert
Action : Grade This Code Example
Tools : My Examples List

  Submit your own code examples 
 

Here is a fun example on how to use functions to squeeze the most out of one page. This page lists users, adds users and edits users.

Enjoy...

Bastien

  CREATE TABLE `kids` (
  `id` int(10) NOT NULL auto_increment,
  `first_name` varchar(30) NOT NULL default '',
  `last_name` varchar(50) NOT NULL default '',
  `email` varchar(75) default NULL,
  `contact_status` tinyint(1) NOT NULL default '0',
  PRIMARY KEY  (`id`)
) TYPE=MyISAM  ;


<html>
<head>
<title>Manage contact's data</title>
</head>
<body>
<?php
/*************************************************************************
               control code for application
*************************************************************************/

//submit button was pressed so call the process form function
if (isset($_POST['submit']))
{
 
process_form();
  die();
}
//end if


//call the get_data function
if (isset($_GET['id']))
{
 
get_data();
}
//endif


//nothing chosen so list the kids
if ((empty($_POST))&&(empty($_GET)))
{
 
list_users();
  die();
}
//end if


//request to add a new contact so call the show_form function
if ((isset($_GET['action']))&&($_GET['action']=='add'))
{
 
show_form();
}
//endif



/*************************************************************************
               get the data for an individual contact
*************************************************************************/

function get_data()
{
   
//validate the id has been passed at that it is a number
   
if ((empty($_GET['id']))||(is_nan($_GET['id'])))
    {
       
//there was a problem so list the users again
     
list_users();
     
//kill the script
     
die();
    }else{
     
//all is ok and assign the data to a local variable
     
$id = $_GET['id'];
    }
//end if
   
$sql = "select * from contacts where id = $id";
   
$result = conn($sql);
    if (
mysql_num_rows($result)==1){
     
//call the form and pass it the handle to the resultset
     
show_form($result);
    }else{
     
$msg = "No data found for selected contact";
     
confirm($msg);
     
//call the list users function
     
list_users();
    }
//end if 
}//end function


/*************************************************************************
               show the input / edit form
*************************************************************************/
function show_form($handle='',$data='')
{
 
//$handle is the link to the resultset, the ='' means that the handle can be empty / null so if nothing is picked it won't blow up
 
  //set default values
 
$first_name = '';
 
$last_name  = '';
 
$email      = '';
 
$status     = '';
 
$id         = '';
 
$value      = 'Add'//submit button value
 
$action     = 'add'//default form action is to add a new kid to db

  //set the action based on what the user wants to do
 
if ($handle)
  {
   
//set form values for button and action
   
$action = "edit";
   
$value  = "Update";
   
   
//get the values from the db resultset
   
$row = mysql_fetch_array($handle);
   
$first_name = $row['first_name'];
   
$last_name  = $row['last_name'];
   
$email      = $row['email'];
   
$status     = $row['contact_status'];
   
$id         = $row['id'];
 
  }
//end if
 
  //error handling from the processing form function
 
if($data != '')
  {
   
$elements = explode("|",$data);
       
$first_name     = $elements[0];
       
$last_name      = $elements[1];
       
$email          = $elements[2];
       
$id             = $elements[3];
  }
?>
    <body>
    <form name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>?action=<?php  echo $action?>">
    <table width="400" align="center" border="0" cellspacing="0" cellpadding="0">
      <tr>
          <td colspan="2" align="center" style="font-size:18px; font-weight:bold;">Manage Contact's Data Form</td>
          <input type="hidden" value="<?php echo $id?>" name="id">
      </tr>
      <tr>
        <td> </td>
        <td> </td>
      </tr>
      <tr>
        <td align="right">First Name: </td>
        <td><input name="first_name" type="text" value="<?php echo $first_name?>"> </td>
      </tr>
      <tr>
       <td align="right">Last Name: </td>
       <td><input name="last_name" type="text" value="<?php echo $last_name?>"> </td>
      </tr>
      <tr>
        <td align="right">Email Address: </td>
        <td><input name="email" type="text" value="<?php echo $email?>"> </td>
      </tr>
      <tr>
        <td align="right">Stop Contact? </td>
        <td><input name="status" type="checkbox" value="1" <?php if ($status==1){ echo " checked=CHECKED "; } ?>> </td>
      </tr>
      <tr>
        <td> </td>
        <td> </td>
      </tr>
      <tr>
        <td colspan="2" align="center"><input name="submit" type="submit" value="<?php echo $value?>"> <input name="reset" type="reset" value="Clear Form"></td>
      </tr>
    </table>
   
    </form>
    </body>

<?
}//end function


/*************************************************************************
               list all the contacts in the db
*************************************************************************/
function list_users()
{
   
$y = 0; //counter
   
   
$sql = "select * from contacts "//may want to add the option where clause to only take kids with an active status
   
$result = conn($sql);
 
  echo
"<table width='400' align='center' cellpadding='0' cellspacing='0'>
        <tr><td colspan='2' align='center' style='font-size:18px; font-weight:bold;'>Manage Contacts Data Form</td></tr>
        <tr><td colspan='2'> </td></tr>
        <tr><td colspan='2'><a href='"
.$_SERVER['PHP_SELF']."?action=add'>Add a new contact</a></td></tr>
        <tr><td colspan='2'> </td></tr>"
;
       
     if (
mysql_num_rows($result)){
     
//show a list of kids with name as a link to the prepopulated form with their data in it
     
while($rows = mysql_fetch_array($result)){
       
       
//change row background color
       
(($y % 2) == 0) ? $bgcolor = "#8FBC8F" : $bgcolor=" #9ACD32";
       
       
//build strings to make life easier
       
$name   = $rows['first_name'].' '.$rows['last_name'];
       
$status = $rows['contact_status'];
       
$id     = $rows['id'];
       
       
//convert status to readable string from 1 or 0
       
($status == 0) ? $status = "Available to contact" : $status = "Do not contact at present.";
       
       
//echo out the row
       
echo "<tr style='background-color:$bgcolor;'><td><a href='".$_SERVER['PHP_SELF']."?id=$id'>$name</a></td><td>$status</td><tr>";
       
$y++;  //increment the counter
     
}//end while
     
echo "</table>";
  }else{
   
//handle no results
   
echo "<tr><td colspan='2' align='center'><b>No data found.</b></td></tr>";
  }
//endif
}


/*************************************************************************
               add / update the contact's data
*************************************************************************/
function process_form()
{
 
$fname  = '';
 
$lname  = '';
 
$email  = '';
 
$id     = '';
 
$action = '';
 
$status = 0;    //default value

 
$fname  = @$_POST['first_name'];
 
$lname  = @$_POST['last_name']; 
 
$email  = @$_POST['email'];     
 
$id     = @$_POST['id'];         
 
$action = @$_GET['action'];
 
$status = @$_POST['status'];
 
 
//if no status is set, defaults to 0 (allow contact)
 
if ($status == ''){$status = 0; }
   
  if ((
$fname=='')||($lname=='')||($email==''))
  {
   
$msg = "Some data from the form was forgotten. Please fill in the entire form.";
   
confirm($msg);
   
$data = "$fname|$lname|$email|$id";
   
show_form('',$data);
    die();
  }
//end if
 
  //You could add some validation of the data ( I recommend it and its a great way to get your feet wet with php )


 
if ($action == "add")
  {
   
$sql = "insert into contacts (first_name, last_name, email, contact_status) values('$fname','$lname','$email',$status)";
   
$msg = "Record successfully added";
  }elseif(
$action=="edit"){
   
$sql = "update contacts set first_name = '$fname', last_name = '$lname', email = '$fname', contact_status = '$status' where id = $id";
   
$msg = "Record successfully updated";
  }
 
$result = conn($sql);
  if (
mysql_errno()==0)
  {
   
confirm($msg);
   
list_users();
  }else{
   
$msg = "There was a problem adding the user to the database. Error is:".mysql_error();
   
confirm($mag);
  }
//end if
     
}


/*************************************************************************
               db connection function
*************************************************************************/
function conn($sql)
{   

$host = "localhost";
$user = "user";
$pass = "pass";
$db     = "my_db";


   
//echo "commnecing connection to local db<br>";
   
   
if (!($conn=mysql_connect($host, $user, $pass)))  {
       
printf("error connecting to DB by user = $user and pwd=$pass");
        exit;
    }
   
$db3=mysql_select_db($db,$conn) or die("Unable to connect to local database");

   
$result = mysql_query($sql) or die ("Can't run query because ". mysql_error());
   
    return
$result;
   
}
//end function     

/*************************************************************************
               alert box popup confimation message function
*************************************************************************/
function confirm($msg)
{
  echo
"<script langauge=\"javascript\">alert(\"".$msg."\");</script>";
}
//end function

?>



This program allows you to upload an ODBC ressource - i.e. an MS-Access database to a MySQL server.
Categories : Databases, MySQL, Complete Programs, PHP, Databases
bookmarker - PHP, PHPLIB, MySQL WWW based bookmark manager
Categories : MySQL, PHP, MySQL, Complete Programs, Databases
Accepts a database & hostname from a user and then HTTP username and password. Uses this to connect to a MySQL database. Produces a form based on the tables it finds there to allow the user to do SELECTs, INSERTs, and DELETEs.
Categories : Databases, PHP, MySQL, Complete Programs
phpAds, a complete banner and ad management system with detailled tracking and stats.
Categories : MySQL, Complete Programs, Ecommerce, PHP, Databases
Point and Click Interface ala MS Access for creating SQL statements.
Categories : MySQL, Complete Programs, General SQL, PHP, Databases
Message of the Day - Random Message (Needs MySQL!)
Categories : Databases, HTML and PHP, PHP, MySQL
email new items in db
Categories : PHP, Email, Databases, MySQL, Beginner Guides
Alternating background color for HTML table rows
Categories : PHP, Databases, MySQL, HTML and PHP
color codes for positive and negative numbers
Categories : PHP, MySQL, Databases, HTML
Authorize Me! An authentication script.
Categories : MySQL, Databases, Authentication, PHP
A very simple way to build and do a hierarchical html categories browser without javascript , just using html php and mySql
Categories : HTML and PHP, Databases, Algorithms, PHP, MySQL
Linked comboboxes with php-mysql & javascript
Categories : PHP, Java Script, Databases, MySQL
mysql_escape_string
Categories : PHP, MySQL, Databases, Strings
Automatically printing the contents of an sql table in MySQL.
Categories : MySQL, PHP, HTML and PHP, Databases
usercounter class
Categories : PHP, PHP Classes, Databases, MySQL, Environment Variables
 Urb LeJeune wrote : 1280
Replace:
    $first_name = $row[`first_name`]; 
    $last_name  = $row[`last_name`]; 
    $email      = $row[`email`]; 
    $status     = $row[`contact_status`]; 
    $id         = $row[`id`]; 

with extract($row);

Urb
 
 Marcus King wrote :1281
thanks for this script.  it works great for me....someone with about 4 weeks of php/mysql skills.