How to mail fetch data from mysql in php

To fetch data from a MySQL database using PHP, you can use the following steps:

Step 1: Connect to the MySQL database

You need to establish a connection to your MySQL database using the mysqli extension in PHP. Here's an example:

<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

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

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

Step 2: Prepare the query

You need to prepare a query to fetch the data from the MySQL database. For example, let's say you want to fetch all the rows from a table named users:

<?php
$query = "SELECT * FROM users";
?>

Step 3: Execute the query

Use the mysqli object to execute the query:

<?php
$result = $conn->query($query);
?>

Step 4: Fetch the data

Use a loop to fetch the data from the result set:

<?php
while($row = $result->fetch_assoc()) {
    echo $row["username"]. "<br>";
    echo $row["email"]. "<br>";
}
?>

In this example, we're using the fetch_assoc() method to fetch each row as an associative array, and then accessing the values using the column names.

Step 5: Close the connection

Don't forget to close the connection when you're done:

<?php
$conn->close();
?>

Here's the complete code:

<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

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

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

// Prepare the query
$query = "SELECT * FROM users";

// Execute the query
$result = $conn->query($query);

// Fetch the data
while($row = $result->fetch_assoc()) {
    echo $row["username"]. "<br>";
    echo $row["email"]. "<br>";
}

// Close the connection
$conn->close();
?>

Make sure to replace the placeholders (your_username, your_password, your_database) with your actual MySQL credentials and database name.

Also, note that this is a basic example, and you should consider using prepared statements and parameterized queries to prevent SQL injection attacks.