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

问题描述 投票:-1回答:1

当我在SQL Server Management Studio中执行此行EXEC pl.spGetInfo'JOHN DOE'时,它工作得很好。

当我调用这个php文件时,我收到一条错误消息'警告:json_decode()期望参数1为字符串,..'而我无法找到问题。

<?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.\n";      
            die(json_decode(array('outcome' => false, 'message' => 'Unable to connect')));
            echo "Connection failed: " . $ex->getMessage();         

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

?>

此致,Elio Fernandes

php json
1个回答
1
投票

出于某种原因,似乎你的PHP代码在catch分支中运行并且命中die(json_decode(array('outcome' => false, 'message' => 'Unable to connect')));

json_decode需要一个字符串并返回一个数组(大多数情况下),但你想要反过来。所以使用json_encode()

© www.soinside.com 2019 - 2024. All rights reserved.