我想知道为什么我无法在PHP中执行此操作。
db.php中
function db_connect(){
try {
$db = new PDO('xxxxxxxx');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
return $db;
}
FUNCTION.PHP
require_once('db.php');
$db = db_connect();
//Incoming AJAX request
if(isset($_POST['rowId'])) $rowId = $_POST['rowId'];
if(isset($_POST['func'])){
$func = $_POST['func'];
switch($func){
case "info":
echo json_encode(info($rowId));
break;
}
}
function info($rowId){
global $db;
$rowInfo = $db->prepare("SELECT name FROM table WHERE id = :rowId");
$rowInfo->bindParam(':rowId', $rowId);
$rowInfo->execute();
//do more stuff
我得到这个错误
Catchable fatal error: Object of class PDO could not be converted to string
我能解决这个问题两种方式
- 不要使用任何约束PARAMS(这显然是没用这里)
- 通
$db
到函数
问题是什么?该错误发生在execte()上。我可以删除任何东西,但仍然会出现错误。
您还需要在全局范围内分配'$ db'。您的摘录中没有任何内容没有断言这是包含“functions.php”的地方。 – mario 2014-10-03 04:46:33
@mario他有'$ db = db_connect();',它将它分配到全局范围中。 – Barmar 2014-10-03 04:48:12
错误消息表明变量IS设置为PDO对象,但您在需要字符串的地方使用它,如'echo $ db;'。有哪些错误发生? – Barmar 2014-10-03 04:49:22