如何使用PDO迭代重新调整的调用函数变量



我目前正在努力迭代一个结果集,该结果集存储在一个单独文件的函数中,我该如何迭代该变量集?

请参阅下面的示例代码。

list.classes.php

class Lists extends Dbh {
public function getCountries() {
$stmt = $this->connect()->prepare("EXEC spl_countries");
if(!$stmt->execute()) {
$stmt = null;
header("location: ../index.php?error=stmtfailed");
exit();
}
if($stmt->rowCount() == 0) {
$stmt = null;
header("location: ../index.php?error=countrynotfound");
exit();
}
return $stmt;
}
}

spl_countries

IF EXISTS(SELECT * FROM dbo.sysobjects
WHERE ID = OBJECT_ID(N'spl_countries')
AND OBJECTPROPERTY(ID, N'IsProcedure') = 1)
BEGIN
PRINT 'DROPPING THE STORED PROCEDURE spl_countries';
DROP PROCEDURE spl_countries;
END
GO
PRINT 'CREATING THE STORED PROCEDURE spl_countries';
GO
CREATE PROCEDURE spl_countries
AS 
SELECT countryID, country, iso2, iso3, phoneCode, niceName, numCode FROM CO_Country GROUP BY countryID, country, iso2, iso3, phoneCode, niceName, numCode ORDER BY country ASC
RETURN

test.php

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/style.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://unicons.iconscout.com/release/v3.0.6/css/line.css">
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>
</head>
<body style="background-color:#404258;">
<?php
//require('admin.sidebar.php');
include "classes/dbh.classes.php";
include "classes/list.classes.php";
$listCountry = new Lists();
$listCountry->getCountries();
?>
<div class="col">
<div class="form-outline">
<select class="form-select" aria-label="Default select example" id="form-contactType">
<?php
while($row = $listCountry->fetch(PDO::FETCH_ASSOC)) {
echo "<option value=".$row['countryID'].">".$row['phoneCode']."</option>";
}
?>
<!--<option selected>Open this select menu</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>-->
</select>
<label for="form-contactType" class="form-label" >Contact Type</label>
</div>
</div>
</body>
</html>

我在打开PHP文件时收到以下错误

致命错误:未捕获错误:调用C:\xamplep\htdocs\BusinessSolution\test:128中的未定义方法Lists::fetch((堆栈跟踪:#0{main}在C:\examplep\htdocs\BusinessSolution\test.php 中抛出

我不确定在getCountrys((中循环返回变量的正确步骤是什么?

您要么需要将返回的值存储在变量中,要么只需迭代方法调用的结果。

$listCountry = new Lists();
$countries = $listCountry->getCountries();
foreach($countries as $country) {
}

$listCountry = new Lists();
foreach($listCountry->getCountries() as $country) {
}

相关内容

  • 没有找到相关文章

最新更新