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().

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

报告相同问题?

悬赏问题

  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常
  • ¥15 关于风控系统,如何去选择