PHP is a popular server-side language used for creating dynamic web applications. When creating these applications, you often need to connect to a database to read data from the database, modify data, or insert new data into the database. This article will introduce the basic knowledge of PHP database connection.
1. Select the database type
When connecting PHP to the database, you need to select a suitable database type. PHP supports multiple database types such as MySQL, PostgreSQL, SQLite, and Oracle. Each database has its own advantages and limitations, so it is necessary to evaluate the needs and characteristics of the project to choose a suitable database.
2. Database connection
PHP uses built-in functions to connect to the database. Generally, we use PDO or mysqli library, which provide many functions to connect to the database.
For PDO, you can use the following code to create a connection:
$servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); // 设置 PDO 错误模式为异常 $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "Connected successfully"; } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); }
For mysqli, you can use the following code to create a connection:
$servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // 创建连接 $conn = mysqli_connect($servername, $username, $password, $dbname); // 检测连接 if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } echo "Connected successfully";
3. Execute SQL query
Once connected to the database, you can execute SQL queries. Query results can be returned as an array or object. For example, you can use the following code to execute a SELECT query:
$sql = "SELECT id, firstname, lastname FROM MyGuests"; $result = $conn->query($sql); if ($result->num_rows > 0) { // 输出每行数据 while($row = $result->fetch_assoc()) { echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>"; } } else { echo "0 results"; }
4. Close the connection
After completing communication with the database, the connection should be closed to avoid unnecessary overhead. You can use the following code to close the connection:
$conn->close();
Alternatively, if using mysqli, you can use the following code to close the connection:
mysqli_close($conn);
Summary
Connecting to the database is to create a Web The foundation of the application, therefore requires mastery of basic database connection concepts and techniques. This article introduces the basic knowledge of connecting to databases in PHP. Hope it will be helpful to your learning and development.
The above is the detailed content of Basic knowledge of PHP database connection. For more information, please follow other related articles on the PHP Chinese website!