Hongmu Notes
Home Language Notes PHP connects to a database and executes SQL statements.
Language Notes PHP PHP and mysql

PHP connects to a database and executes SQL statements.

PHP connects to a database and executes SQL statements.

In PHP, connecting to a database and executing SQL statements can be done through the following steps:

  1. Connect to database

Use mysqli_connect() Function or PDO Use a class to connect to a database. For example:

// 使用 mysqli 连接数据库
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// 创建连接
$conn = mysqli_connect($servername, $username, $password, $dbname);

// 检查连接是否成功
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

// 使用 PDO 连接数据库
$dsn = "mysql:host=localhost;dbname=myDB";
$username = "username";
$password = "password";

// 创建连接
try {
    $conn = new PDO($dsn, $username, $password);
    // 设置 PDO 错误模式为异常
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully";
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
  1. Execute an SQL statement

Use mysqli_query() Function or PDO generic query() A method for executing SQL statements. For example:

// 使用 mysqli 执行 SQL 语句
$sql = "SELECT * FROM myTable";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    // 输出数据
    while($row = mysqli_fetch_assoc($result)) {
        echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";
    }
} else {
    echo "0 results";
}

// 使用 PDO 执行 SQL 语句
$sql = "SELECT * FROM myTable";
$result = $conn->query($sql);

if ($result->rowCount() > 0) {
    // 输出数据
    while($row = $result->fetch()) {
        echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";
    }
} else {
    echo "0 results";
}

The above describes the basic steps for connecting to a database and executing SQL statements; the specific implementation may vary depending on the context. It is important to prevent SQL injection attacks when executing SQL statements; this can be done using mysqli_real_escape_string() Function or PDO Use a preprocessing statement to avoid this situation.

微信赞赏

WeChat

支付宝赞赏

Alipay

✍️ Author: Hong Mu

webmaster · Thanks for reading, stay tuned for more exciting content

Author homepage View home page →

Related articles

PHP cast type

PHP cast type Language Notes PHP PHP collection PHP and mysql

Get the data type 1. If you want to check the value and type of an expression, use var_dump(). 2. If you just want to get an easy-to-read type expression for debugging, use gettype(). 3. To check a certain type, do not use gettype(), but use the is_type() function. Converting Strings to Numbers When a string is evaluated as a number, the result is determined according to the following rules...
👁 232
PHP special character escaping and restoration

PHP special character escaping and restoration Language Notes PHP PHP collection PHP and mysql

Escape character is a special character constant. Escape characters are backslashed " & quot; At the beginning, followed by one or more characters. The escaped character has a specific meaning, which is different from the original meaning of the character, so it is called "escaped" character. The use of escape characters 1: turn ordinary characters into special purposes, such as back key and enter key. 2. Used to convert a character with special meaning back to its original meaning. 3. Before data is written into the database, escape characters (function …
👁 180
mysqli in PHP

mysqli in PHP Language Notes PHP PHP collection PHP and mysql

The `mysqli_num_rows()` function is exclusively used with `SELECT` query methods, whereas the `mysqli_affected_rows()` function returns the number of rows affected by the previous SQL statement across the entire database; this function is primarily used with `INSERT`, `UPDATE`, and `DELETE` operations.
👁 145

Recommended reading

(Adaptive mobile version) Responsive construction machinery equipment PBootCMS website template – Download HTML5 excavator website source code – 0650

(Adaptive mobile version) Responsive construction machinery equipment PBootCMS website template – Download HTML5 excavator website source code – 0650 Practical Collection pbootcms Template

A responsive website template for construction machinery and excavators using PbootCMS, compatible with both PC and WAP devices. The design features a bold yellow color scheme, ideal for showcasing excavators, construction machinery products, and project cases. This template helps construction machinery companies showcase their products online and attract clients in the construction and mining industries. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5...
👁 53
Industrial Machinery Production Equipment Website Template 0301

Industrial Machinery Production Equipment Website Template 0301 Practical Collection Yiyou template

This EyouCMS template is ideal for the industrial machinery and production equipment sector, featuring a professional industrial design style that effectively showcases mechanical equipment products, production line solutions, technical specifications, and industrial applications. It enables machinery manufacturing enterprises to showcase their products online and attract industrial customers. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS...
👁 46
Responsive Fishery Association Website Template 1151

Responsive Fishery Association Website Template 1151 Practical Collection Yiyou template

An EyouCMS responsive website template designed specifically for fishing associations. Its professional fishing-themed design effectively showcases the association's functions, member services, industry news, and fishing-related information, helping fishing associations establish an online industry exchange platform. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS...
👁 51
(PC + WAP) Automotive Parts Lubricants – PBootCMS Website Template; Download Source Code for Automotive Repair 4S Store Websites – 0651

(PC + WAP) Automotive Parts Lubricants – PBootCMS Website Template; Download Source Code for Automotive Repair 4S Store Websites – 0651 Practical Collection pbootcms Template

A PbootCMS website template designed for the automotive parts, lubricants, and auto repair industry, supporting both PC and WAP devices. Its robust and professional design effectively showcases automotive parts products and repair services. This template helps automotive parts manufacturers or 4S dealership repair businesses build their online brand identity and expand their sales channels. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin...
👁 47
Responsive premium imported alcoholic beverage website template – 0302

Responsive premium imported alcoholic beverage website template – 0302 Practical Collection Yiyou template

An eYouCMS responsive website template designed for the premium imported alcoholic beverages industry. Its luxurious and high-end design enables effective presentation of imported beverage products, brand stories, tasting experiences, and business partnership opportunities. This template helps beverage traders attract high-end consumers and distributors online. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for eYouCMS | eYouCMS...
👁 41
Public Relations Association Website Template 1152

Public Relations Association Website Template 1152 Practical Collection Yiyou template

This EyouCMS template is ideal for Public Relations Associations, featuring a professional and sophisticated design that effectively showcases the association's functions, member services, industry trends, and PR activities. It helps PR associations establish an online information exchange platform. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS System...
👁 49