PHP連接和操作MySQL數據庫基礎教程,mysql基礎教程
Jun 13, 2016 am 09:24 AMPHP連接和操作MySQL數據庫基礎教程,mysql基礎教程
從這里開始
我的博客,后臺數據庫是什么?沒錯,就是MySQL,服務器端使用的腳本就是PHP,整個框架使用的是WordPress。PHP和MySQL就像夫妻一樣,總是在一起干活?,F(xiàn)在這里,就集合PHP,總結一下MySQL的實際使用,也算作是MySQL開發(fā)的入門。關于PHP與MySQL的合作,不外乎以下三種方法:
1.mysql擴展;但是目前已經不推薦使用;
2.mysqli擴展;同時提供面向對象風格和面向過程的風格;要求MySQL版本是4.1及以上的;
3.PDO擴展為PHP訪問數據庫定義了一種輕量級的一致接口;PDO_MYSQL是對其的具體實現(xiàn)。這里暫時只關心開發(fā)。由于mysql擴展已經不推薦使用了,我也會與時俱進,不做總結;而mysqli和PDO方式用的比較多,所以這篇將會總結如何使用mysqli擴展來連接數據庫服務器,如何查詢和獲取數據,以及如何執(zhí)行其它重要任務。下一篇博文將會總結PDO的相關內容。
使用mysqli擴展
先看以下測試數據庫db_test中的測試數據:
復制代碼 代碼如下:
mysql> select * from tb_test;
+----+-----------+----------+------------+------------+
| id | firstname | lastname | email????? | phone????? |
+----+-----------+----------+------------+------------+
|? 1 | Young???? | Jelly??? | 123@qq.com | 1384532120 |
|? 3 | Fang????? | Jone???? | 456@qq.com | 1385138913 |
|? 4 | Yuan????? | Su?????? | 789@qq.com | 1385138913 |
+----+-----------+----------+------------+------------+
3 rows in set (0.00 sec)
1.建立和斷開連接
與MySQL數據庫交互時,首先要建立連接,最后要斷開連接;這包括與服務器連接并選擇一個數據庫,以及最后關閉連接,釋放資源。選擇使用面向對象接口與MySQL服務器交互,首先需要通過其構造函數實例化mysqli類。
復制代碼 代碼如下:
??? // 實例化mysqli類
??? $mysqliConn = new mysqli();
??? // 連接服務器,并選擇一個數據庫
??? $mysqliConn->connect('127.0.0.1', 'root', 'root', 'db_test');
??? printf("MySQL error number:%d", $mysqliConn->errno);
??? // 或者
??? // $mysqliConn->connect("http://127.0.0.1", 'root', 'root');
??? // $mysqliConn->select_db('db_test');
???
??? // 與數據庫交互
???
??? // 關閉連接
??? $mysqliConn->close();
?>
一旦成功的選擇了數據庫,然后就可以對這個數據庫執(zhí)行數據庫查詢了。一旦腳本執(zhí)行完畢,所有打開的數據庫連接都會自動關閉,并釋放資源。不過,有可能一個頁面在執(zhí)行期間需要多個數據庫連接,各個連接都應當適當的加以關閉。即使只使用一個連接,也應該在腳本的最后將其關閉,這是一種很好的實踐方法。在任何情況下,都由close()負責關閉連接。
2.處理連接錯誤
當然,如果無法連接MySQL數據庫,那么不大可能在這個頁面繼續(xù)完成預期的工作了。因此,一定要注意監(jiān)視連接錯誤并相應地做出反應。mysqli擴展包包含很多可以用來捕獲錯誤消息的特性,另外也可以使用異常來做到這一點。例如,可以使用mysqli_connect_errno()和mysqli_connect_error()方法診斷并顯示一個MySQL連接錯誤的有關信息。
關于mysqli的具體信息可以在這里查看:http://php.net/manual/zh/book.mysqli.php
與數據庫交互
絕大多數查詢都與創(chuàng)建、獲取、更新和刪除任務有關,這些任務統(tǒng)稱為CRUD。這里就開始總結CRUD相關的內容。
1.向數據庫發(fā)送查詢
方法query()負責將query發(fā)送給數據庫。它的定義如下:
復制代碼 代碼如下:
mixed mysqli::query ( string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )
可選參數resultmode可以用于修改這個方法的行為,它接受兩個可取值。這篇文章總結了二者之間的區(qū)別。http://www.bkjia.com/article/55792.htm;下面是一個簡單的使用例子:
復制代碼 代碼如下:
??? // 實例化mysqli類
??? $mysqliConn = new mysqli();
?
??? // 連接服務器,并選擇一個數據庫
??? // 錯誤的密碼
??? $mysqliConn->connect('127.0.0.1', 'root', 'root', 'db_test');
??? if ($mysqliConn->connect_error)
??? {
??????? printf("Unable to connect to the database:%s", $mysqliConn->connect_error);
??????? exit();
??? }
???
??? // 與數據庫交互
??? $query = 'select firstname, lastname, email from tb_test;';
?
??? // 發(fā)送查詢給MySQL
??? $result = $mysqliConn->query($query);
?
??? // 迭代處理結果集
??? while (list($firstname, $lastname, $email) = $result->fetch_row())
??? {
??????? printf("%s %s's email:%s
", $firstname, $lastname, $email);
??? }
???
??? // 關閉連接
??? $mysqliConn->close();
?>
2.插入、更新和刪除數據
插入、更新和刪除使用的是insert、update和delete查詢完成的,其做法實際上與select查詢相同。示例代碼如下:
復制代碼 代碼如下:
??? // 實例化mysqli類
??? $mysqliConn = new mysqli();
?
??? // 連接服務器,并選擇一個數據庫
??? // 錯誤的密碼
??? $mysqliConn->connect('127.0.0.1', 'root', 'root', 'db_test');
??? if ($mysqliConn->connect_error)
??? {
??????? printf("Unable to connect to the database:%s", $mysqliConn->connect_error);
??????? exit();
??? }
???
??? // 與數據庫交互
??? $query = 'select firstname, lastname, email from tb_test;';
??? // 發(fā)送查詢給MySQL
??? $result = $mysqliConn->query($query);
?
??? // 迭代處理結果集
??? while (list($firstname, $lastname, $email) = $result->fetch_row())
??? {
??????? printf("%s %s's email:%s
", $firstname, $lastname, $email);
??? }
???
??? $query = "delete from tb_test where firstname = 'Yuan';";
??? $result = $mysqliConn->query($query);
?
??? // 告訴用戶影響了多少行
??? printf("%d row(s) have been deleted.
", $mysqliConn->affected_rows);
??? // 重新查詢結果集
??? $query = 'select firstname, lastname, email from tb_test;';
?
??? // 發(fā)送查詢給MySQL
??? $result = $mysqliConn->query($query);
?
??? // 迭代處理結果集
??? while (list($firstname, $lastname, $email) = $result->fetch_row())
??? {
??????? printf("%s %s's email:%s
", $firstname, $lastname, $email);
??? }
??? // 關閉連接
??? $mysqliConn->close();
?>
3.釋放查詢內存
有時可能會獲取一個特別龐大的結果集,此時一旦完成處理,很有必要釋放該結果集所請求的內存。free()方法可以為我們完成這個任務。例如:
復制代碼 代碼如下:
// 與數據庫交互
$query = 'select firstname, lastname, email from tb_test;';
?
// 發(fā)送查詢給MySQL
$result = $mysqliConn->query($query);
?
// 迭代處理結果集
while (list($firstname, $lastname, $email) = $result->fetch_row())
{
??? printf("%s %s's email:%s
", $firstname, $lastname, $email);
}
$result->free();
4.解析查詢結果
一旦執(zhí)行了查詢并準備好結果集,下面就可以解析獲取到的結果行了。你可以使用多個方法來獲取各行中的字段,具體選擇哪一個方法主要取決于個人喜好,因為只是引用字段的方法有所不同。
(1)將結果放到對象中
使用fetch_object()方法來完成。fetch_object()方法通常在一個循環(huán)中調用,每次調用都使得返回結果集中的下一行被填入一個對象,然后可以按照PHP典型的對象訪問語法來訪問這個對象。例如:
復制代碼 代碼如下:
// 與數據庫交互
$query = 'select firstname, lastname, email from tb_test;';
?
// 發(fā)送查詢給MySQL
$result = $mysqliConn->query($query);
?
// 迭代處理結果集
while ($row = $result->fetch_object())
{
??? $firstname = $row->firstname;
??? $lastname = $row->lastname;
??? $email = $row->email;
}
$result->free();
(2)使用索引數組和關聯(lián)數組獲取結果
mysqli擴展包還允許通過fetch_array()方法和fetch_row()方法分別使用關聯(lián)數組和索引數組來管理結果集。fetch_array()方法實際上能夠將結果集的各行獲取為一個關聯(lián)數組、一個數字索引數組,或者同時包括二者,可以說,fetch_row()是fetch_array的一個子集。默認地,fetch_array()會同時獲取關聯(lián)數組和索引數組,可以在fetch_array中傳入參數來修改這個默認行為。
MYSQLI_ASSOC,將行作為一個關聯(lián)數組返回,鍵由字段名表示,值由字段內容表示;
MYSQLI_NUM,將行作為一個數字索引數組返回,其元素順序由查詢中指定的字段名順序決定;
MYSQLI_BOTH,就是默認的選項。
確定所選擇的行和受影響的行
通常希望能夠確定select查詢返回的行數,或者受insert、update或delete影響的行數。
(1)確定返回的行數
如果希望了解select查詢語句返回了多少行,num_rows屬性很有用。例如:
復制代碼 代碼如下:
// 與數據庫交互
$query = 'select firstname, lastname, email from tb_test;';
?
// 發(fā)送查詢給MySQL
$result = $mysqliConn->query($query);
?
// 獲取行數
$result->num_rows;
記住,num_rows只在確定select查詢所獲取的行數時有用,如果要獲得受insert、update或delete影響的行數,就要使用下面總結的affected_rows屬性。
(2)確定受影響的行數
affected_rows屬性用來獲取受insert、update或delete影響的行數。代碼示例見上面的代碼。
執(zhí)行數據庫事務
有3個新方法增強了PHP執(zhí)行MySQL事務的功能,分別為:
1.autocommit函數,啟用自動提交模式;
autocommit()函數控制MySQL自動提交模式的行為,由傳入的參數決定啟動還是禁用自動提交;傳入TRUE,則啟動自動提交,傳入false則禁用自動提交。無論啟用還是禁用,成功時都將返回TRUE,失敗時返回FALSE。
2.commit函數,提交事務;將當前事務提交給數據庫,成功時返回TRUE,否則返回FALSE。
3.rollback函數,回滾當前事務,成功時返回TRUE,否則返回FALSE。
關于事務,我后面還要繼續(xù)總結,這里就簡要的總結了一下這三個API。
不會結束
這只是MySQL學習的開始,不會結束。再接再勵。
$conn=mysql_pconnect("localhost","root","123456");//打開連接
mysql_select_db("數據庫名",$conn);//連接到指定的數據庫
mysql_query("set names utf8");//設置字符編碼
$sql="";
$R=mysql_query($sql);//執(zhí)行SQL語句返回結果集
while($v=mysql_fetch_array($R)){
echo "字段名".$v['title'];
}
?
$hostname = "localhost";//主機地址,一般不需要改
$database = "zx_title";//數據庫表名
$username = "root";//用戶名,,默認一般為root
$password = "123";//mysql數據庫的密碼
$conn= mysql_pconnect($hostname, $username, $password) or trigger_error(mysql_error(),E_USER_ERROR);
?>
?

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHPhasthreecommentstyles://,#forsingle-lineand/.../formulti-line.Usecommentstoexplainwhycodeexists,notwhatitdoes.MarkTODO/FIXMEitemsanddisablecodetemporarilyduringdebugging.Avoidover-commentingsimplelogic.Writeconcise,grammaticallycorrectcommentsandu

The key steps to install PHP on Windows include: 1. Download the appropriate PHP version and decompress it. It is recommended to use ThreadSafe version with Apache or NonThreadSafe version with Nginx; 2. Configure the php.ini file and rename php.ini-development or php.ini-production to php.ini; 3. Add the PHP path to the system environment variable Path for command line use; 4. Test whether PHP is installed successfully, execute php-v through the command line and run the built-in server to test the parsing capabilities; 5. If you use Apache, you need to configure P in httpd.conf

The basic syntax of PHP includes four key points: 1. The PHP tag must be ended, and the use of complete tags is recommended; 2. Echo and print are commonly used for output content, among which echo supports multiple parameters and is more efficient; 3. The annotation methods include //, # and //, to improve code readability; 4. Each statement must end with a semicolon, and spaces and line breaks do not affect execution but affect readability. Mastering these basic rules can help write clear and stable PHP code.

PHPisaserver-sidescriptinglanguageusedforwebdevelopment,especiallyfordynamicwebsitesandCMSplatformslikeWordPress.Itrunsontheserver,processesdata,interactswithdatabases,andsendsHTMLtobrowsers.Commonusesincludeuserauthentication,e-commerceplatforms,for

The steps to install PHP8 on Ubuntu are: 1. Update the software package list; 2. Install PHP8 and basic components; 3. Check the version to confirm that the installation is successful; 4. Install additional modules as needed. Windows users can download and decompress the ZIP package, then modify the configuration file, enable extensions, and add the path to environment variables. macOS users recommend using Homebrew to install, and perform steps such as adding tap, installing PHP8, setting the default version and verifying the version. Although the installation methods are different under different systems, the process is clear, so you can choose the right method according to the purpose.

How to start writing your first PHP script? First, set up the local development environment, install XAMPP/MAMP/LAMP, and use a text editor to understand the server's running principle. Secondly, create a file called hello.php, enter the basic code and run the test. Third, learn to use PHP and HTML to achieve dynamic content output. Finally, pay attention to common errors such as missing semicolons, citation issues, and file extension errors, and enable error reports for debugging.

TohandlefileoperationsinPHP,useappropriatefunctionsandmodes.1.Toreadafile,usefile_get_contents()forsmallfilesorfgets()inaloopforline-by-lineprocessing.2.Towritetoafile,usefile_put_contents()forsimplewritesorappendingwiththeFILE_APPENDflag,orfwrite()w

The key to writing Python's ifelse statements is to understand the logical structure and details. 1. The infrastructure is to execute a piece of code if conditions are established, otherwise the else part is executed, else is optional; 2. Multi-condition judgment is implemented with elif, and it is executed sequentially and stopped once it is met; 3. Nested if is used for further subdivision judgment, it is recommended not to exceed two layers; 4. A ternary expression can be used to replace simple ifelse in a simple scenario. Only by paying attention to indentation, conditional order and logical integrity can we write clear and stable judgment codes.
