在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; ?>
原创文章,作者:未希,如若转载,请注明出处:https://www.kdun.com/ask/673144.html
本网站发布或转载的文章及图片均来自网络,其原创性以及文中表达的观点和判断不代表本网站。如有问题,请联系客服处理。
发表回复