PHP: MySQL Database

·

2 min read

MySQL

It is an open-source relational database system where we can store data in the form of tables. To use this database with PHP, we need to install MySQL but if you have XAMPP installed, MySQL already comes with it. To work with MySQL in PHP:

  • We need to get connected with the MySQL server.

  • Execute our SQL queries to interact with the database.

  • The result can then be fetched and displayed in the browser.

Connection

To connect with the server using Object Oriented method, we use:

mysqli(host, username, password, database, port, socket)

$conn = new mysqli("localhost", "root", "", "form_db");
// Error Handling
if($conn->connect_error) echo "Connection Failed";
else echo "Connection Success. ";
💡
Here, 'form_db' is the database that can be created visually using XAMPP's phpMyAdmin.

Execute Query

Once the connection is established, the SQL query can be executed and the result can be stored in a variable.

// Write a SQL query
$sql = "INSERT INTO pizza(email, title, ingredient) VALUES('youremail@gmail.com', 'Pizza', 'Cheese')";
// Execute SQL query using above '$conn' object
$result = $conn->query($sql);
// Error Handling
if($result) "Insertion Successful";
else echo "Insetion Failed!";
💡
Here, 'pizza' is a table created inside the 'form_db' database using XAMPP.

Display Result

To display the query result in the browser, we use a 'fetch_assoc()' method which returns the next row of the table as an associative array every time it is called. It returns 'FALSE' if no rows are left to be fetched. The 'pizza' table is shown below:

// Display attributes of each row
while($row = $result->fetch_assoc())
{
    echo "<br>";
    echo $row['email'];
    echo $row['title'];
    echo $row['ingredient'];
    echo "<br>";
}

Likewise, we can use other SQL queries to perform CRUD(Create, Read, Update and Delete) operations and get that result shown to the user.