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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?