In this quest, you will embark on an exciting journey to learn how to build dynamic websites using PHP and MySQL. You'll start with the basics of PHP, understanding its syntax and how it integrates with HTML. As you progress, you will learn how to connect PHP with a MySQL database, enabling you to store and retrieve data effectively.
PHP or Hypertext Preprocessor is a popular scripting language designed for web development. It can be embedded into HTML code and interpreted by a web server with a PHP processor module.
Let's start by looking at the basic syntax of PHP.
<?php
// This is a single-line comment
echo "Hello, World!";
?>
MySQL is a popular open-source relational database management system. It's used in conjunction with PHP to store and retrieve data.
Follow the instructions on the official MySQL documentation to install MySQL in your local development environment.
Now that we understand the basics of PHP and have MySQL installed, let's connect PHP and MySQL.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Let's put everything together and build a simple web application.
First, we'll create a database and a table in MySQL to store our data.
CREATE DATABASE mydatabase;
USE mydatabase;
CREATE TABLE mytable (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL
);
Next, we'll use PHP to insert data into the table and retrieve it.
<?php
// Insert data
$sql = "INSERT INTO mytable (name, email) VALUES ('John Doe', 'john.doe@example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
// Retrieve data
$sql = "SELECT id, name, email FROM mytable";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";
}
} else {
echo "0 results";
}
?>
Ready to start learning? Start the quest now