Insert to a Database
How do you Insert to a Database using PHP?
Take all the following code, (both the HTML and the PHP), and paste it into a single file named 'mynewpage.php'.
Take a look at the codes now...
Yes. It's as simple as that.
First as you see in the beginning we make use of isset. This will be useful later when we want to make different things happen in this same page. You may have seen pages with more than one submit button. Like a “Write” and “Edit”. These make use of the same, but two separate, submit buttons. So here at the top of the script we call a function depending on the name of the submit button pressed by the user. It's like this:
if (isset($_POST['readme'])) {
doread();
}
All that happens here, is that we check for the button named “readme”, and if it is submitted, then we call the function “doread”.
So we made a small change in the HTML FORM;
<INPUT TYPE='submit' NAME='readme' VALUE='Okay, write to DB'>
Naming the submit button, so we then can recognize the button being clicked. Notice also that the ACTION in the now is pointing at the page itself.
Also we put all the existing PHP code into one function, that is done by putting the code inside two curly brackets. It look like so:
function doread() {
//.. all our code for this submit here ..
}
In the next blogposting I will show how to read your newly written input from the database.
HTML
<HTML><BODY>
<FORM METHOD='POST' ACTION='readmyform.php'>
<TABLE>
<TR>
<TD>Firstname: </TD>
<TD><INPUT TYPE='text' NAME='firstname'></TD>
</TR>
<TR>
<TD>Lastname: </TD>
<TD><INPUT TYPE='text' NAME='lastname'></TD>
</TR>
<TR>
<TD>Email Address: </TD>
<TD><INPUT TYPE='text' NAME='emailaddr'></TD>
</TR>
<TR>
<TD>Homepage Address: </TD>
<TD><INPUT TYPE='text' NAME='webaddr'></TD>
</TR>
<TR>
<TD></TD>
<TD><INPUT TYPE='submit' VALUE='Okay, write to DB'></TD>
</TR>
</TABLE>
</FORM>
</BODY>
</HTML>
PHP
<?php
// Here we read the inputs from the Form
$Firstname = $_POST['firstname'];
$Lastname = $_POST['lastname'];
$EmailAddr = $_POST['emailaddr'];
$WebAddr = $_POST['webaddr'];
// Now lets connect to the database
$con = mysqli_connect('127.0.0.1', 'root', 'Your_Password', 'dbname');
if (mysqli_connect_errno()) {
echo "Error connecting to DB";
}
// Here we compose the SQL string
$SQL_String = "INSERT INTO contacts (
Lastname,
Firstname,
EmailAddr,
WebAddr) VALUES (
'$Lastname',
'$Firstname',
'$EmailAddr',
'$WebAddr')";
// Execute the query – write to the DB
$dostuff = mysqli_query($con, $SQL_String);
if(! $dostuff ) {
echo 'Error in executing query';
exit();
}
mysqli_close ($con);
echo “Success, you have now written a row to your table”;
?>