Build a MySQL Database Using PHP

1. Create a MySQL database:

CREATE DATABASE mydatabase;

2. Create a MySQL user and grant access to the database:

CREATE USER ‘myuser’@’localhost’ IDENTIFIED BY ‘mypassword’;

GRANT ALL PRIVILEGES ON mydatabase.* TO ‘myuser’@’localhost’;

3. Create a PHP file and establish a connection to the MySQL database:

<?php

$servername = “localhost”;

$username = “myuser”;

$password = “mypassword”;

$dbname = “mydatabase”;

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {

die(“Connection failed: ” . $conn->connect_error);

}

echo “Connected successfully”;

?>

4. Create a table in the database:

CREATE TABLE users (

id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,

firstname VARCHAR(30) NOT NULL,

lastname VARCHAR(30) NOT NULL,

email VARCHAR(50),

reg_date TIMESTAMP

);

5. Insert data into the table:

INSERT INTO users (firstname, lastname, email)

VALUES (‘John’, ‘Doe’, ‘john@example.com’);

6. Retrieve data from the table:

SELECT * FROM users;

7. Close the connection:

$conn->close();

No comments yet.

Leave a comment

Request a Free SEO Quote