search
HomeBackend DevelopmentPHP TutorialPHP和MySQL入门(10)

在第二章中,我们使用一个叫mysql的程序来连接到MySQL数据库服务器,在这个程序中,我们可以输入SQL查询(命令)并立即显示查询结果。在PHP中,有着类似的机制:mysql_query函数。

 

mysql_query(, );

 

在这儿,是一个包含将执行的SQL命令的字符串。和mysql_select_db一样,连接标识这个参数也是可选的。

这个函数的返回决定于发出的查询的类型。对于绝大多数的SQL命令来说,mysql_query返回逻辑真或逻辑假来标明执行是否成功。请参看下面这个例子,这是用来建立我们在第二章中建立的Jokes数据表的:

 

$sql = "CREATE TABLE Jokes ( " .
"ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY, " .
"JokeText TEXT, " .
"JokeDate DATE NOT NULL " .
")";
if ( mysql_query($sql) ) {
echo("

Jokes table successfully created!

");
} else {
echo("

Error creating Jokes table: " .
mysql_error() . "

");
}

 

这儿使用的mysql_error将以字符串的形式返回MySQL服务器最后发出的错误信息。

对于DELETE、 INSERT以及UPDATE(用来修改存储的数据),MySQL可以知道有多少数据行被这个查询影响。参看下面的SQL命令,这个命令我们曾在第二章中用来设置所有包含单词“chicken”的笑话的日期:

$sql = "UPDATE Jokes SET JokeDate='1990-04-01' " .
"WHERE JokeText LIKE '%chicken%'";

当我们执行这个查询时,我们可以使用mysql_affected_rows函数来显示这个修改所影响的数据行的数目:

 

if ( mysql_query($sql) ) {
echo("

Update affected " .
mysql_affected_rows() . " rows.

");
} else {
echo("

Error performing update: " .
mysql_error() . "

");
}

 

SELECT命令会有一些不同,因为它会得到许多信息,而PHP必须提供方法来处理这些信息。

处理SELECT结果集

对于绝大多数的SQL查询来说,mysql_query函数仅仅返回逻辑真或逻辑假。而对于 SELECT查询来说,仅仅这样显然是不够的。你应该还记得 SELECT查询是用来显示数据库中存储的数据的。除了指出查询成功还是失败之外,PHP还必须得到查询的结果。作为一个结果,当我们执行一个 SELECT查询的时候,mysql_query会返回一个标识“结果集”的数字,这将包含了这个查询返回的所有行的列表。如果查询失败,函数仍然是返回 一个逻辑假。

 

$result = mysql_query("SELECT JokeText FROM Jokes");
if (!$result) {
echo("

Error performing query: " .
mysql_error() . "

");
exit();
}

 

假定在执行查询时没有遇到错误,上面的代码会定位一个有关存储在笑话库中所有笑话的正文的结果集,这个定位被存储在变量$result中。因为数据库中的笑话的数目是没有限制的,这个结果集可能非常庞大。

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 Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

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

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

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools