search
HomeBackend DevelopmentPHP TutorialPHP:MySQL数据库访问(mysqli & PDO)

一. 使用mysqli访问数据库

1. 连接数据库

$db = new mysqli("localhost", "username", "password", "databaseName");或者:@ $db = mysqli_connect("localhost", "username", "password", "databaseName");

2. 关闭数据库

$db->close();或者:mysqi_close($db);

3. 选择使用的数据库

$db->select_db(databaseName);或者:mysqli_select_db(databaseName);

4. 查询数据库

查询:

$query = "SELECT * from dbName";$result = $db->query($query);或者:mysqli_query($db, $query);

5. 检索查询结果

(1)查询结果的行数:

$num_results = $result->num_rows;或者:$num_results = mysqli_num_rows($result);

(2)查询结果的每一行内容:

$row = $result->fetch_assoc();或者:$row = mysqli_fetch_assoc($result);

获取每一行的字段的值:

$row["books"]

(3)获取查询结果的列举数组:

$row = $result->fetch_object();或者:$row = mysqli_fetch_object($result);

然后可以通过$row[0}、$row[1]或$row->title、$row->author等来访问每个属性。

6. 释放结果集

$result->free();

或者:

mysqli_free_result($result);

二. 使用PDO访问数据库

1. 连接数据库

$mysql = new PDO("mysql:host=localhost", $user, $password);$mysql = new PDO("mysql:host=localhost;port=8090", $user, $password);$mysql = new PDO("mysql:host=localhost;port=8090;dbname=android", $user, $password);// 连接到一个本地MySQL服务器$mysql = new PDO("mysql:unix_socket=/tmp/mysql.sock", $user, $password);

譬如:

$dbhost = "localhost";$dbdatabase = "android";$username = "android";$userpass = "android";$dsn='mysql:host='.$dbhost.';dbname='.$dbdatabase;try {    $dbh = new PDO($dsn,$username,$userpass);    foreach($dbh->query('SELECT * from test') as $row) {        print_r($row);    }    // 关闭数据库连接    $dbh = null;} catch (PDOException $e) {    print "Error!: " . $e->getMessage() . "<br/>";    die();}

2. 关闭数据库

$conn = null;

3. 持久化连接

<?php    $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(PDO::ATTR_PERSISTENT => true));?>

4. 想数据库中插入数据

try {      $dbh->beginTransaction();  $dbh->exec("insert into staff (id, first, last) values (23, 'Joe', 'Bloggs')");  $dbh->exec("insert into salarychange (id, amount, changedate)       values (23, 50000, NOW())");  $dbh->commit();} catch (Exception $e) {  $dbh->rollBack();  echo "Failed: " . $e->getMessage();}

PDO 类的常用方法:

方法名 描述
commit() 提交一个事务。
__construct() 创建一个表示数据库连接的 PDO 实例。
errorInfo() 返回最后一次操作数据库的错误信息。
exec() 执行一条 SQL 语句,并返回受影响的行数。
getAttribute() 取回一个数据库连接的属性。
lastInsertId() 返回最后插入行的ID或序列值。
prepare() 备要执行的SQL语句并返回一个 PDOStatement 对象。
query() 执行 SQL 语句,返回PDOStatement对象,可以理解为结果集。
quote() 为SQL语句中的字符串添加引号。
setAttribute() 设置属性。

PDOStatement的常用方法:

方法名 描述
bindColumn() 绑定一列到一个 PHP 变量。
bindParam() 绑定一个参数到指定的变量名。
bindValue() 把一个值绑定到一个参数。
closeCursor() 关闭游标,使语句能再次被执行。
columnCount() 返回结果集中的列数。
debugDumpParams() 打印一条 SQL 预处理命令。
errorCode() 获取跟上一次语句句柄操作相关的 SQLSTATE。
errorInfo() 获取跟上一次语句句柄操作相关的扩展错误信息。
execute() 执行一条预处理语句。
fetch() 从结果集中获取下一行。
fetchAll() 返回一个包含结果集中所有行的数组。
fetchColumn() 从结果集中的下一行返回单独的一列。
fetchObject() 获取下一行并作为一个对象返回。
getAttribute() 检索一个语句属性。
getColumnMeta() 返回结果集中一列的元数据。
nextRowset() 在一个多行集语句句柄中推进到下一个行集。
rowCount() 返回受上一个 SQL 语句影响的行数。
setAttribute() 设置一个语句属性。
setFetchMode() 为语句设置默认的获取模式。

记录:踩过的一些坑

(1)问题:数据为中文时,在数据库中可以正常显示,但是一在前台调用就出现乱码。

解决:

1)首先检查php文件是否有编码格式声明头文件,如

header('COntent-Type:text/html;charset=utf-8');;如果是html文件则要检查是否有meta声明,如

2)如果php文件的编码格式没问题,那问题可能出现在抓取数据过程中,数据的编码格式有误而导致乱码。可以尝试在数据库查询前插入编码格式的显式定义:$db->query("SET NAMES 'UTF8'");。

原文 http://www.dengzhr.com/others/backend/750
Statement
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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),