How to query mysql database from php?

Member

by lizzie , in category: MySQL , 7 months ago

How to query mysql database from php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by jasen_gottlieb , 5 months ago

@lizzie 

To query a MySQL database from PHP, you can follow these steps:

  1. 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());
}


  1. 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";


  1. 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));
}


  1. 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>";
}


  1. Close the connection: Use the mysqli_close($conn) function to close the database connection when you are done.
1
mysqli_close($conn);


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.