[英]Fetch Array from class with PDO
Hello I would like to see if someone can help me with the following. 您好,我想看看是否有人可以帮助我进行以下工作。 I am selecting some results from database with PDO, which SQL query is inside a class file inside /class/functions.php.
我正在使用PDO从数据库中选择一些结果,该SQL查询位于/class/functions.php中的类文件中。 The problem is that I can't make it display the results in php file inside a form.
问题是我无法使其在表单内的php文件中显示结果。
Here is the SQL query which I am using inside class/functions.php: 这是我在class / functions.php内部使用的SQL查询:
class Users {
public function selecttema() {
try{
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT * FROM topics";
$stmt = $con->prepare( $sql );
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute();
}catch (PDOException $e) {
echo $e->getMessage();
}
}}
After that on the external file I am trying to display the information from this query with the following code: 之后,在外部文件上,我尝试使用以下代码显示此查询的信息:
<?php
$select = new Users;
$select->selecttema();
while( $row = $stmt->fetch()){
echo '<option value="' . $row['id'] . '">' . $row['topic'] . '</option>';
} ?>
I am getting the following errors: 我收到以下错误:
Notice: Undefined variable: stmt in E:\\xampp\\htdocs\\doccms\\add_doc.php on line 83 注意:未定义的变量:第83行的E:\\ xampp \\ htdocs \\ doccms \\ add_doc.php中的stmt
Fatal error: Call to a member function fetch() on null in E:\\xampp\\htdocs\\doccms\\add_doc.php on line 83 致命错误:第83行的E:\\ xampp \\ htdocs \\ doccms \\ add_doc.php中的null上调用成员函数fetch()
Any help will be welcome. 任何帮助都将受到欢迎。 thanks!
谢谢!
The variable $stmt
is local to the function. 变量
$stmt
是函数的局部变量。 You need to return the value: 您需要返回值:
public function selecttema() {
try{
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT * FROM topics";
$stmt = $con->prepare( $sql );
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute();
return $stmt;
}catch (PDOException $e) {
echo $e->getMessage();
return false;
}
}
Then use that in the caller: 然后在调用方中使用它:
$statement = $select->selecttema();
while ($row = $statement->fetch()) {
echo '<option value="' . $row['id'] . '">' . $row['topic'] . '</option>';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.