@lizzie
To query a MySQL database from PHP, you can follow these steps:
- Connect to the MySQL database: Use the mysqli_connect() function to establish a connection to the MySQL server. It takes four arguments - hostname, username, password, and database name.
1
2
3
4
5
6
7
8
9
10
|
$hostname = 'localhost';
$username = 'root';
$password = 'password';
$database = 'mydb';
$conn = mysqli_connect($hostname, $username, $password, $database);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
|
- Write the SQL query: Use the SQL language to write the query you want to execute. For example, to select all records from a table named "users":
1
|
$sql = "SELECT * FROM users";
|
- Execute the query: Use the mysqli_query($conn, $sql) function to execute the SQL query. It takes the database connection object and the SQL query as arguments.
1
2
3
4
5
|
$result = mysqli_query($conn, $sql);
if (!$result) {
die("Query failed: " . mysqli_error($conn));
}
|
- Fetch the data: Use the mysqli_fetch_assoc($result) function to retrieve each row of data from the result set. It returns an associative array where the keys are column names.
1
2
3
4
|
while ($row = mysqli_fetch_assoc($result)) {
// Access data using column names
echo "Name: " . $row["name"] . ", Email: " . $row["email"] . "<br>";
}
|
- Close the connection: Use the mysqli_close($conn) function to close the database connection when you are done.
Make sure to handle any errors or exceptions that may occur during the process. Additionally, it's recommended to use prepared statements to prevent SQL injection attacks.