【问题标题】:PHP function giving me exception when trying to display on HTML尝试在 HTML 上显示时,PHP 函数给了我异常
【发布时间】:2016-01-26 12:31:00
【问题描述】:

我在执行 SQL 语句和在我的 HTML 页面上打印结果时遇到问题。

这是函数:

function getFirstName($shId) {


$query  = 'SELECT sh_firstname';
$query .= 'FROM Shaddr';
$query .= 'WHERE shopper_id = ?';

$dbo = db_connect();

try {
    $statement = $dbo->prepare($query);
    $statement->bindParam(1,$shId,PDO::PARAM_INT);
    $statement->execute();
}
catch (PDOException $ex) {
    error_log($ex->getMessage());
    die("Errors encountered while obtaining first name");
}

return $statement;
}

这就是我试图在我的 HTML 中显示它的方式:

<?php 
$results = getFirstName(2);
echo $results;
?>

数据库连接正确,一切正常,因为我有其他工作查询。我得到的错误是“获取名字时遇到的错误”的异常。

这个函数有什么问题?

【问题讨论】:

  • 您的mysql 表是什么样的?
  • 如果您查看错误日志,您会得到更好的错误消息。
  • 下次输出真正的错误或至少查看您的错误日志并从那里获取真正的错误消息。

标签: php html mysql pdo


【解决方案1】:

你需要space before FROM and WHERE子句

$query  = 'SELECT sh_firstname';
$query .= ' FROM Shaddr';
$query .= ' WHERE shopper_id = ?';

你需要从你的getFirstName()返回结果集

 try {
    $statement = $dbo->prepare($query);
    $statement->bindParam(1,$shId,PDO::PARAM_INT);
    $statement->execute();
}
catch (PDOException $ex) {
    error_log($ex->getMessage());
    die("Errors encountered while obtaining first name");
}

return $result = $statement->fetch(PDO::FETCH_ASSOC);

你得到你的价值

<?php 
$results = getFirstName(2);
print_r($results);
?>

【讨论】:

  • 这给了我这个:Catchable fatal error: Object of class PDOStatement could not be convert to string in /home/ubuntu/workspace/delivery_details.php on line 27 Call Stack: 0.0001 232800 1. { main}() /home/ubuntu/workspace/delivery_details.php:0
  • 你的db_connect()函数在哪里??
  • 我相信错误在于这一行:echo $results;因为没有它,页面不会出现错误(当然查询中没有显示任何内容)
  • 非常感谢!!它现在确实显示“数组([sh_firstname] => Jane)”,而不仅仅是 Jane,但我会弄清楚的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-15
  • 1970-01-01
  • 1970-01-01
  • 2014-03-20
  • 1970-01-01
  • 1970-01-01
  • 2015-08-05
相关资源
最近更新 更多