To integrate MySQL with PHP, you need to follow these steps:
1. Connect to MySQL Server: Use the `mysqli_connect` function to connect to the MySQL server. Provide the hostname, username, password, and database name as parameters. For example:
“`php
$servername = “localhost”;
$username = “username”;
$password = “password”;
$dbname = “database”;
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die(“Connection failed: ” . mysqli_connect_error());
}
“`
2. Execute SQL Query: Use the `mysqli_query` function to execute SQL queries. Pass the database connection and the SQL query as parameters. For example, to select data from a table:
“`php
$sql = “SELECT * FROM table_name”;
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
// Process the data
}
} else {
echo “No results found”;
}
“`
3. Retrieve and Process Data: Use the `mysqli_fetch_assoc` function to retrieve data from the result set. This function returns an associative array containing the column names and values. Process the retrieved data as required.
4. Close the Connection: To close the MySQL connection, use the `mysqli_close` function. For example:
“`php
mysqli_close($conn);
“`
Note: It is important to sanitize user input when constructing SQL queries to prevent SQL injection attacks. You can use prepared statements or parameterized queries to achieve this.