doubaoguo7469 2017-12-16 01:03
浏览 93
已采纳

PHP和SQL Server - json_decode()期望参数1为字符串

When I execute this line EXEC pl.spGetInfo 'JOHN DOE' in SQL Server Management Studio, it works just fine.

When I call this php file, I am getting an error message 'Warning: json_decode() expects parameter 1 to be string,..' and I cant' find the problem.

<?php 

    // BD
    $conn = dbConnect();

    // Assign parameter values
    $name = 'JOHN DOE';

    $data = getRecords($conn, $name);

    function dbConnect(){
        $DBSERVER = "xxx1";
        $DBUSER   = "xxx2";
        $DBPASS   = "xxx3";
        $DBNAME   = "xxx4";

        // OBDC
        try 
            {       
            $pdo = new PDO("odbc:DRIVER={SQL Server};Server={$DBSERVER};Database={$DBNAME}", $DBUSER, $DBPASS);
            // set the PDO error mode to exception
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            //die(json_encode(array('outcome' => true)));
            //echo "Connected successfully";
            return $pdo;
            }
        catch(PDOException $ex) 
            {
            //die(json_decode(array('outcome' => false, 'message' => 'Unable to connect')));
            echo "Connection failed: " . $ex->getMessage();
            }
    }

    function getRecords($cn, $myname){
        // Prepare the statement
        $sql = 'EXEC pl.spGetInfo ?';
        $stmt = $cn->prepare($sql);
        $stmt->bindParam(1, $myname, PDO::PARAM_STR, 4000);         

        try{
            // Execute the statement 
            $stmt->execute(array($myname));

            // Records found
            $row = $stmt->fetchAll(PDO::FETCH_ASSOC);

            // Free the statement and connection resources
            $stmt->closeCursor();       

            // Return
            return $row;

        }catch (PDOException $e) {
            echo "Statement could not be executed.
";      
            die(json_decode(array('outcome' => false, 'message' => 'Unable to connect')));
            echo "Connection failed: " . $ex->getMessage();         

            // Free the statement and connection resources
            $stmt->closeCursor();
         } 
    }

?>

Regards, Elio Fernandes

  • 写回答

1条回答 默认 最新

  • douhong9210 2017-12-16 01:10
    关注

    For some reason its seems that your PHP code runs in the catch branch and hits die(json_decode(array('outcome' => false, 'message' => 'Unable to connect')));

    json_decode expects a string and returns an array (mostly) but you want to go the other way. So use json_encode().

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog