Labs ICT
โญ Pro Login

MySQL Queries

Once you have a database connection, you can start running queries. The big four are SELECT (read data), INSERT (add data), UPDATE (change data), and DELETE (remove data). Together they're called CRUD โ€” Create, Read, Update, Delete. Every web app you've ever used is basically just CRUD operations.

SELECT โ€” Reading Data

Use mysqli_query() to run a query. For SELECT queries, it returns a result object. You can then fetch rows one at a time with fetch_assoc() (returns an associative array) or all at once with fetch_all().

<?php
$result = mysqli_query($conn, "SELECT * FROM users");
while ($row = mysqli_fetch_assoc($result)) {
    echo $row["name"] . " - " . $row["email"];
}
?>
Try it Yourself โ†’

INSERT โ€” Adding Data

INSERT adds a new row to your table. Use mysqli_query() again, but this time it returns true on success or false on failure. You can get the ID of the newly inserted row with mysqli_insert_id().

<?php
$sql = "INSERT INTO users (name, email) VALUES ('John', 'john@example.com')";
if (mysqli_query($conn, $sql)) {
    echo "New record created. ID: " . mysqli_insert_id($conn);
} else {
    echo "Error: " . mysqli_error($conn);
}
?>
Try it Yourself โ†’

UPDATE and DELETE

UPDATE changes existing rows. Always use a WHERE clause unless you want to update every single row. DELETE removes rows โ€” same warning about WHERE applies. Without it, you'll wipe the entire table.

<?php
mysqli_query($conn, "UPDATE users SET email='new@email.com' WHERE id=1");
mysqli_query($conn, "DELETE FROM users WHERE id=3");
?>
Try it Yourself โ†’

๐Ÿงช Quick Quiz

Which MySQLi function is used to prepare an SQL statement before execution?