mysqli_affected_rows() 函數(shù)獲取上一個(gè)MySQL操作中受影響的行數(shù)
mysqli_affected_rows()函數(shù)的作用是:如果在INSERT、UPDATE、REPLACE或DELETE查詢后調(diào)用,則返回受上一操作影響的行數(shù)。
在select語(yǔ)句之后使用時(shí)此函數(shù)返回行數(shù)。
mysqli_affected_rows($con)
序號(hào) | 參數(shù)及說(shuō)明 |
---|---|
1 | con(必需) 這是一個(gè)表示與MySQL Server的連接的對(duì)象。 |
PHP mysqli_affected_rows()函數(shù)返回一個(gè)整數(shù)值,該值指示受先前(SELECT,INSERT,UPDATE,REPLACE或DELETE)操作影響的行數(shù)。
如果前一個(gè)查詢有錯(cuò)誤,則此函數(shù)返回 -1。如果沒(méi)有受影響的行,或者前面的查詢/操作不是上面提到的查詢/操作之一,則此函數(shù)返回0。
此函數(shù)最初是在PHP版本5中引入的,并且可以在所有更高版本中使用。
以下示例演示了mysqli_affected_rows()函數(shù)的用法(程序風(fēng)格)
<?php //創(chuàng)建連接 $con = mysqli_connect("localhost", "root", "password", "mydb"); //查詢以檢索employee表的所有行 mysqli_query($con, "SELECT * FROM employee"); //受影響的行 $rows = mysqli_affected_rows($con); print("受影響的行數(shù): ".$rows); //關(guān)閉連接 mysqli_close($con); ?>
輸出結(jié)果
受影響的行數(shù): 5
在面向?qū)ο蟮娘L(fēng)格中,此函數(shù)的語(yǔ)法為 $con -> affected_rows,其中 $con 是連接對(duì)象-
<?php //創(chuàng)建連接 $con = new mysqli("localhost", "root", "password", "mydb"); //查詢以檢索employee表的所有行 $con -> query("SELECT * FROM employee"); //受影響的行數(shù) $rows = $con -> affected_rows; print("受影響的行數(shù): ".$rows); //關(guān)閉連接 $con -> close(); ?>
輸出結(jié)果
受影響的行數(shù): 5
當(dāng)以下情況下,讓我們檢查此函數(shù)的返回值:沒(méi)有(指定的)查詢,并且查詢有錯(cuò)誤或不影響任何行時(shí):
<?php //創(chuàng)建連接 $con = mysqli_connect("localhost", "root", "password", "mydb"); $rows1 = mysqli_affected_rows($con); print("受影響的行(之前未指定操作): ".$rows1."\n"); //查詢以檢索employee表的所有行 mysqli_query($con, "SELECT * FORM employee"); $rows2 = mysqli_affected_rows($con); print("受影響的行(查詢有錯(cuò)誤時(shí)): ".$rows2."\n"); //查詢以檢索employee表的所有行 mysqli_query($con, "SELECT FIRST_NAME FROM employee WHERE AGE <=19"); $rows3 = mysqli_affected_rows($con); print("受影響的行(當(dāng)查詢不執(zhí)行任何操作時(shí)): ".$rows3."\n"); //關(guān)閉連接 mysqli_close($con); ?>
輸出結(jié)果
受影響的行(之前未指定操作): 0 受影響的行(查詢有錯(cuò)誤時(shí)): -1 受影響的行(當(dāng)查詢不執(zhí)行任何操作時(shí)): 0
下面的示例演示了SELECT,UPDATE,INSERT和DELETE查詢中mysqli_affected_rows函數(shù)的用法-
<?php //建立連接 $con = mysqli_connect("localhost", "root", "password", "mydb"); //查詢employee表的所有行 mysqli_query($con, "SELECT * FROM employee where INCOME > 8000"); print("SELECT查詢影響的行: ".mysqli_affected_rows($con)."\n"); //更新employee表的行的查詢 mysqli_query($con, "UPDATE employee set INCOME=INCOME+5000 where FIRST_NAME in ('Ramya', 'Trupthi', 'Sarmista')"); print("UPDATE查詢影響的行: ".mysqli_affected_rows($con)."\n"); //向employee表中插入行的查詢 mysqli_query($con, "INSERT INTO employee VALUES ('Archana', 'Mohonthy', 30, 'M', 13000, 106)"); print("INSERT查詢影響的行: ".mysqli_affected_rows($con)."\n"); //查詢以刪除employee表的行 mysqli_query($con, "DELETE FROM employee where AGE > 25"); print("DELETE查詢影響的行: ".mysqli_affected_rows($con)."\n"); //關(guān)閉連接 mysqli_close($con); ?>
輸出結(jié)果
SELECT查詢影響的行: 4 UPDATE查詢影響的行: 3 INSERT查詢影響的行: 1 DELETE查詢影響的行: 3