Register|Login

Have a question? Click here to ask the community.

Tutorial 5 – MySQL Select

| In: 5. Database Select | 4,810 views

Video Tutorial


Video Source Code

File: viewContacts.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php
// MySQL Tutorial 5 - Selecting Data From A Database
 
/* Syntax
SELECT columnNames FROM tableName
*/
 
include("header.php"); // include header links
include("config.php"); // connect to database
 
$result = mysql_query("SELECT * FROM contacts")
                    or die (mysql_error());
 
while ($row = mysql_fetch_array($result)) {
    echo "Name: $row[firstName] $row[lastName] <br>";
    echo "Phone Number: $row[phoneNumber] <br>";
    echo "Zip Code: $row[zipCode]";
    echo "<br><br>";
}
?>

File: header.php

1
2
3
<a href="contactForm.php">Add Contact</a> |
<a href="viewContacts.php">View Contacts</a>
<br><br><br>

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.php

1
2
3
4
5
6
7
8
9
10
11
<?php
include("header.php"); // include header links
?>
 
<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
10
11
12
<?php
 
include("header.php"); // include headers links
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.