Now that the database has been set, we will start to write our form source code and PHP scripts. Let us start with our basic form. We will name this form.htm. <html> <head> <title>Enter your name</title> </head> <body> Enter your name and we will assign a random number from 1 to 10 to be stored in our database. <br /><br /> <form action="generaterandom.php" method="post"> Name <input type="text" name="user" size="30"> <br /> <input type="submit" value="Submit your name"> </form> </body> </html> After a user presses “Submit your name,” a PHP script named “generaterandom.php” will generate a random number from 1 to 10 and store that number along with the name in the MySQL database. For the PHP script of generaterandom.php, the following is the flow of information: <?php //Step 1: PHP will connect to the database //Using the information we set above. //In this illustration, it uses an XAMPP local host //However this can be applied to any types of Apache based servers running PHP. $username = "root"; $password = "xxxxx"; $hostname = "localhost"; $database = "randomnumber"; $dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL"); $selected = mysql_select_db($database,$dbhandle) or die("Could not select $database"); //Step 2: PHP will generate a random number from 1 to 10. //We will incorporate the previous script but we will change the minimum and maximum. $randomnumber = mt_rand(1,10); //Step 3: We will extract the name on the form, but first we have to check if the user did not provide a blank or empty data. $data=trim($_POST['user']); if (strlen($data)==0) { die('You forget to enter your name, please press the back button of your browser'); } else { $name = $data; }
//Step 4: Sanitize data before storing it in database. $name = mysql_real_escape_string($name); $randomnumber = mysql_real_escape_string($randomnumber); //Step 5: Insert both data into the database. mysql_query("INSERT INTO `randgenerated` (`name`,`random`) VALUES('$name','$randomnumber')") or die(mysql_error()); //Storing of data is complete. Give feedback to the user. echo 'Storing of data is complete.'; echo '<br />'; echo '<a href="http://localhost/form.htm">Click here to input data again.</a>'; //Step 6: Close the database connections mysql_close($dbhandle); ?>
blog comments powered by Disqus |
|
|
|
|
|
|
|