【问题标题】:Encode json in PHP file在 PHP 文件中编码 json
【发布时间】:2017-02-17 09:18:00
【问题描述】:

实际上,我在我的 php 文件(正在工作的 PHP)中进行了 JSON 编码,并且它正在工作,但是当我在另一个 PHP(错误 PHP)文件中执行相同的步骤时,它不起作用请帮助我

PHP 错误

<?php

require_once('dbConnect.php');
$id =$_POST['id'];
$sql= "select title,description,image,price,cid FROM products a where a.cid='$id'";

$res=mysqli_query($con,$sql);

$result = array();

while ($row=mysqli_fetch_array($res)){
        array_push($result,array('title'=>$row['0'],
                                 'description'=>$row['1'],
                                 'image'=>$row['2'],
                                 'price'=>$row['3'],
                                )
        );
}
echo json_encode(($result));

mysqli_close($con);
?>

我知道这是一个非常愚蠢的问题,但我不明白为什么 Erro.php 文件不工作,当我在查询中硬编码 $id 时 Error.php 工作 编辑:删除工作 php

【问题讨论】:

  • 尝试使用准备好的语句。
  • 检查var_dump($_POST['id'])的值。
  • 我是 php 新手,你能提供一些例子吗
  • delete 评论我的错误结果为NULL
  • 什么不工作?

标签: php json mysqli pdo


【解决方案1】:

那么我们必须假设$_POST['id'] 不存在或不包含有效数据或查询中有错误。

您应该编写类似这样的代码,至少以类似这样的可用方式报告此类情况

<?php

require_once('dbConnect.php');

if ( ! isset($_POST['id']) ) {
    echo json_encode(array('status'=>false, 'msg'=>'Input missing'));
    exit;
}

$_POST['id'];

// amend select to select only what you want
$sql= "select title,description,image,price
        FROM products
        where cid = '$id'";

$res=mysqli_query($con,$sql);
if ( ! $res ) {
    echo json_encode(array( 'status'=>false, 
                            'msg'=>'Query failed',
                            'sql_msg' => mysqli_error($con)
                            )
                    );
    exit;
}

$result = array();

// use mysqli_fetch_assoc() and the columns names are used
// so you can simply add the $row to the $result array
while ($row=mysqli_fetch_assoc($res)){
    $result[] = $row;
}

echo json_encode(array('status'=>true, 'results'=>$result));
?>

现在对您的 javascript 做一个小修改,以便它首先检查状态,并在测试时显示任何错误消息。

【讨论】:

  • 谢谢你,现在我明白我的 POST 值为 null 所以这就是我面临这个问题的原因......
  • 我的输入就像 "{"id":"1"}" (在jsonObject中编码)
  • 好的,抱歉不清楚。是$_POST['id'] = "{"id":"1"}" 还是$_POST = "{"id":"1"}"
  • 我认为这是一个键值对,所以我更改了我的 php $stripe_json = json_decode($_POST['id']); $ida=$stripe_json->id; $sql="select title,description,image,price,cid FROM products a where a.cid='".$ida."'";但还是不行
  • print_r($_POST); 添加到您的代码中显示什么
猜你喜欢
  • 2012-05-11
  • 2015-11-18
  • 2014-08-29
  • 2022-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-05
相关资源
最近更新 更多