通过PDO获取所有记录

时间:2017-01-28 06:48:06

标签: php pdo

尝试从表中获取所有数据,但既不显示数据也不显示任何错误。我知道我错过了一些东西,但我不确切知道它是什么。

<?php
$st = $pdo->prepare("SELECT plan_id, plan_name, zone_id, operator_price, selling_price, validity, plan_type FROM plan_tbl");
$st->execute();
$cnt=$st->rowCount();
$user_record=$st->fetchAll();
}
catch (PDOException $ex) {
    echo  $ex->getMessage();
}
$rowdata="<tbody>";
foreach($plan_record as $plan_record1){
    $rowdata.="<tr>";
    $sr_no = $plan_record1['plan_id'];
    $plan_name = $plan_record1['plan_name'];
    //$user_fullname = $user_record1['fname'] . " " . $user_record1['mname'] . " " . $user_record1['lname'];
    //echo $user_fullname;
    $zone_id = $plan_record1['zone_id'];
    $operator_price = $plan_record1['operator_price'];
    $selling_price = $plan_record1['selling_price'];
    $validity = $plan_record1['validity'];
    $plan_type = $plan_record1['plan_type'];
    $icon="<i class='fa fa-pencil-square-o pad' aria-hidden='true'></i><i class='fa fa-times pad' aria-hidden='true'></i>";
    $rowdata.="</tr>";
}
?>

2 个答案:

答案 0 :(得分:1)

我会使用有意义的变量名,例如$ plans和$ plan。另请注意,您不是

<?php
$st = $pdo->prepare("SELECT plan_id, plan_name, zone_id, operator_price, selling_price, validity, plan_type FROM plan_tbl");
$st->execute();
$cnt=$st->rowCount();
$plans=$st->fetchAll();
}
catch (PDOException $ex) {
    echo  $ex->getMessage();
}
$rowdata="<tbody>";
foreach($plans as $plan){
    $rowdata.="<tr>";
    $rowdata .= "<td>{$plan['plan_id']}</td>";
    $rowdata .= "<td>{$plan['plan_name']}</td>";
    $rowdata .= "<td>{$plan['zone_id']}</td>";
    $rowdata .= "<td>{$plan['operator_price']}</td>";
    $rowdata .= "<td>{$plan['selling_price']}</td>";
    $rowdata .= "<td>{$plan['validity']}</td>";
    $rowdata .= "<td>{$plan['plan_type']}</td>";
    $rowdata .= "<td><i class='fa fa-pencil-square-o pad' aria-hidden='true'></i><i class='fa fa-times pad' aria-hidden='true'></i></td>";
    $rowdata.="</tr>";
}
$rowdata .= "</tbody>";

echo $rowdata;

您还需要对循环中的数据执行某些操作,否则每次循环时都会覆盖它。例如,您可能希望更改每一行,使它们看起来像这样:

$rowdata .= "<td>{$plan['plan_id']}</td>";

而不是

$sr_no = $plan['plan_id'];

退出循环后,请确保显示:

echo $rowdata

我还把你关闭了吗?&gt;标签,如果它位于文件的最末端,可能会导致一些问题。

答案 1 :(得分:0)

使用$user_record代替$plan_record,因为您没有在代码中声明它

foreach($user_record as $plan_record1){
    $rowdata.="<tr>";
    $sr_no = $plan_record1['plan_id'];
    $plan_name = $plan_record1['plan_name'];
    //$user_fullname = $user_record1['fname'] . " " . $user_record1['mname'] . " " . $user_record1['lname'];
    //echo $user_fullname;
    $zone_id = $plan_record1['zone_id'];
    $operator_price = $plan_record1['operator_price'];
    $selling_price = $plan_record1['selling_price'];
    $validity = $plan_record1['validity'];
    $plan_type = $plan_record1['plan_type'];
    $icon="<i class='fa fa-pencil-square-o pad' aria-hidden='true'></i><i class='fa fa-times pad' aria-hidden='true'></i>";
    $rowdata.="</tr>";
}