Sambungan Pangkalan Data PHP

王林
Lepaskan: 2024-08-29 13:14:34
asal
585 orang telah melayarinya

The database is one of the important components of any programming language. To deal with a dynamic project and data management, we need to have a database. PHP supports various kinds of database connections with it. MySQL is one of the most widely used relational databases, and it is mostly used with PHP as well. Considering the term database connection in PHP, MySQL itself have various way to make connections in an application to play with the database operations. After making the connection of PHP-MYSQL, we can do various things like – insertion of records, deletion of records, updating the records, etc. This article will see database connection using the PHP language in various ways, so keep reading to grab it properly.

ADVERTISEMENT Popular Course in this category PHP DEVELOPER - Specialization | 8 Course Series | 3 Mock Tests

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

How to Connect PHP Database?

Before making a connection, we should have details like – Hostname, Database User Name, Database Password, Port (if application), etc. Every programming language has its own unique way of making a connection with the databases and playing with that. Database in PHP, not that much of a big task as we see in a programming language like JAVA. There is a very simple couple of lines code to connect with the database.

In the PHP language, we can make database connection in a below-mentioned way:

1. MySQL

This will work with the MySQL database only. This extension follows the old traditional way of communicating with a database. Now, every coming PHP version has deprecated this approach.

2. MySQLi Extension

This will work with the MySQL database only, but this is an improved version of MySQL.

3. PDO

It works with various databases. Usually, we consider this as the best approach out of these three. This one is considered as an object-oriented way of communicating with the MySQL database. The moment we create a connection, it gives us the object to deal with the MySQL related.

Examples

Given below are the examples mentioned:

Example 1 – PHP MYSQL Connection using MYSQL

Code:

$servername = "localhost"; $username = "root"; $password = ""; $link = mysql_connect($servername, $username, $password); if (!$link) { die('Connection failed: ' . mysql_error()); }else{ echo "Database Connected successfully"; // in case of success }
Salin selepas log masuk

The connection can be made successfully in the lower version of PHP. But, if we use this code, it says Deprecated: mysql_connect():The MySQL extension is deprecated and will be removed in the future: use mysqli or PDO instead.

That’s why we should avoid using this technique to make a database connection in PHP language to the MySQL database.

Example 2 – PHP MYSQL Connection Using MYSQLi

We can make the connection using the MYSQLi in two ways.

MYSQLi Object-Oriented.

Code:

connect_error) { die("Connection failed: " . $conn->connect_error); // in case of error }else{ echo "Database Connected successfully"; // in case of success } ?>
Salin selepas log masuk

Now, we have $conn, the database connection object. We can use this object for all the communication to the database.

Code:

// selecting database "test1" mysqli_select_db($conn,"test1");
Salin selepas log masuk

You can also pass the database as an argument at the time of connection establishment.

Code:

$conn = new mysqli($servername, $username, $password, $databaseName);
Salin selepas log masuk

MYSQLi Function (procedural) Way

Code:

$servername = "localhost"; $username = "root"; $password = ""; // Database Connection Code $conn = mysqli_connect($servername, $username, $password); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); // in case of error }else{ echo "Database Connected successfully"; // in case of success }
Salin selepas log masuk

We can also use the other operation like database connection and other as mentioned above.

Example 3 – PDO PHP Database Connection

Again this is an Object-Oriented way of database connection in PHP. We can use various types of databases with this approach.

Code:

$servername = "localhost"; $username = "root"; $password = ""; try { // Database Connection Code $conn = new PDO("mysql:host=$servername;dbname=test1", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // in case of success echo "Connected successfully"; } catch(PDOException $e) { // in case of error echo "Connection failed: " . $e->getMessage(); }
Salin selepas log masuk

Now the question is Should I Use MYSQLi or PDO?

These both are the object-oriented way of database connection using PHP. We can consider this as a present and the future way of the database connection. But choosing out of these two is all about what kind of need you have with your project. If there is a MySQL database only, you can go with MYSQLi. But the moment the possibility of the database changes, from MySQL to MySQL SERVER or any other vendor, the PDO will be the best option. These both approach support the prepared statement while writing queries to do database operations. A prepared statement is an approach we can protect our application or the database from the SQL injection attack.

Fazit

Also, was geht dir durch den Kopf? Nachdem wir alle drei oben genannten Arten von Datenbankverbindungstechniken kennengelernt hatten, kamen wir zu dem Schluss, dass PDO der beste Ansatz ist, mit dem wir weitermachen können. Die Idee dahinter ist, dass wir diesen Ansatz für die Verbindung nicht nur für die MySQL-Datenbank, sondern auch für andere Datenbanken wie MySQL Server verwenden können. Wir sollten die Verwendung von mysql_connect() vermeiden, um sicherzustellen, dass unser Code langlebig und zukunftssicher ist.

Atas ialah kandungan terperinci Sambungan Pangkalan Data PHP. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Label berkaitan:
php
sumber:php
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!