PHP U5
PHP U5
Example:
<?php
$servername = "localhost";
$username = "root";
$password = "";
1|Page
// Create a new database
$sql = "CREATE DATABASE mydatabase";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
}
Example:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydatabase";
2|Page
$conn = mysqli_connect($servername, $username, $password,
$dbname);
2. Execute an SQL query to insert data into the table using mysqli_query().
6. Fetch each row using mysqli_fetch_assoc() or similar functions, and access the values
using column names.
Example:
<?php
3|Page
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydatabase";
if (mysqli_query($conn, $sql)) {
echo "Data inserted successfully";
} else {
echo "Error inserting data: " . mysqli_error($conn);
}
if (mysqli_num_rows($result) > 0) {
// Output data of each row
while ($row = mysqli_fetch_assoc($result)) {
4|Page
echo "Name: " . $row["name"] . ", Email: " . $row["email"] . "<br>";
}
} else {
echo "No records found";
}
In the above example, after establishing the database connection, we execute a SELECT
query to retrieve all the records from the "users" table using mysqli_query(). We then check
if there are any rows returned using mysqli_num_rows(). If there are rows, we loop through
the result using mysqli_fetch_assoc() to fetch each row as an associative array. We can then
access the values of each column using the column names as keys.
2. Execute an SQL query to update or delete data in the table using mysqli_query().
Example:
<?php
$servername = "localhost";
$username = "root";
$password = "";
5|Page
$dbname = "mydatabase";
if (mysqli_query($conn, $sql)) {
echo "Data updated successfully";
} else {
echo "Error updating data: " . mysqli_error($conn);
}
if (mysqli_query($conn, $sql)) {
echo "Data deleted successfully";
} else {
echo "Error deleting data: " . mysqli_error($conn);
}
6|Page
mysqli_close($conn);
?>
In the above example, we establish a connection to the MySQL server and select the
database. We then execute an UPDATE query to update the email field for the user with the
name 'John Doe' in the 'users' table. Next, we execute a DELETE query to delete the row where
the name is 'John Doe'. If the update or delete operation is successful, it displays a success
message; otherwise, it shows an error message. Finally, we close the database connection using
mysqli_close().
7|Page