Inserting data using PHP

From Hashmysql
Jump to: navigation, search

This example uses two files. The first is a simple html form which requests the data and then loads the php file. A neater way is to put it all in one file and make the submit action be to call itself but putting it in two files probably makes it easier to see what is going on. It assumes that you have created a database along the lines of Basic SQL Statements, the same as in PHP Tutorial.

Input Form

This a basic html form. When Submit is pressed, the values of name and id are sent to

<html>
 <head>
  <title>simple form example</title>
 </head>
 <body>
  <form action="action.php" method="post">
   <p>First Name <input type="text" name="name" /></p>
   <p>Id <input type="text" name="id" /></p>
   <p><input type="submit" /></p>
  </form>
 </body>
</html>

the PHP file

Save the following as "action.php". It will be called when the submit button of the form is clicked.

The actual query is in inserted into the string variable $query. This should only have one mysql query and does not end in a semicolon. This is passed to mysql_query which interacts with the mysql server itself.

 <?php
    $id = $_POST['id'];
    $name = $_POST['name'];
    $myuser = 'myuser';//change this
    $mypass = 'mypass';//change this
    $mydb = 'mydb';
    $link = mysql_connect('localhost',$myuser,$mypass);
     
    // If there was an error report the error.
    if(!$link) {
     die('Could not connect to the database: ' . mysql_error());
    }
    
    echo "if we got this far then we've logged on .. <br>";
     
    $db = mysql_select_db($mydb,$link);
 
    // Report any error with DB selection here.
    if(!$db) {
     die ('Could not use the test db because: ' . mysql_error());
    } 
    echo "We have selected the database.. <br>";
   
    // Print out the contents of the rows line by line. 
    // you can switch assoc, with array if you don't know the names of the fields.    
   $query = "INSERT INTO mytable ";
   $query .= "VALUES($id,'$name')";//note the single quotes round $name
   if(!mysql_query($query, $link)){
    die ('Could not insert name into database because: ' . mysql_error());
   }
   //if we'v got this far we can assume that the record has been inserted
   print("successfully added new name to the mySQL database!<br>"); 
 ?>

External Links

Forms are not php but basic html. They can get quite sophisticated though. Here are a few links to get you started: