将CSV传递给PHP以在JSON中编码多行

时间:2015-12-14 22:46:59

标签: php json csv postman

Postman is an IDE for making APIs in Chrome.

我将路线定义为:

enter image description here

PHP case语句中的逻辑为:

case "checkContactsWithServer":

        if ($userId = authenticateUser($db, $username, $password, $gcmregid)) 
        {   
            $phoneNumCSV = $_REQUEST['phone_num_csv'];

            $syncContactsServerSQL = "SELECT DISTINCT
                                      source_user_sync_id, target_user_sync_id, friend_request_sync_id, status, user_sync_id, phone_number
                                    FROM friends a
                                    RIGHT JOIN (SELECT distinct
                                                  user_sync_id,
                                                  phone_number
                                                FROM users
                                                WHERE phone_number IN ('".$phoneNumCSV."')
                                                AND user_sync_id != '".$userId."'
                                                ) b
                                      ON a.target_user_sync_id = '".$userId."'
                                      AND a.source_user_sync_id = b.user_sync_id                                      
                                      OR a.source_user_sync_id = '".$userId."'
                                      AND a.target_user_sync_id = b.user_sync_id;";

            if($result = $db->query($syncContactsServerSQL))
            {

                $rows = array();

                while($row = $result->fetch_assoc()){
                    $rows[] = array('data' => $row);
                }

                // now all the rows have been fetched, it can be encoded
                echo json_encode($rows);    

            }
            else
            {
                $out = FAILED;          
            }       


        }
        else
        {
            error_log($out, 0);
            $out = FAILED;
        }


    break;

如上所示,将两个电话号码作为CSV传递,即。 “number1,number2”,JSON结果只是一个对象。但是在db中运行查询,应该返回两个:

enter image description here

我知道我在这里缺少一些简单的东西。如何配置此功能?

1 个答案:

答案 0 :(得分:1)

问题是你的查询。你的IN条款都吓坏了。

WHERE phone_number IN ('".$phoneNumCSV."')

...变为

WHERE phone_number IN ('1231231234,1231231234')

正确的语法是

WHERE phone_number IN ('1231231234','1231231234')

您可以通过更改此行来实现此目的。

$phoneNumCSV = $_REQUEST['phone_num_csv'];

对此..

$phoneNumCSV = "'".implode("','", explode(",", $_REQUEST['phone_num_csv']))."'";

然后删除查询中的引号。

WHERE phone_number IN ($phoneNumCSV)

(你不需要双引号或点数)

此外,您应该使用某种预准备语句或至少转义用户输入。