Inset php json encoded array into database - php

I need to insert elements of a php encoded array into a database and I'm completely stuck. I have first used json encode to to grab data from the database using an SQL query (which I did successfully) but I now need to be able to do the opposite. If anyone could help I'd greatly appreciate it. It's my second day of work and I'm not doing so well. The following is my code:
$UserCoords_Query = "Select Accuracy, Longitude, Latitude, Timestamp
FROM UserDetails
WHERE UserId =" . $UserID;
$UserCoords_result = mysql_query($UserCoords_Query);
if (mysql_num_rows($UserCoords_result) == 0) {
echo "There are no users with an id of ". $UserID;
}
else {
$EmptyArray=array();
while ($row = mysql_fetch_array($UserCoords_result)) {
$Accuracy=$row['Accuracy'];
$Longitude= $row['Longitude'];
$Latitude=$row['Latitude'];
$Timestamp= $row['Timestamp'];
$Queue= array('Accuracy:' => $Accuracy, 'Latitude' => $Latitude, 'Longitude' => $Longitude, 'Timestamp' => $Timestamp);
array_unshift($EmptyArray,$Queue);
}
$ObjectResponse = array('Coords' => $EmptyArray);
echo json_encode($ObjectResponse);
$Json_Encoded= json_encode($ObjectResponse);
$Json_Decoded= json_decode($Json_Encoded, true);
$Update_Query= "INSERT INTO UserDetails (UserId, Accuracy, Latitude, Longitude, Timestamp)
VALUES ('".$UserID."','".$Json_Decoded[0] ['Accuracy']."','".$Json_Decoded[0]['Latitude']."',
'".$Json_Decoded[0]['Longitude']."','".$Json_Decoded[0]['Timestamp']."')";
mysql_query($Update_Query) or die(mysql_error());

I agree with chandresh_cool. you should use 'true' option to decode the json encoded string as array, otherwise it will return an object.
moreover, file_get_contents() expects a filename (with full or relative path). When you try to give a json_encoded string, it thinks that its the file name and it will try to open it as a file, which, obviously does not exist, and thus throws an error. Try to give an existing filename and see that solves the problem.
P.s. I know this should be a comment, but due to insufficient points, I cannot comment

You need to set second parameter of json_encode as true to return array
$Json_Decoded = json_decode($Json_Encoded, true);

Related

url did not send correct data ,what can i do for send the correct values

i want to send data with url
and my code php is:
<?php
$db_host="127.0.0.1"; $db_uid="root"; $db_pass="";
$db_name="highway_db"; $db_con =
mysqli_connect($db_host,$db_uid,$db_pass,$db_name);
$longitude =(isset( $_GET['lon`enter code here`gitude']));
$latitude = (isset($_GET['latitude']));
$timestamp = (isset($_GET['timestamp']));
$result = mysqli_query($db_con,"INSERT INTO accident (longitude, latitude, timestamp)
VALUES ($longitude, $latitude, $timestamp)");
if($result == true)
echo '{"query_result":"SUCCESS"}';
else
echo '{"query_result":"FAILURE"}';
mysqli_close($db_con);
?>
and my table is accident have id,longitude,latitude and timestamp
id is AUTO_INCREMENT.
but thme problem when i use this url :
http://127.0.0.1/addAccidents.php?longitude=3.54&latitude=3.09&timestamp=2016-04-25 11:11:00
i find that is add to my table accident
longitude=1
latitude =1,
timestamp =0000-00-00 00:00:00.
and this my problem with url please help me
try this :
$result = mysqli_query($db_con,"INSERT INTO accident (longitude, latitude, timestamp) VALUES ('".$longitude."', '".$latitude."', '".$timestamp."')");
Echo the sql query and try to run query directly in your phpmyadmin and also check your database table column type.
try changing the setting of hte variables around - you should anyway because even if the GET value is not present - this code will still try to insert values into the db, such as :
if(isset( $_GET['longitude'])){$longitude =$_GET['longitude']};
and then write code that only allows the writing to the db if the three values are set.
isset() is a function which checks if a given variable has contents or not. If it has it returns 1 and if not it return 0.
In all 3 below statements, you are just checking the variables, you have not assigned values to your variables!
Try to use this code here, it should work if GET REQUEST with those specified parameters is sent!
<?php
$db_host="127.0.0.1";
$db_uid="root";
$db_pass="";
$db_name="highway_db";
$db_con = mysqli_connect($db_host,$db_uid,$db_pass,$db_name);
$longitude = isset($_GET['longitude'])?$_GET['longitude']:"";
$latitude = isset($_GET['latitude'])?$_GET['latitude']:"";
$timestamp = isset($_GET['timestamp'])?$_GET['timestamp']:"";
$query = "INSERT INTO accident (longitude,latitude,timestamp) VALUES ($longitude,$latitude,$timestamp)";
if(mysqli_query($db_con,$query)){
echo '{"query_result":"SUCCESS"}';
}
else{
echo '{"query_result":"FAILURE"}';
echo "ERROR= ". mysql_error();
}
mysqli_close($db_con);
?>
Let me know how it goes....

PHP function issues with array

I have a postgres table with four columns labelled dstart which is date data type,
dend which is also a date data type, dcontract which is a date data type and id which is a integer. I am trying to run a php code to get the data using an array and use it in the body of my application. But when I test the array and try to echo some values... My browser just displays the word array... Is there anyway I can be able to retrieve the data or fix this code? Please see code below
<?php
function getLiveDate($campid)
{
global $conn,$agencies;
$return=array(
'livedate'=>'',
'campid'=>'',
'enddate'=>'',
'dateContract'=>'',
);
$sql = "SELECT id, dcontract, dstart, dend
FROM campaigns
WHERE id = '".$campid."' ORDER BY dstart DESC LIMIT 1";
$r = pg_query($conn,$sql);
if ($r)
{
$d = pg_fetch_array($r);
if (!empty($d))
{
$return['livedate'] = $d['dstart'];
$return['campid'] = $d['id'];
$return['enddate'] = $d['dend'];
$return['dateContract'] = $d['dcontract'];
}
}
#pg_free_result($r);
return $return;
}
I am pretty sure, your array $d is "multi-dimensional" and pg_fetch_array() returns an array of arrays, because the result of SQL queries in general may contain multiple rows. You limited it to one row, but you certainly get the correct values by assinging $return['livedata'] = $d[0]['dstart']; or $return['livedata'] = $d['dstart'][0]; and so on (I am not familiar with that particularly function for I usually use MySQL instead of Postgre).
Besides, try echoing your data by means of print_r() instead of echo.
The $return variable is an array, if you want shows the content, you must use print_r or var_dump not echo.

How to store multiple parameters passed as POST in database

I have passed JSON encoded parameters by POST which we have captured and decoded in another PHP file. I have used the following code to do that.
$entityBody = file_get_contents('php://input');
$entityBody = json_decode($entityBody, true);
I have passed the JSON encoded parameters as follows:
{
"id": "5",
"name": "abcd",
"imei": "1234"
}
Actually the number of parameters I am passing by POST may be 15 to 20 which I am going to insert in a table i.e. each of them is a field in the table in mysql database. I am new to JSON and PHP. What method I know is that get value of each parameter after checking whether it is set like following:
if(isset($entityBody['id']))
...
elseif(isset(...))
...
It is clear there will be many if and else when there are many parameters. So is there any way so that I can store the parameters in table in more efficient way. If anyone helps me in doing that I will be really grateful.
use json_decode function to parse the json to an array or object.
$a = json_decode($entityBody);
$a->id;
refer http://php.net/manual/en/function.json-decode.php
If you're using prepared statements you could do something like this. Please note that you should consider how you implement something like this, and change it to suit your needs.
$json = '{"id": "5","name": "abcd","imei": "1234"}';
$array = json_decode($json, true);
if (!count($array) > 0) {
throw new Exception('No params set.');
}
$allowedKeys = array('id','name','imei'); // could be hard coded, or something like: SELECT * FROM yourdb.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = yourtable
$queryParams = array();
foreach ($array as $key => $value) {
if (in_array($key, $allowedKeys)) {
$queryParams['keys'][] = $key;
$queryParams['values'][] = $value;
}
}
print_r($queryParams);
$query = 'INSERT INTO yourtable (' . implode(', ', $queryParams['keys']) . ') VALUES (?' . str_repeat(',?', count($queryParams['values'])-1) . ')';
print_r($query); // INSERT INTO yourtable (id, name, imei) VALUES (?,?,?)
Then you can just execute it with the $queryParams['values'] as the values :)
There's however no need to insert "id" if you're using auto increment, it will possibly just end up in some strange errors.

INSERT INTO using PDO not inserting data

I am trying to get the data to insert into the specified database but it just wont. Ive looked at the manual tried examples and all of that but I cant get the data to pass through to the database I can however echo/print_r/var_dump it so I know I have data. Here is my code:
public function insertJson($url, $subId)
{
$json_file = file_get_contents(KHAN_BASE.$url.'/videos');
if(isset($json_file))
{
$json_decoded = json_decode($json_file, true);
}else{
$this->error = 'A valid JSON file was not specified';
}
// var_dump($json_decoded); <--- This return all of the data needed from the json pull so i know I have data
//m3u8, mp4, png,
//". $row['m3u8'] .",". $row['mp4'] .",". $row['png'] .",
foreach($json_decoded as $row)
{
//echo $row['backup_timestamp'].'<br/>'; <--- This outputs the correct information so I know I can access it that way
$sql = "INSERT INTO tbl_khan_videos (sub_subject_id, backup_timestamp, date_added, description,
duration, extra_properties, has_questions, ka_url, keywords, kind, position, readable_id, relative_url, title, url, views,
youtube_id) VALUES (:subid, :backup_timestamp, :date_added, :description, :duration, :extra_properties, :has_questions, :ka_url, :keywords, :kind, :position,
:readable_id, :relative_url, :title, :url, :views, :youtube_id)";
$stmt = $this->db->prepare($sql);
$stmt->bindValue(":subid", $subId);
$stmt->bindValue(":backup_timestamp", $row['backup_timestamp']);
$stmt->bindValue(":date_added", $row['date_added']);
$stmt->bindValue(":description", $row['description']);
$stmt->bindValue(":duration", $row['duration']);
$stmt->bindValue(":extra_properties", $row['extra_properties']);
$stmt->bindValue(":has_questions", $row['has_questions']);
$stmt->bindValue(":ka_url", $row['ka_url']);
$stmt->bindValue(":keywords", $row['keywords']);
$stmt->bindValue(":kind", $row['kind']);
$stmt->bindValue(":position", $row['position']);
$stmt->bindValue(":readable_id", $row['readable_id']);
$stmt->bindValue(":relative_url", $row['relative_url']);
$stmt->bindValue(":title", $row['title']);
$stmt->bindValue(":url", $row['url']);
$stmt->bindValue(":views", $row['views']);
$stmt->bindValue(":youtube_id", $row['youtube_id']);
$stmt->execute();
}
}
Im not sure what I am doing wrong. I have tried binding it as an array (ex: $array = array(':subId' => $subId); $stmt->execute($array);) and still get no data through to the database. I know my config for the $this->db is good because I can pull other forms of already populated data with it. Any help would be very much appreciated.
I figured out my problem through some of the advice on here. What had been happening is I was trying to bind null values so the bindValue would cause the execute to go through without producing an error. Simple fix was doing this through foreach loops with a couple if statements which allowed me to set a value to the fields that were null. This solved the error. Again thank you to those who attempted to set in the correct path to finding the solution.

Problems using MERGE INTO statements in php for a MySQL database

I'm trying to use a MERGE INTO statement in my php file to update or insert into a MySQL database for a multiplayer game.
Here's a full description of what I'm trying to accomplish:
The php file is called with the following line from a javascript file:
xmlhttp.open('GET', "phpsqlajax_genxml.php?" + "lat=" + lla[0] + "&heading=" + truckHeading + "&lng=" + lla[1] + "&velocity0=" + vel0 + "&velocity1=" + vel1 + "&velocity2=" + vel2 + "&id=" + playerNumber, true);
This will be sending the php file information to update the database with. Either this will be a new player and the first time this information has been sent, meaning that a new row in the database will be created, or it will be a current player who just needs to have their information updated.
If it is a new player the "id" that is sent will be one that doesn't yet exist in the database.
For some reason the database isn't being updated, nor are new rows being added. I'm thinking it's a syntax error because I don't have much experience using MERGE statements. Could someone with experience with this please let me know what I might be doing wrong?
Here is the code before the MERGE INTO statement so you can understand which variables are which:
$id = $_GET['id'];
$lat = $_GET['lat'];
$lng = $_GET['lng'];
$heading = $_GET['heading'];
$velocity0 = $_GET['velocity0'];
$velocity1 = $_GET['velocity1'];
$velocity2 = $_GET['velocity2'];
id is the column heading, $id is the id being passed in
Here is my current MERGE INTO statement in my php file:
MERGE INTO markers USING id ON (id = $id)
WHEN MATCHED THEN
UPDATE SET lat = $lat, lng = $lng, heading = $heading, velocityX = $velocity0, velocityY = $velocity1, velocityZ = $velocity2
WHEN NOT MATCHED THEN
INSERT (id, name, address, lat, lng, type, heading, velocityX, velocityY, velocityZ) VALUES ($id, 'bob', 'Poop Lane', $lat, $lng, 'Poop', $heading, $velocity0, $velocity1, $velocity2)
PHP's database libraries invariably have their various function calls return FALSE if anything failed during the call. Assuming you're on mysql_/mysqli_, then you shoudl be doing something like this:
$sql = "MERGE INTO ....";
$result = mysql_query($sql);
if ($result === FALSE) {
die(mysql_error());
}
It is poor practice to NOT check the return values from database calls. Even if the query string is 100% syntactically valid, there's far too many ways for a query to fail. Assuming everything works is the easiest way to get yourself into a very bad situation. As well, when things do fail, the lack of error handling will simply hide the actual reason for the error and then you end up on SO getting answers like this.
Oh, and before I forget... MySQL doesn't support "MERGE INTO...", so your whole query is a syntax error. Look into using "REPLACE INTO..." or "INSERT ... ON DUPLICATE KEY UPDATE ..." instead.

Categories