错误:类PDO的对象无法转换为字符串

时间:2017-01-10 21:23:19

标签: php mysql

我正在使用slim-framework v2和php来获取json输出。使用此代码,我收到了关于该主题的错误。 mysql表的格式错误,现在无法更改,所以我以这种方式制作这些函数,因为我不是很有经验。 解决这个问题的最佳方法是什么?如果可以使用sql命令完成更好,那么我可以从主循环中删除这些函数吗?循环中的函数是不是很糟糕? ps:如果主题看起来不对,请告诉我。

test()是客户ID的主要循环

function test($server, $user, $pass, $db) {
  $result = array();
  $sql = "SELECT cid from tasks where total!=0";
  $db = newDB($server, $user, $pass, $db);
  $stmt = $db->prepare($sql);
  $stmt->execute();
  foreach ($stmt as $v) {
    $result[] = ['cid'=> $v['cid'], 'test'=> toGet($server, $user, $pass, $db, $v['cid']), 'test2'=> toGet2($server, $user, $pass, $db, $v['cid'])];
  }
  echo json_encode($result, JSON_FORCE_OBJECT);
}

和其他功能

function toGet($server, $user, $pass, $db, $id) {
  $sql = "SELECT sum(`poso`) as posoe from `economics` where `custid`=:id and flag=0";
  $db = newDB($server, $user, $pass, $db);
  $stmt = $db->prepare($sql);
  $stmt->bindParam("id", $id);
  $stmt->execute();
  $row = $stmt->fetch(PDO::FETCH_NUM);
  return $row[0];
}

function toGet2($server, $user, $pass, $db, $id) {
  $sql = "SELECT sum(`poso`) as posoe from `economics` where `custid`=:id and flag=1";
  $db = newDB($server, $user, $pass, $db);
  $stmt = $db->prepare($sql);
  $stmt->bindParam("id", $id);
  $stmt->execute();
  $row = $stmt->fetch(PDO::FETCH_NUM);
  return $row[0];
}

非常感谢!

更新 打开debug $ app-> config('debug',true),最终得到了错误 键入:ErrorException 代码:4096 消息:类PDO的对象无法转换为字符串 文件:/var/www/api/newdb.php 行:6

function newDB($host, $user, $pass, $db) {
    $dbhost= $host;
    $dbuser= $user;
    $dbpass= $pass;
    $dbname= $db;
    $dbConnection = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
    $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $dbConnection->query('set names utf8');
    return $dbConnection;
}

UPDATE2:Slim conf

include 'newdb.php';
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
$app->config('debug', true);
$app->response->setStatus(200);
$app->contentType('application/json; charset=utf-8');
$app->get('/test/:server/:user/:pass/:db', 'test');
$app->get('/', function() use($app) {
    $app->response->setStatus(200);
    echo "Welcome!";
});
$app->run();

1 个答案:

答案 0 :(得分:0)

问题由Freenode上的一个人通过单个MYSQL查询解决。

- Reconnecting on db for each query was bad.
- toGet() toGet2() removed 

我可以使用单个查询

获取数据
SELECT t1.custid as cid, sum(if(t2.flag=0,t2.poso,0)) as posoX,
sum(if(t2.flag=1,t2.poso,0)) as posoY from tasks t1 
left join economics t2 on t2.custid=t1.custid and t2.flag in (0,1) group by t1.custid;