-1

我在 wamp 服务器中有 PHP 文件。当我在 localhost 中运行该文件时,它会出现如下错误。

这是我的 PHP 文件:

<?php
$response = array({
    "success": [
        {
            "message": "Required field id missing"
        },
        {
            "message": "successfully created."
        },
        {
            "message": "Oops! An error occured"
        }
    ]}
);
 
if (isset($_POST['name']) && isset($_POST['price']) && isset($_POST['description'])) {
 
    $name = $_POST['name'];
    $price = $_POST['price'];
    $description = $_POST['description'];
 

    require_once __DIR__ . '/db_connect.php';
 
    
    $db = new DB_CONNECT();
 
   
    $result = mysql_query("INSERT INTO products(name, price, description) VALUES('$name', '$price', '$description')");
 
   
    if ($result) {
        
        $response["success"] = 1;
        $response["message"] = "Product successfully created.";
 
       
        echo json_encode($response);
    } else {
      
        $response["success"] = 2;
        $response["message"] = "Oops! An error occurred.";
 
    
        echo json_encode($response);
    }
} else {
   
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";
 
    
    echo json_encode($response);
}
?>

当我在 localhost 中运行它时,出现以下错误,

( ! ) 解析错误:语法错误,第 2 行 D:\wamp\www\android\create_product.php 中的意外 '{',期待 ')'

还建议我如何设置本地路径以在浏览器中运行 php 文件。

4

2 回答 2

1

您的数组格式错误,顺便说一句,您不需要它,因为您在条件中向数组添加消息,所以只需删除这部分:

$response = array({
    "success": [
        {
            "message": "Required field id missing"
        },
        {
            "message": "successfully created."
        },
        {
            "message": "Oops! An error occured"
        }
    ]}
);
于 2013-10-30T06:51:20.283 回答
0

您的代码看起来更好:

  • 您不应该在每个条件语句结束后回显响应,您可以执行一次。
  • 此外,在使用isset函数时,您可以根据需要设置任意数量的参数。


 isset($_POST['name']) && isset($_POST['price']) && isset($_POST['description'])

等于:

 isset($_POST['name'],$_POST['price'],$_POST['description'])

最后:

if (isset($_POST['name'],$_POST['price'],$_POST['description'])) {

    $name = $_POST['name'];
    $price = $_POST['price'];
    $description = $_POST['description'];


    require_once __DIR__ . '/db_connect.php';


    $db = new DB_CONNECT();


    $result = mysql_query("INSERT INTO products(name, price, description) VALUES('$name', '$price', '$description')");


    if ($result) {
        $response["success"] = 1;
        $response["message"] = "Product successfully created.";
    } else {
        $response["success"] = 2;
        $response["message"] = "Oops! An error occurred.";
    }
} else {
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";
}

echo json_encode($response);
于 2013-10-30T07:02:58.097 回答