I have an android application that sends some array of strings to php. php takes that array and inserts that data value individually into database. now when the data is inserted, each row data get an additional white space along with it. how to eliminate it. i tried REPLACE with the string but when tried REPLACE, am unable to insert anything. a white space is added when second row is entered.
here is the PHP code for entering data.
<?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);
}
when i display it using JSON, it looks like this..
{
"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"
},
a white space is inserted every time a row is inserted i don't know how to solve this problem.
Have you tried to do a trim () in the loop?
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')"
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With