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')"
);
}
Related
im trying to insert data into a table from a json file but the rows gets 0. not the value from json
DB
JSON code:
{
"posts": [{
"dr_DeviceID": "323",
"dr_UserLocalLat": "38.7482572",
"dr_UserLocalLong": " -9.1847516"
}]
}
$connection = mysql_connect("localhost", "***", "!*****!");
if (!$connection)
{
die('PHP Mysql database connection could not connect : ' . mysql_error());
}
$db_selected = mysql_select_db("*****", $connection);
$result=mysql_query("SELECT * FROM $tbl_name wHERE ad_IMEI=ad_IMEI ");
$i=0;
while($row=mysql_fetch_array($result)) {
$response[$i]['dr_DeviceID'] = $row['ad_IDDevice'];
$response[$i]['dr_UserLocalLat']= $row['user_location_lat'];
$response[$i]['dr_UserLocalLong']= $row['user_location_long'];
$data['posts'][$i] = $response[$i];
$i=$i+2;}
$json_string = json_encode($data);
$file = 'select.json';
file_put_contents($file, $json_string);
$jsondata = file_get_contents('select.json');
$obj = json_decode($jsondata, true);
$id = $obj['posts']['dr_DeviceID'];
$dr_UserLocalLat = $obj['posts']['dr_UserLocalLat'];
$dr_UserLocalLong = $obj['posts']['dr_UserLocalLong'];
$sqlj = "INSERT INTO $tbl_name1 (dr_DeviceID, dr_UserLocalLat, dr_UserLocalLong) VALUES('$dr_DeviceID', '$dr_UserLocalLat', '$dr_UserLocalLong')";
$result=mysql_query($sqlj,$connection);
The problem is that you're trying to access an array of objects as if it was a single one.
With this line here
$data['posts'][$i] = $response[$i];
you add an item to the $data['posts'] array. If your result had more than one row, the json example you've left above would be
{
"posts": [{
"dr_DeviceID": "323",
"dr_UserLocalLat": "38.7482572",
"dr_UserLocalLong": " -9.1847516"
},
{
"dr_DeviceID": "324",
"dr_UserLocalLat": "39.7482572",
"dr_UserLocalLong": " -19.1847516"
}]
}
So, when you decode your json afterwards, you get an array of objects. To access every item in the array, you need some loop cycle. Otherwise, to get the first item from the json, you would need to do
$obj['posts'][0]['dr_UserLocalLat'], instead of $obj['posts']['dr_UserLocalLat'].
How do i add register validation so that user wont be able to use the same user id as others? I'm stuck here as I have tried every code and nothing would work. And it will crash my app.
I'm using Eclipse to do my app.
My php file
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['user_name']) && isset($_POST['user_pwd'])){
$user_name = $_POST['user_name'];
$user_pwd = $_POST['user_pwd'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO doc_user (user_name, user_pwd) VALUES('$user_name', '$user_pwd')");
// 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);
}
change this part in your code
// connecting to db
$db = new DB_CONNECT();
// chack database
$result = mysql_query("select user_name from doc_user where user_name = '$user_name'");
if(mysql_num_rows($result)){
$response["success"] = 0;
$response["message"] = "username not available.";
// echoing JSON response
echo json_encode($response);
exit;
}
// mysql inserting a new row
$result = mysql_query("INSERT INTO doc_user (user_name, user_pwd) VALUES('$user_name', '$user_pwd')");
I am using php with mysql database to do some insert.
I have 2 tables.
user
status
where the second table has as foreign key user_id to relate between these 2 tables
my problem is that when i insert into status table the user_id field do change and take 0 no matter what is the user_id.
so how to fix this problem ???
this is the code of login.php
<?php
//array for JSON response
$response = array();
// check for required fields
if(empty($_POST['user']) || empty($_POST['password'])){
$response["success"] = 0;
$response["message"] = "enter Both Fields";
// echoing JSON response
die (json_encode($response));
}
else if (isset($_POST['user']) && isset($_POST['password']) ) {
$user = $_POST['user'];
$password = $_POST['password'];
// include db connect class
require_once '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$sql = mysql_query("Select user, password from users where user='$user'")or die(mysql_error());
$count_query = mysql_num_rows($sql);
if($count_query >0){
$response["success"] = 1;
$response["message"] = "correct Informations";
// echoing JSON response
echo json_encode($response);
}
else{
$response["success"] = 0;
$response["message"] = "Wrong User Or Pass";
// 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);
}
?>
status.php
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
if(empty($_POST['status'])){
$response["success"] = 0;
$response["message"] = "You must Write something";
// echoing JSON response
die (json_encode($response));
}
// check for required fields
else if (isset($_POST['status'])) {
$status = $_POST['status'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO status(status, user_id) VALUES('$status' , '$last_insert_id')") or die(mysql_error);
$last_insert_id = mysql_insert_id();
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Your Status has been saved.";
// echoing JSON response
die (json_encode($response));
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
die (json_encode($response));
}
}
?>
i am using php with android so their is no html form
You can't. mysql_insert_id() only applies to the LAST insert performed. If you're doing two inserts, and call insert_id() after the second one, the first ID is lost.
There is no way around this.
You must have something like:
INSERT INTO foo ....
$fooid = mysql_insert_id();
INSERT INTO bar .... foo_id=$fooid
$barid = mysql_insert_id();
Given that your code actually seems to be split into multiple pages, it's even worse. mysql_insert_id() only applies to the CURRENT connection to the database. Once your first script exits, the connection is closed and the insert_id is lost.
The next script will get a NEW connection, and have its own completely separate insert_id system going.
For chaining multiple pages together like this, you'll have to retrieve/pass the insert ID around yourself, e.g.
page1:
INSERT ...
$_SESSION['page1_id'] = mysql_insert_id();
page2:
$last_id = $_SESSION['page1_id'];
INSERT ..... id=$last_id
how to fix the error:
Undefined variable : id in c:\wamp\www\android_connect\status.php in 38
what i am doing wrong ???
status.php
<?php
ob_start();
session_start();
//array for JSON response
$response = array();
if(isset($_SESSION['id']))
{
$id= $_SESSION['id'];
}
//var_dump ($id);
// include db connect class
require_once '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for required fields
if(empty($_POST['status'])){
$response["success"] = 0;
$response["message"] = "Your Text Field is empty";
// echoing JSON response
die (json_encode($response));
}
else if (isset($_POST['status'])) {
$status = $_POST['status'];
$sql = mysql_query("INSERT INTO status (status_text, uid)VALUES('$status', '$id')")or die(mysql_error());
if ($sql) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Status Saved.";
// echoing JSON response
die (json_encode($response));
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Error in saving the status.";
// echoing JSON response
die (json_encode($response));
}
}
ob_end_flush();
?>
the error is in the insert query but i do not know how to fix it.
it have something with the $_SESSION can anyone help me ??
The error you get means $id is unset. In your code there isn't a check for the $id variable.
Change else if (isset($_POST['status'])) { to else if (isset($_POST['status']) && isset($id)) {
and add an else statement, something like this:
else {
// failed to insert row because of missing $id
$response["success"] = 0;
$response["message"] = "Error in saving the status, session variable $id missing";
// echoing JSON response
die (json_encode($response));
}
Change the insert query like this,
$sql = mysql_query("INSERT INTO status (status_text, uid)VALUES('".$status."', '".$id."')")or die(mysql_error());
I'm trying to implement a way to keep names, entered in an android app and sent to a server, from being used again. I figured the easiest way to do this is create another table and every time a product is added the name is added to the name table. I'm very new to php so this may seem like a very simple question but how would I go about checking the table to see if name is already on it.
here is what I go so far(most of it was already there just the commented out is my thought process)
<?php
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['name']) && isset($_POST['longitude']) && isset($_POST['latitude']) && isset($_POST['pavement']) && isset($_POST['traffic']) && isset($_POST['environment'])) {
//if(Name is not already in list of names){
$name = $_POST['name'];
$longitude = $_POST['longitude'];
$latitude = $_POST['latitude'];
$pavement = $_POST['pavement'];
$traffic = $_POST['traffic'];
$environment = $_POST['environment'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO spots(name, longitude, latitude, pavement, traffic, environment) VALUES('$name', '$longitude', '$latitude', '$pavement', '$traffic', '$environment')");
//add new name to table
//$result2 = mysql_query("INSERT INTO names(name) VALUES('$name')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Spot 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 {
// name already taken
$response["success"] = 0;
$response["message"] = "Name has already been taken.";
// 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);
}
?>
Sorry for the simple question but thank you in advance,
Tyler
You could do a SELECT query like this:
$query = mysql_query("SELECT * FROM spots WHERE name='$name'");
$count = mysql_num_rows($query);
if($count == 0){
// name not in database
}
else{
// name is in database
}
However, this is using mysql_ functions which are deprecated. Please use mysqli_ functions instead.
Make name primary key in names table or apply unique constrain and check for duplicate key error after insertion in names table
Or you can first query table to see if name is already there or not
$result3 = mysql_query("SELECT * FROM names WHERE name='$name'");
if(mysql_num_rows($result3) <= 0 )
{
// name is not in names table
// now insert in names table
}