在PHP中,row()
函数通常用于从结果集中获取一行作为关联数组、数字数组或两者兼有,这个函数是PDOStatement类的一部分,用于处理数据库查询的结果。
以下是一些使用row()
函数的示例:
1、获取一行作为关联数组:
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn>setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $conn>prepare("SELECT id, firstname, lastname FROM MyGuests"); $stmt>execute(); // 设置结果集为关联数组 $result = $stmt>setFetchMode(PDO::FETCH_ASSOC); // 获取一行数据 $row = $stmt>fetch(PDO::FETCH_ASSOC); print_r($row); } catch(PDOException $e) { echo "Error: " . $e>getMessage(); } $conn = null; ?>
2、获取一行作为数字数组:
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn>setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $conn>prepare("SELECT id, firstname, lastname FROM MyGuests"); $stmt>execute(); // 设置结果集为数字数组 $result = $stmt>setFetchMode(PDO::FETCH_NUM); // 获取一行数据 $row = $stmt>fetch(PDO::FETCH_NUM); print_r($row); } catch(PDOException $e) { echo "Error: " . $e>getMessage(); } $conn = null; ?>
3、获取一行作为关联数组和数字数组:
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn>setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $conn>prepare("SELECT id, firstname, lastname FROM MyGuests"); $stmt>execute(); // 设置结果集为关联数组和数字数组 $result = $stmt>setFetchMode(PDO::FETCH_BOTH); // 获取一行数据 $row = $stmt>fetch(PDO::FETCH_BOTH); print_r($row); } catch(PDOException $e) { echo "Error: " . $e>getMessage(); } $conn = null; ?>
最新评论
本站CDN与莫名CDN同款、亚太CDN、速度还不错,值得推荐。
感谢推荐我们公司产品、有什么活动会第一时间公布!
我在用这类站群服务器、还可以. 用很多年了。