PHP - Create a json file from mysql - php

I know my code below isn't the best way of doing what i'm trying to do here, but I need a way to remove just the double quotes from the key values only using PHP. I need to keep the double quotes inside the "src attribute" though!
Here is my PHP code:
$host = "localhost"; //Your database host server
$db = "root"; //Your database name
$user = "root"; //Your database user
$pass = "1234"; //Your password
$connection = mysql_connect($host, $user, $pass);
//Check to see if we can connect to the server
if(!$connection)
{
die("Database server connection failed.");
}
else
{
//Attempt to select the database
$dbconnect = mysql_select_db($db, $connection);
//Check to see if we could select the database
if(!$dbconnect)
{
die("Unable to connect to the specified database!");
}
else
{
$query = "SELECT * FROM playlist_builder";
$resultset = mysql_query($query, $connection);
$records = array();
$response = array(); //extra
//Loop through all our records and add them to our array
while($r = mysql_fetch_assoc($resultset))
{
$records[] = $r;
}
//Output the data as JSON
$json = json_encode($records, JSON_PRETTY_PRINT);
$json = str_replace('\\', '', $json);
$json = preg_replace('/"([a-zA-Z]+[a-zA-Z0-9_]*)":/','$1:',$json);
// $json = str_replace('"', "'", $json);
//NOTE: FOLDERS 'url' and 'file' SHOULD BE WRITABLE WITH PERMISSIONS - 777
//IN CASE 'url' FOLDER PLACED IN SERVER'S ROOT
//IF YOU'RE USING SOME FTP BROWSER CHANGE PERMISSIONS FOR 'url'
//FOLDER AND APPLY IT TO ALL ENCLOSED ITEMS
$data = 'var data = [{ tags: ';
$end = '}];';
$script = "// Call Slider function
$(window).load(function () {
$('#slideshow-slider').jSonSlider({
'loadallslides': false,
'auto': [true, '14000'],
'nextprev': false,
'circular': true,
'pagi': false,
'data': data
});
});";
file_put_contents('records.js', $data);
file_put_contents('records.js', $json, FILE_APPEND);
file_put_contents('records.js', $end, FILE_APPEND);
file_put_contents('records.js', $script, FILE_APPEND);
}
}
Here is my Output of my js file:
var data = [{ tags: [
{
id: "1",
volume: "volume1",
name: "a",
content: "<img src="../../../image1.jpg">",
css_animate: "fadeIn"
},
{
id: "2",
volume: "volume1",
name: "a",
content: "<img src="../../../image2.jpg">",
css_animate: "fadeIn"
},
{
id: "3",
volume: "volume1",
name: "a",
content: "<img src="../../../image3.jpg">",
css_animate: "fadeIn"
}
]}];
// Call Slider function
$(window).load(function () {
$('#slideshow-slider').jSonSlider({
'loadallslides': false,
'auto': [true, '14000'],
'nextprev': false,
'circular': true,
'pagi': false,
'data': data
});
});
Any help is really appreciated! :)

My recommendation would be to use Collection that comes with illuminate/support package. You can pass your associative array to the Collection's constructor, then map through it and return as json.
Example would be:
use Illuminate\Support\Collection;
$collection = new Collection($records);
$json = $collection->map(function(array $record) {
return [
id => $record['id'],
volume: $record['volume'],
name: $record['name'],
content: '<img src="../../../'.$record['image'].'">',
css_animate: "fadeIn"
];
})->toJson();

I understand you are converting a PHP array to JSON, and then converting that JSON to Javascript object. Why don't we let Javascript itself convert the JSON to a JS object? Like this:
// JSONify $records. We need the slashes for the
// string to work correctly in Javascript.
$jsonRecords = addslashes(json_encode($records));
// This is the JS file contents (using PHP's heredoc string syntax).
// The $jsonRecords string is inserted as part of that JSON string.
$fileContents = <<<DOC
var data = JSON.parse("[{\"tags\": $jsonRecords }]");
// Call Slider function
$(window).load(function () {
$('#slideshow-slider').jSonSlider({
'loadallslides': false,
'auto': [true, '14000'],
'nextprev': false,
'circular': true,
'pagi': false,
'data': data
});
});
DOC;
// Create a file and write to it once.
file_put_contents('records.js', $fileContents);
We convert $records to JSON and insert it inside a JSON string (var data), which is parsed by Javascript's JSON.parse function. Now we don't have any troubles with quotes.

Related

Getting a JSON from a Ajax request and creating a polygon layer in Leaflet

I need some help with a script, i have an ajax request that returns a GeoJSON
Images:
JSON Format
"id_map": "2",
"description": "AC1",
"geojson": {a GeoJSON coordinate }
"file": "AC1.geojson"
I can use AJAX JSON Leaflet (plugin( to create a polygon layer using the JSON value file ex (ac1.geojson) and point it up to a folder with the GeoJSON files (ex. geojson), but i have the same GeoJSON saved as a text variable in a database and i want to use it besides the file because of the risk of losing the files, so i recover it (i use GeoJson.io to validate the geojson and copy paste it in a column in my database) using a database connection and then i JSON encode it, but i am unable to use it. And I'm having problems with the format that comes out from the PHP.
$(document).ready(function() {
document.body.onload = function() {
var tiles = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 20,
minZoom: 13,
attribution: 'x'
}),
latlng = L.latLng(-32.0312422, -52.0917713);
var mymap = L.map('mapid', {
center: latlng,
zoom: 18,
layers: [tiles]
});
L.marker([-32.0312422, -52.0917713]).addTo(mymap);
function popUp(f, l) {
var out = [];
if (f.properties) {
for (key in f.properties) {
out.push(key + ": " + f.properties[key]);
}
l.bindPopup(out.join("<br />"));
}
}
var j_url = "somephp.php";
var results = $.ajax({
url: j_url,
dataType: 'json',
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
function AjaxSucceeded(results) {
console.log("Data successfully loaded.");
alert("OK");
$.each(results, function(index, value) {
var geojsonTESTE = {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"properties": {},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[-52.101760, -32.031909],
[-52.102275, -32.028598],
[-52.100794, -32.028435],
[-52.099206, -32.029053],
[-52.097554, -32.029362],
[-52.097511, -32.029672],
[-52.096760, -32.029672],
[-52.096696, -32.029544],
[-52.095795, -32.029617],
[-52.094142, -32.029835],
[-52.088585, -32.030672],
[-52.088392, -32.030763],
[-52.088027, -32.034656],
[-52.101631, -32.032145],
[-52.101760, -32.031909]
]
]
}
}]
};
var geoObject = JSON.parse(value.geojson);
L.geoJSON(geojsonTESTE).addTo(mymap);
L.geoJSON(features).addTo(mymap);
//With Leaflet Ajax e Files
//j_url = "json/"+value.file;
//var jsonTest = new L.GeoJSON.AJAX([j_url]{onEachFeature:popUp}).addTo(mymap);
});
}
function AjaxFailed(results) {
console.log("ERROR AJAX");
alert("ERRO");
}
$.when(results).done(function() {
});
};
});
<?php
header('Content-Type: application/json');
$connStr = { database connection string }
$conn = pg_connect($connStr);
$result = pg_query($conn, "select * from mapas");
$qtd = pg_num_rows($result);
$res = "[";
if($qtd > 0){
$i = 0;
foreach(pg_fetch_all($result) as $row)
{
$x = $row['geojson'];
$patterns = array ('/[^A-Za-z0-9\-\,\"\:\{\}\[\]]/');
$replace = array ('');
$desc = preg_replace($patterns, $replace,$x);
$desc = str_replace('\"', '"', $desc, $count);
$data['id_map'] = $row['id_map'];
$data['description'] = $row['description'];
$data['geojson'] = $desc;
$data['file'] = $row['file'];
$map = json_readable_encode($data,null,true);
$res .= $map;
if($i < $qtd -1 ){
$res .= ",";
}
$i++;
}
}
$res .= "]";
echo trim($res);
pg_free_result($result);
pg_close();
?>

Full Calendar - Error Loading JSON events

I am having trouble with Full Calendar (FC) to read the JSON object I have returned from my database to display events on the calendar. Where could I be overlooking?
My jQuery for FC is here:
$('#calendar').fullCalendar({
defaultView: 'month',
titleFormat: "MMMM YYYY",
header: {
left: 'month,agendaWeek,agendaDay',
center: 'title',
right: 'prevYear,prev,next,nextYear'
},
events: {
url: "../ajax/tutor/json_events.php",
type: "POST",
color: "yellow",
textColor: "black",
error: function() {
alert('There was an error while fetching events.');
}
}
});
The json_events.php is here:
$returnArray = array();
$userID = filter_input(INPUT_GET, "id");
$connect = db();
$stmt = $connect->prepare("SELECT * FROM Lessons WHERE TutorID = 1");
if($stmt->execute()){
$results = $stmt->get_result();
while($row = $results->fetch_assoc()){
$rowArray['start'] = $row['Start'];
$rowArray['end'] = $row['End'];
$rowArray['title'] = $row['CourseTaught'];
array_push($returnArray, $rowArray);
}
$json = json_encode($returnArray);
}
echo print_r($json);
$stmt->close();
The JSON object displays perfectly, however the alert is being thrown from jquery events for some reason, I am just overlooking the error somehow. A fresh pair of eyes would be useful.
Add square brackets around $json, something like echo('['.$json.']');
You are returning a human-readable dump of the variable in PHP by using print_r(). Your JavaScript is expecting the true JSON object without formatting.
Simply echo $json; instead of echo print_r($json); and you will get your json object without the surrounding <pre> tags.

PHP with DataTables gives an Invalid JSON response due to quotes

I encountered a problem fetching my data from my database and display it via DataTables. I found out that most of my data has single and double quotes and other special characters. I tried every escaping functions in PHP but it didn't work. addslashes only retrieves 59 data out of 40,000 data. So far, i have this code:
PHP:
$query = mysqli_query($new_conn, "SELECT * FROM bill_of_materials");
$table = '';
while($row = mysqli_fetch_array($query)) {
$table.= '{
"allotment_code":"'.$row['allotment_code'].'",
"activity":"'.$row['activity'].'",
"category_name":"'.addslashes($row['category_name']).'",
"description":"'.addslashes($row['description']).'"
},';
}
$table = substr($table,0, strlen($table) - 1);
echo '{"data":['.$table.']}';
**jQuery data tables:**
$(function() {
$('#dataTables-example').DataTable( {
"bLengthChange": false,
"pageLength": 50,
"bDeferRender": true,
"bProcessing": true,
"sPaginationType": "full_numbers",
"ajax": base_url('ajax/ajaxGetBOM.php'),
"columns":[
{mData: "allotment_code"},
{mData: "activity"},
{mData: "category_name"},
{mData: "description"}
],
contentType: 'application/json',
dataType: 'json'
});
})
function base_url(path) {
var url = 'https://192.168.3.254/'+path;
return url;
}
The error is like this:
Use json_encode() function to properly encode your response using JSON format.
$query = mysqli_query($new_conn, "SELECT * FROM bill_of_materials");
$data = array();
while($row = mysqli_fetch_array($query)) {
$data[] = array(
"allotment_code" => $row["allotment_code"],
"activity" => $row["activity"],
"category_name" => $row["category_name"],
"description" => $row["description"]
);
}
header("Content-type: application/json");
echo json_encode(array("data" => $data));

PHP: how to populate html form fields with query results using ajax

I'm trying to populate a form with values after performing a simple search but when I run the script, I either get "undefined" or a blank response when I do alert(data);.
search.php
<?php
include_once 'config/config.php';
include_once 'config/connect.php';
$conn = dbconn();
if(isset($_POST['btn-search']))
{
$sub_id = mysqli_real_escape_string($conn, $_POST['user_id']);
$sql = "SELECT * FROM users WHERE user_id = '".$sub_id."'";
$res = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($res);
$found = array();
while ($row = mysqli_fetch_array($res))
{
$found[] = array(
'name' => $row['full_name'],
'init_date' => $row['init_date'],
'position' => $row['position'],
'email' => $row['email'],
);
echo json_encode($found);
}
}
mysqli_close($conn);
?>
script
<script>
/*
simple validation script
*/
$('document').ready(function()
{
$('#register-submit-btn').attr('disabled', 'disabled');
/* validation */
$("#register-form").validate({
rules:
{
user_id: {
required: true,
minlength: 5,
},
},
messages:
{
cedulaid:{
required: "The user ID is required",
minlength: "The user ID should be no less than 5 characeters long.",
},
},
submitHandler: submitForm
});
/* validation */
/* get data */
function submitForm()
{
var data = $("#details-form").serialize();
$.ajax({
type : 'POST',
url : 'search.php',
data : data,
beforeSend: function()
{
$("#detailsmsg").fadeOut();
$("#btn-search").html('<img src="include/btn-ajax-loader.gif" /> Looking...');
$('#btn-search').attr('disabled', 'disabled');
},
success : function(data)
{
alert(data);
$("#detailsmsg").fadeIn(1000, function(){
$("#detailsmsg").removeClass("alert-danger").addClass("alert-success");
$('#btn-search').removeAttr('disabled');
$("#btn-search").html('Search again?');
$('#register-submit-btn').removeAttr('disabled');
$("#detailsmsg").html("<span>Data Found</span>");
});
$("#name").val(data.name); // not sure how to do this part. this is probably very wrong but still not getting anything on the alert.
$("#init_date").val(data.init_date);
$("#position").val(data.position);
$("#email").val(data.email);
}
});
return false;
}
/* get data */
});
</script>
I have the alert(data) at the top of the success function because I want to see what I would get in return but it comes back blank. If I do alert(data[0]) I get "undefined" message.
the console POST returns this:
name=&init_date=&position=&email=
There are probably many mistakes in the script and I'm open to any feedback and help I can get. Let me know if any other details are needed.
Thanks in advance,
for getting single output, you only need a $row = mysqli_fetch_array($res); not loop..it will return single parameter output..
Search.php
<?php
include_once 'config/config.php';
include_once 'config/connect.php';
$conn = dbconn();
if(isset($_POST['btn-search']))
{
$sub_id = mysqli_real_escape_string($conn, $_POST['user_id']);
$sql = "SELECT * FROM users WHERE user_id = '".$sub_id."'";
$res = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($res);
$found = array();
$found[] = array(
'name' => $row['full_name'],
'init_date' => $row['init_date'],
'position' => $row['position'],
'email' => $row['email'],
);
echo json_encode($found);
}
mysqli_close($conn);
?>
try it once..may be it will help you.
By just quickly looking at the PHP code it returns nested arrays:
[
[
'name' => 'whatever',
'init_date' => 'date',
...
]
]
This happens because you first define $found = array(); and then append more arrays to it with $found[] = array(...).
The javascript part however tries to access just data.name which doesn't exist. Maybe data[0].name should exist assuming there's at least one record in the database.
Did you want to iterate data as an array instead?
But maybe the problem lies in the PHP part where you call mysqli_fetch_array() twice and therefore override $row variable and skip the first result found:
$row = mysqli_fetch_array($res);
$found = array();
while ($row = mysqli_fetch_array($res))
{
...
Last thing I see is that you probably want to call echo json_encode($found); after the while loop when you've collected all search results. By the way, this also produces invalid JSON.

Save Ajax POST data to file using PHP

I am posting some data to a PHP file using ajax and saving it to a MySQL database. This works fine, but I also want to save one of the data elements to a text file (which should be created) on the server but I can't get it to save to a file.
This is how my code looks:
jQuery (snippet)
var uid = "1";
var name = "bruno";
var number = "0889-123-123";
var location = "{"locationInfo":[{"title":"home","lat":-16.450902223672625,"lng":10.6103515625,"speed":""},{"title":"work","lat":-14.94621907436008,"lng":17.99560546875,"speed":""}]}"
$.ajax({
type: "POST",
url: "process.php",
data: {uid:uid, name:name, number:number, location:location},
dataType: 'json',
cache: false,
})
PHP - process.php
<?php
$inputvalues = $_POST;
$errors = false;
$result = false;
$mysqli = new mysqli('localhost', "root", "", "tp");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
foreach ($inputvalues as $key => $value) {
if(isset($value) && !empty($value)) {
$inputvalues[$key] = $mysqli->real_escape_string( $value );
} else {
$errors[$key] = 'The field '.$key.' is empty';
}
}
if( !$errors ) {
$mysqli->query("
INSERT INTO `table`(`uid`, `name`, `number`)
values ('".$inputvalues['uid']."', '".$inputvalues['name']."', '".$inputvalues['number']."');
");
file_put_contents('saved/file.txt', file_get_contents('".$inputvalues['location']."'));
}
mysqli_close($mysqli);
$returnResult ="success";
echo json_encode(['result' => $returnResult, 'errors' => $errors]);
exit;
?>
change this:
file_put_contents('saved/file.txt', file_get_contents('".$inputvalues['location']."'));
to this:
file_put_contents('saved/file.txt', $inputvalues['location']);
Also, in JS you need to remove the quotations from your location object.
It should be like this:
var location = {"locationInfo": [{"title": "home", "lat": -16.450902223672625, "lng": 10.6103515625, "speed": ""}, {"title": "work", "lat": -14.94621907436008, "lng": 17.99560546875, "speed": ""}]};
#CodeGodie $inputvalues['location'] doesn't seem to contain a file location.
Maybe like this?
file_put_contents('saved/file.txt', $inputvalues['location']);

Categories