Ask Your Question
3

What is the method for establishing a connection to my website's database using PHP?

asked 2022-09-30 11:00:00 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2022-01-23 07:00:00 +0000

scrum gravatar image

The method for establishing a connection to your website's database using PHP is to use the mysqli or PDO extension. Here are the steps to connect to the database:

  1. Create a database on your webhosting server.
  2. Open a PHP file inside your website's directory and set up a connection to the database by creating a new instance of either the mysqli or PDO class.
  3. Use the connection object to execute SQL queries and access the data in your database.

Example code for connecting using mysqli:

$host = "localhost";
$user = "username";
$password = "password";
$database = "dbname";

// Create connection
$conn = new mysqli($host, $user, $password, $database);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

Example code for connecting using PDO:

$host = "localhost";
$user = "username";
$password = "password";
$database = "dbname";

// Set DSN
$dsn = "mysql:host=$host;dbname=$database";

// Create a PDO instance
$conn = new PDO($dsn, $user, $password);

// Set PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-09-30 11:00:00 +0000

Seen: 11 times

Last updated: Jan 23 '22