PDO新手。这是我的功能。我们连接到数据库,一切正常,但是这个函数在调用时会杀掉要执行的其余PHP。显然它有问题。
$dbh = new PDO("mysql:host=$host;dbname=$database", $username, $password);
global $dbh;
/*** set the error reporting attribute ***/
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
function selectall($table){
$stmt = $dbh->prepare("SELECT * FROM :table");
$stmt->bindParam(':table', $table, PDO::PARAM_STR,20);
$stmt->execute();
$result = $stmt->fetchAll();
return $result;
}
在这样的页面上调用:
<?php $telephones = selectall('telephone'); foreach($telephones as $telephones) { echo $telephone['title'].', '; } ?>
///编辑 - 我已经尝试了所有方法,并且在页面上调用时函数仍然存在。这是整个代码。为了测试目的略微修改。
try {
$dbh = new PDO("mysql:host=$host;dbname=$database", $username, $password);
/*** set the error reporting attribute ***/
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM system";
foreach ($dbh->query($sql) as $row)
{
$url = $row['url'];
$election = $row['election'];
$election_date = $row['election_date'];
$sitename = $row['sitename'];
}
//FUNCTION
function selectall($table){
global $dbh;
$sql = "SELECT * FROM telephone";
foreach ($dbh->query($sql) as $row){
print $row['title'] .' - '. $row['name'] . '<br />';
}
}
/** close database connections **/
$dbh = null;
}
catch(PDOException $e) {
echo $e->getMessage();
}
函数外的代码即。反映表系统的那个工作正在完美但是函数内部的函数在以后被调用为函数时会在调用它之后将其删除并且不执行。
答案 0 :(得分:0)
我认为问题是:$telephones as $telephones
试试这个:
$telephones = selectall('telephone'); foreach($telephones as $telephone) { echo $telephone['title'].', '; }
答案 1 :(得分:0)
当您尝试使用未定义的变量($dbh
)作为对象时,第二行会产生致命错误。
您需要从全局范围中导入它,如下所示:
global $dbh;
或将其作为参数传递给函数。
修复此问题后,您的代码仍无效,因为您无法使用参数作为标识符(表名或列名,甚至是限制和偏移量)。不幸的是,你必须在那里使用字符串连接。