Mar 3, 2023

How to Connect MySQL database with PHP code?



Connecting MySQL database with PHP requires a few steps which can be accomplished using the following code:

Step 1: Establishing Connection to MySQL Database

$host = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database_name";
// Creating a MySQL Connection
$connection = mysqli_connect($host, $username, $password, $dbname);
// Check Connection
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";

Explanation:

Here, we are first declaring the necessary variables that are required to establish a connection with the MySQL database. We then use the mysqli_connect() function to create a connection object which takes four parameters: the hostname, the username, the password, and the name of the database. We then check if the connection is successful or not by using the mysqli_connect_error() function, and if not, we terminate the script with an error message.

Step 2: Executing SQL Query

$sql = "SELECT * FROM your_table_name";
$result = mysqli_query($connection, $sql);
// Check if Query was executed successfully
if (!$result) {
die("Query failed: " . mysqli_error($connection));
}
// Display Results
while ($row = mysqli_fetch_assoc($result)) {
echo $row["column_name"] . "
";
}

Explanation:

Here, we are declaring an SQL query using the SELECT statement to retrieve all data from a specific table in the database. We then use the mysqli_query() function to execute the query and store the result in a variable. We check if the query was executed successfully or not by using the mysqli_error() function. If the query was successful, we then use a while loop to iterate through the result set and display the required data.

Step 3: Closing Connection

mysqli_close($connection);

Explanation:

Finally, we use the mysqli_close() function to close the connection object to the MySQL database. Note: It is recommended to use prepared statements to prevent SQL injection attacks when executing SQL queries in PHP.

No comments:

Post a Comment

Web Application Security for PHP Programmers: Best Practices and Techniques

Web application security is a critical concern for PHP programmers, and it's important to be well-versed in security practices to ensure...