Table of Contents
成功!
Home Backend Development PHP Tutorial Establish object-oriented PHP database connection using PDO

Establish object-oriented PHP database connection using PDO

Jun 05, 2024 pm 01:49 PM
pdo Database Connectivity

Use PHP Data Objects (PDO) to establish object-oriented PHP database connections, providing a unified interface for interacting with various databases. The establishment of a PDO connection requires a data source name (DSN), username and password. Use the query() method to execute SQL queries and the fetchAll() method to obtain results. Practical examples show how to connect a PHP form to a MySQL database and insert data.

Establish object-oriented PHP database connection using PDO

Use PDO to establish an object-oriented PHP database connection

Object-oriented PHP database connection uses the PHP Data Object (PDO) class Library that provides a unified interface for interacting with various databases. Using PDO, you access the database in an object-oriented manner, which makes the code easier to organize and maintain.

Establishing a PDO connection

To establish a PDO connection, you need to use the PDO constructor. This constructor accepts the following parameters:

  • Data source name (DSN): Specifies the database server, database name, and other database-specific connection information. The format of the DSN varies depending on the database type.
  • Username: Username to connect to the database.
  • Password: Password to connect to the database.
$dsn = 'mysql:host=localhost;dbname=my_database';
$username = 'root';
$password = '';

try {
  $pdo = new PDO($dsn, $username, $password);
} catch (PDOException $e) {
  echo 'Connection failed: ' . $e->getMessage();
  die();
}
Copy after login

Execute query

You can use the query() method to execute a SQL query. This method returns a PDOStatement object that represents the query results.

$sql = 'SELECT * FROM users WHERE name LIKE ?';
$stmt = $pdo->prepare($sql);
$stmt->execute(['%joh%']);
Copy after login

Get the results

You can get the query results through the fetchAll() method. This method returns a result array where each element is an associative array.

$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
Copy after login

Practical Example

Consider a basic PHP form where a user can enter their name and insert it into a database. We use PDO to connect this form to a MySQL database.

<!-- form.php -->
<form action="submit.php" method="post">
  <label for="name">姓名:</label>
  <input type="text" id="name" name="name">
  <input type="submit" value="提交">
</form>
Copy after login
// submit.php
$dsn = 'mysql:host=localhost;dbname=my_database';
$username = 'root';
$password = '';

try {
  $pdo = new PDO($dsn, $username, $password);
} catch (PDOException $e) {
  echo 'Connection failed: ' . $e->getMessage();
  die();
}

$name = $_POST['name'];
$sql = 'INSERT INTO users (name) VALUES (?)';
$stmt = $pdo->prepare($sql);
$stmt->execute([$name]);

header('Location: success.php');
Copy after login
<!-- success.php -->
<h1 id="成功">成功!</h1>
<p>您的姓名已添加到数据库中。</p>
Copy after login

This example demonstrates how to use PDO to connect a PHP form to a MySQL database and insert data.

The above is the detailed content of Establish object-oriented PHP database connection using PDO. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use PHP database connection to implement paging query How to use PHP database connection to implement paging query Sep 08, 2023 pm 02:28 PM

How to use PHP database connection to implement paging query. When developing web applications, it often involves the need to query the database and perform paging display. As a commonly used server-side scripting language, PHP has powerful database connection functions and can easily implement paging queries. This article will introduce in detail how to use PHP database connection to implement paging query, and attach corresponding code examples. Prepare the database Before we start, we need to prepare a database containing the data to be queried. Here we take the MySQL database as an example,

PHP PDO vs. mysqli: compare and contrast PHP PDO vs. mysqli: compare and contrast Feb 19, 2024 pm 12:24 PM

PDOPDO is an object-oriented database access abstraction layer that provides a unified interface for PHP, allowing you to use the same code to interact with different databases (such as Mysql, postgresql, oracle). PDO hides the complexity of underlying database connections and simplifies database operations. Advantages and Disadvantages Advantages: Unified interface, supports multiple databases, simplifies database operations, reduces development difficulty, provides prepared statements, improves security, supports transaction processing Disadvantages: performance may be slightly lower than native extensions, relies on external libraries, may increase overhead, demo code uses PDO Connect to mysql database: $db=newPDO("mysql:host=localhost;dbnam

Common database connection and data reading and writing problems in C# Common database connection and data reading and writing problems in C# Oct 10, 2023 pm 07:24 PM

Common database connection and data reading and writing problems in C# require specific code examples. In C# development, database connection and data reading and writing are frequently encountered problems. Correct handling of these problems is the key to ensuring code quality and performance. This article will introduce some common database connection and data reading and writing problems, and provide specific code examples to help readers better understand and solve these problems. Database connection issues 1.1 Connection string errors When connecting to the database, a common error is that the connection string is incorrect. The connection string contains the connection to the database

Advanced PHP database connections: transactions, locks, and concurrency control Advanced PHP database connections: transactions, locks, and concurrency control Jun 01, 2024 am 11:43 AM

Advanced PHP database connections involve transactions, locks, and concurrency control to ensure data integrity and avoid errors. A transaction is an atomic unit of a set of operations, managed through the beginTransaction(), commit(), and rollback() methods. Locks prevent simultaneous access to data via PDO::LOCK_SHARED and PDO::LOCK_EXCLUSIVE. Concurrency control coordinates access to multiple transactions through MySQL isolation levels (read uncommitted, read committed, repeatable read, serialized). In practical applications, transactions, locks and concurrency control are used for product inventory management on shopping websites to ensure data integrity and avoid inventory problems.

PHP PDO Tutorial: An Advanced Guide from Basics to Mastery PHP PDO Tutorial: An Advanced Guide from Basics to Mastery Feb 19, 2024 pm 06:30 PM

1. Introduction to PDO PDO is an extension library of PHP, which provides an object-oriented way to operate the database. PDO supports a variety of databases, including Mysql, postgresql, oracle, SQLServer, etc. PDO enables developers to use a unified API to operate different databases, which allows developers to easily switch between different databases. 2. PDO connects to the database. To use PDO to connect to the database, you first need to create a PDO object. The constructor of the PDO object receives three parameters: database type, host name, database username and password. For example, the following code creates an object that connects to a mysql database: $dsn="mysq

How to configure database connection in mybatis How to configure database connection in mybatis Jan 15, 2024 pm 02:12 PM

How to configure database connection in mybatis: 1. Specify the data source; 2. Configure the transaction manager; 3. Configure the type processor and mapper; 4. Use environment elements; 5. Configure aliases. Detailed introduction: 1. Specify the data source. In the "mybatis-config.xml" file, you need to configure the data source. The data source is an interface, which provides a database connection; 2. Configure the transaction manager to ensure the normality of database transactions. For processing, you also need to configure the transaction manager; 3. Configure the type processor and mapper, etc.

Why does my PHP database connection fail? Why does my PHP database connection fail? Jun 05, 2024 pm 07:55 PM

Reasons for a PHP database connection failure include: the database server is not running, incorrect hostname or port, incorrect database credentials, or lack of appropriate permissions. Solutions include: starting the server, checking the hostname and port, verifying credentials, modifying permissions, and adjusting firewall settings.

PHP returns the numeric encoding of the error message in the previous MySQL operation PHP returns the numeric encoding of the error message in the previous MySQL operation Mar 22, 2024 pm 12:31 PM

This article will explain in detail the numerical encoding of the error message returned by PHP in the previous Mysql operation. The editor thinks it is quite practical, so I share it with you as a reference. I hope you can gain something after reading this article. . Using PHP to return MySQL error information Numeric Encoding Introduction When processing mysql queries, you may encounter errors. In order to handle these errors effectively, it is crucial to understand the numerical encoding of error messages. This article will guide you to use php to obtain the numerical encoding of Mysql error messages. Method of obtaining the numerical encoding of error information 1. mysqli_errno() The mysqli_errno() function returns the most recent error number of the current MySQL connection. The syntax is as follows: $erro

See all articles