在向mysql输入数据时删除额外的空间

时间:2015-10-11 09:50:47

标签: php android mysql

我有一个Android应用程序,它发送一些字符串数组到PHP。 php获取该数组并将该数据值单独插入数据库。现在,当插入数据时,每个行数据都会获得一个额外的空白区域。 如何消除它。我尝试使用字符串REPLACE但是当尝试REPLACE时,我无法插入任何内容。 输入第二行时会添加空格。

这是用于输入数据的PHP代码。

<?php
$response = array();

// check for required fields
if (isset($_POST['docname']) && isset($_POST['prods'])) {

    $docname = $_POST['docname'];
    $prods = $_POST['prods'];

    $e = trim($prods, '[]');
    $pr = preg_split("/[,]/", $e);

    $img = "image/";

    //$docs=array_unique($pr);

    $count = count($pr);

    define("DB_HOST", "localhost");
    define("DB_USER", "root");
    define("DB_PASSWORD", "root");
    define("DB_DATABASE", "android_api");

    $con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD) or die(mysqli_connect_error());

    // selecting database
    $db = mysqli_select_db($con, DB_DATABASE) or die(mysqli_connect_error());

    foreach ($pr as $val) {

        $img = $img . $val . ".jpg";

        // mysql inserting a new row
        $result = mysqli_query($con, 
            "INSERT INTO product_entered(id, doc_name, product_name, image_path, count) 
            VALUES('$id','$docname','$val','$img','$count')"
        );
    }

    // check if row inserted or not
    if ($result) {

        // successfully inserted into database
        $response["success"] = 1;
        $response["message"] = "Product successfully created.";

        // echoing JSON response
        echo json_encode($response);
    } 
    else {

        // failed to insert row
        $response["success"] = 0;
        $response["message"] = "Oops! An error occurred.";

        // echoing JSON response
        echo json_encode($response);
    }
} 
else {

    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";

    // echoing JSON response
    echo json_encode($response);
}

当我使用JSON显示它时,它看起来像这样..

 {
        "id": "15",
        "doc_name": "Dr. XYZ",
        "product_name": " PROTONIL-D",
        "image_path": "image/image/ PROTONIL-D.jpg",
        "count": "7"
    },
    {
        "id": "14",
        "doc_name": "Dr. XYZ",
        "product_name": " PROATH_PLUS",
        "image_path": "image/image/ PROATH_PLUS.jpg",
        "count": "7"
    },

每次插入行时都会插入一个空格 我不知道如何解决这个问题。

1 个答案:

答案 0 :(得分:1)

你试过在循环中做trim ()吗?

foreach ($pr as $val) {
    $val = trim($val);

    $img = $img . $val . ".jpg";

    $result = mysqli_query($con, 
        "INSERT INTO product_entered(id, doc_name, product_name, image_path, count) 
        VALUES('$id','$docname','$val','$img','$count')"
    );
}