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 准备学习小程序搭建,谁能手把手的教我啊?
  • ¥15 关于#嵌入式硬件#的问题:树莓派第一天重装配置python和opencv后第二天打开就成这样,瞎捣鼓搞出来文件夹还是没把原来的界面调回来
  • ¥20 Arduino 循迹小车程序电路出错故障求解
  • ¥20 Arduino 循迹小车程序电路出错故障求解
  • ¥100 AT89C52单片机C语言调试之后再回答
  • ¥15 AT89C52单片机C语言串口助手发送数据包返回值
  • ¥15 C++数组中找第二小的数字程序纠错
  • ¥50 MATLAB APP 制作出现问题
  • ¥15 wannier复现图像时berry曲率极值点与高对称点严重偏移
  • ¥15 利用决策森林为什么会出现这样·的问题(关键词-情感分析)