Register Now


Lost Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

How to connect MySQL database in php

How to connect MySQL database in php

This will show how to connect MySQL database in PHP. You can use following code to connect database.

$con = mysqli_connect("localhost","root","projectpassword","dbname");
if (mysqli_connect_errno()) 
 echo "Failed to connect to MySQL database.."; 

$con = mysqli_connect(“localhost”,”root”,”projectpassword”,”dbname”);

The code you provided is used to connect to a MySQL database using the MySQLi extension in PHP.

  • “localhost” is the server name where the database is located.
  • “root” is the username used to connect to the database.
  • “projectpassword” is the password for the user specified above.
  • “dbname” is the name of the database to be connected.

The mysqli_connect() function takes four parameters: the server name, the username, the password, and the database name. It returns a connection object on successful connection, or false if the connection fails.

It is important to check the return value of the function to ensure that the connection was successful. Once the connection is successful, you can use the connection object to run queries, retrieve data, and perform other operations on the database.

It is also important to consider security best practices such as using a secure password and keeping the connection information in a separate configuration file that is not accessible to the public.

The example above uses the mysqli_connect() function to connect to a MySQL database, and then uses the mysqli_connect_errno() function to check for errors. If there is an error with the connection, the mysqli_connect_errno() function will return a non-zero value, and the error message can be retrieved using the mysqli_connect_error() function. The program will exit in this case.

It’s important to check the return value of the function mysqli_connect() before calling mysqli_connect_errno() because mysqli_connect_errno() can be used only after an unsuccessful connection attempt.

It’s also important to close the connection when your script is done using the mysqli_close() function, this is to avoid any potential security issues and to free up resources on the server.

Leave a reply