mysqli_fetch_lengths()函数返回结果集中的字段长度。
PHP结果对象(mysqli_result类)表示由SELECT或DESCRIBE或EXPLAIN查询返回的MySQL结果。
mysqli_fetch_lengths()函数接受结果对象作为参数,检索给定结果当前行中列的长度,并以数组形式返回它们。
mysqli_fetch_lengths($result);
序号 | 参数及说明 |
---|---|
1 | result(必需) 这是表示结果对象的标识符。 |
PHP mysqli_fetch_lengths()函数返回一个数组(整数),该数组包含(当前行的)每列的长度/大小(如果成功),并且在出现错误的情况下返回布尔值FALSE。
此函数最初是在PHP版本5中引入的,并且可以在所有更高版本中使用。
以下示例演示了mysqli_fetch_lengths()函数的用法(面向过程风格)-
<?php $con = mysqli_connect("localhost", "root", "password", "mydb"); mysqli_query($con, "CREATE TABLE myplayers(ID INT, First_Name VARCHAR(255), Last_Name VARCHAR(255), Place_Of_Birth VARCHAR(255), Country VARCHAR(255))"); print("创建表.....\n"); mysqli_query($con, "INSERT INTO myplayers values(1, 'Sikhar', 'Dhawan', 'Delhi', 'India')"); mysqli_query($con, "INSERT INTO myplayers values(2, 'Jonathan', 'Trott', 'CapeTown', 'SouthAfrica')"); mysqli_query($con, "INSERT INTO myplayers values(3, 'Kumara', 'Sangakkara', 'Matale', 'Srilanka')"); print("插入记录.....\n"); //检索表的内容 $res = mysqli_query($con, "SELECT * FROM myplayers"); //行的长度 $row = mysqli_fetch_row($res); $lengths = mysqli_fetch_lengths($res); print_r($lengths); mysqli_free_result($res); mysqli_close($con); ?>
输出结果
创建表..... 插入记录..... Array ( [0] => 1 [1] => 6 [2] => 6 [3] => 5 [4] => 5 )
在面向对象风格中,此函数的语法为$result->lengths;。以下是面向对象风格中此函数的示例;
<?php //建立连接 $con = new mysqli("localhost", "root", "password", "mydb"); $con -> query("CREATE TABLE Test(Name VARCHAR(255), AGE INT)"); $con -> query("insert into Test values('Raju', 25),('Rahman', 30),('Sarmista', 27)"); print("创建表.....\n"); $stmt = $con -> prepare( "SELECT * FROM Test WHERE Name in(?, ?)"); $stmt -> bind_param("ss", $name1, $name2); $name1 = 'Raju'; $name2 = 'Rahman'; //执行语句 $stmt->execute(); //检索结果 $res = $stmt->get_result(); $row = $res->fetch_row(); $len = $res ->lengths; print_r($len); //结束语句 $stmt->close(); //关闭连接 $con->close(); ?>
输出结果
创建表..... Array ( [0] => 4 [1] => 0 )
此函数要检索长度,必须在使用 mysqli_fetch_row 或 mysqli_fetch_array 或 mysqli_fetch_object 方法读取行后调用,否则返回false:
<?php $con = mysqli_connect("localhost", "root", "password", "mydb"); mysqli_query($con, "CREATE TABLE data(ID INT, Name VARCHAR(255), Age INT)"); mysqli_query($con, "INSERT INTO data values(1, 'Mohan', 25)"); mysqli_query($con, "INSERT INTO data values(2, 'Syamala', 36)"); print("插入记录.....\n"); //检索表的内容 $res = mysqli_query($con, "SELECT * FROM data"); //行的长度 $bool = $lengths = mysqli_fetch_lengths($res); if($bool){ print("检索到长度"); }else{ print("失败"); } print_r($lengths); mysqli_free_result($res); mysqli_close($con); ?>
输出结果
插入记录..... 失败测试看看‹/›