PHP and MySQL Tutorial

Learn how to interact with MySQL databases using PHP.

Connecting to a MySQL Database

To interact with a MySQL database, you first need to establish a connection.

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

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

// Check connection
if ($conn->connect_error) {
 die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
 

Performing CRUD Operations

Inserting Data

Use the INSERT INTO statement to add new records to your database.

$sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')";

if ($conn->query($sql) === TRUE) {
 echo "New record created successfully";
} else {
 echo "Error: " . $sql . "
" . $conn->error; }

Reading Data

Use the SELECT statement to retrieve data from your database.

$sql = "SELECT id, firstname, lastname FROM MyGuests";
$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["firstname"]. " " . $row["lastname"]. "
"; } } else { echo "0 results"; }

Updating Data

Use the UPDATE statement to modify existing records in your database.

$sql = "UPDATE MyGuests SET lastname='DoeUpdated' WHERE id=1";

if ($conn->query($sql) === TRUE) {
 echo "Record updated successfully";
} else {
 echo "Error updating record: " . $conn->error;
}
 

Deleting Data

Use the DELETE statement to delete records from your database.

$sql = "DELETE FROM MyGuests WHERE id=1";

if ($conn->query($sql) === TRUE) {
 echo "Record deleted successfully";
} else {
 echo "Error deleting record: " . $conn->error;
}
 

Try it Yourself!