PHP 准备的语句:回显结果


PHP Prepared Statements: Echo the Result

我想通过回显显示结果('Positio: 2' 或 'Position: 1')但是$statement是类 PDOStatement 的对象而不是字符串,我如何让它只看到$statement的结果?谢谢

<?php
$pdo = new PDO('mysql:host=localhost;dbname=testdb1', 'root', '');
    $idV = $_GET['id'];
$statement = $pdo->prepare("SELECT position FROM idtabelle WHERE idnumber = ?");
$statement->execute(array($idV));
echo "Position: //$result_Of_Statement''  ";
?>
以下是

我的做法:

$statement = $pdo->prepare("SELECT position FROM idtabelle WHERE idnumber = :idV");
$statement->bindParam(':idV', $idV);
$statement->execute();
while ($row = $statement->fetch(PDO::FETCH_ASSOC))
{
  echo $row['position'];
}

如果您愿意,您也可以取消 while 循环。

我会获取结果并使用print_rvar_dump快速查看结果。

$statement = $pdo->prepare("SELECT position FROM idtabelle WHERE idnumber = ?");
$statement->execute(array($idV));
$result = $statement->fetch(PDO::FETCH_ASSOC); //Or fetchAll()
echo "Position: ". print_r($result);

这是一种快速而肮脏的检查结果的方法。如果要添加一些格式:

$result = $statement->fetch(PDO::FETCH_ASSOC); 
for( $result as $key=>$value ){
    echo ucfirst($key) .": $value 'n";
}
如果要获取多行,

请将其包装在一个循环中,每次迭代都会获取新行

while( $result = $statement->fetch(PDO::FETCH_ASSOC) ){
  echo "===New Row===";
  for( $result as $key=>$value ){
    echo ucfirst($key) .": $value 'n";
  }
}