Register|Login

Have a question? Click here to ask the community.

Tutorial 4 – MySQL Insert

| In: 4. Database Insert | 8,540 views

Video Tutorial


Video Source Code

File: index.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
// MySQL Tutorial 4 - Inserting Data Into A Database
 
/* Syntax:
INSERT INTO tableName (field1, field2, field3, ...)
VALUES (value1, value2, value3, ...)
*/
 
include("config.php"); // connect to database
 
mysql_query("INSERT INTO contacts (firstName, lastName, phoneNumber, zipCode)
VALUES ('Tom', 'Green', '5559870123', 40344)")
    or die('Could not add new contact');
 
echo "New Contact Added";
 
?>

File: config.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
// MySQL Tutorial 3 - Connecting To A Database
 
// CREATE CONNECTION TO DATABASE
 
$user = "root";
$pass = "";
$database = "phoneBook";
$server = "localhost";
 
// Syntax: mysql_connect("servername","username","password");
$connect = mysql_connect($server, $user, $pass)
                or die ('Connection To Server Failed');
 
// Syntax: mysql_select_db("databaseName", $connect);
mysql_select_db("$database", $connect)
                or die ('Connection To Database Failed');
 
// CLOSE CONNECTION
//mysql_close($connect);
?>

File: contactForm.html

1
2
3
4
5
6
7
<form action="addContact.php" method="post">
First Name: <input type="text" name="firstName">
Last Name: <input type="text" name="lastName">
Phone Number: <input type="text" name="phoneNumber">
Zip Code: <input type="text" name="zipCode">
<input type="submit">
</form>

File: addContact.php

1
2
3
4
5
6
7
8
9
<?php
include("config.php"); // connect to database
 
mysql_query("INSERT INTO contacts (firstName, lastName, phoneNumber, zipCode)
VALUES ('$_POST[firstName]', '$_POST[lastName]', '$_POST[phoneNumber]', $_POST[zipCode])")
    or die(mysql_error());
 
echo "New Contact Added";
?>

Comment Form

You must be logged in to post a comment.