Please, help with this. I generate a JSON string from database, like this
<?php
require_once "pdo.php";
$stmt = $pdo->query("SELECT * FROM locals WHERE article_id = {$_POST['idc']}");
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
echo(JSON_encode($row['article_image']));
And receiving in browser like this
$('#local').change(function(event){
locid = $(this).val();
$.post('mod/imgtour.php', {'idc':locid}, function(data){
window.console && console.log(data);
$.getJSON('mod/artic.php',function(data){
window.console && console.log(data);
$('#artimg').attr("src","data.first");
});
});
But in the console I realize that the data I recieve, which is the path to an image come in this way: "images\\locals\\article1.png" (the path stored in database is in this form "images\locals\article1.png" )
I need the file path comes in the right way, to replace it in the image tag...
Any suggestion?
Related
As the tittle says i'm coding a web app as part of a school project. My goal is for someone to upload a json file and save some data of it in a table on Mysql for further functionallity in the app.
My question is how exaclty can you pass a JSON file to PHP and then parse it from there as to store the wanted data to the DB. I tried sending it with the help of Jquery fileupload as the json files may be quite large and on the php side i used the function file_get_contents but i had no luck with it.
Here is my javascript code :
$(document).ready(function () {
$("#submitupload").click(function(){
var files = $("#files");
$("#uploadedfile").fileupload({
url: 'upload.php',
dataType: 'json',
autoUpload: false
}).on('fileuploadadd', function (e, data) {
var fileTypeAllowed = /.\.(json)$/i;
var fileName = data.originalFiles[0]['name'];
var fileSize = data.originalFiles[0]['size'];
console.log(data);
if (!fileTypeAllowed.test(fileName)){
$("#error").html('Only json files are allowed');
}else
data.submit();
}).on('fileuploaddone', function (e , data){
var msg = data.jqXHR.responseJSON.msg;
$("#error").html(msg);
}).on('fileuploadprogress', function (e,data){
var progress = parseInt(data.loaded / data.total * 100, 10 );
$("#progress").html("Completed: " + progress + "%");
})
})
})
And here is the PHP :
<?php
include_once ('connection.php');
if (isset($_FILES['uploadingfile'])){
$file = $_FILES['uploadingfile'];
$data = file_get_contents($file);
$array = json_decode($data, true );
foreach( $array as $row){
$sql = "INSERT INTO locations(timestamp) VALUES ('".$row["timestampMs"]."')";
mysqli_query($conn, $sql);
}
$msg = array("msg" => "times ok ");
exit(json_encode($msg));
}
Noticed the error in file_get_contents() that says that the $file variable is an array not a string so i tried to pass the $_FILES variable as an argument with no luck again.
Is this the correct way to way to do it and if yes what am i missing or should i use another approach?
Thanks for the long read and your time in advance ! Sorry if any of this sounds stupid but im new to PHP .
$_FILES['uploadingfile'] is an array with several pieces of information about the uploaded file. So you need to use:
$file = $_FILES['uploadingfile']['tmp_name'];
to get the filename where the data is stored.
See Handling File Uploads for full details.
I'm a 'newbie' on stackoverflow but it is a source that I keep coming to regularly for tips.
I've picked up some code from the simple.html file accompanying the jsPDF auto-table plug-in but as it doesn't appear to pick up data from a php generated table.
I am trying to get the data into a format that can be transformed into a nice pdf report - 'with all the trimmings' - ie; page-breaks, headers on each page, alternate row-colours etc.
I've tried to get the data into a form that can be used by the jsPDF autotable but I'm going wrong in that it is just going through the array and keeping the last record and printing that in pdf format. Code shown below.
<button onclick="generate()">Generate pdf</button>
<script src="/js//jspdf.debug.js"></script>
<script src="/js/jspdf.plugin.autotable.js"></script>
<?php
$link = mysqli_connect('localhost','user','password','database');
if(!$link)
{
echo 'Database Error: ' . mysqli_connect_error() ;
exit;
}
$results=array();
$sql_staff = "SELECT staff_id, staff_firstname, staff_lastname, staff_username, staff_chargerate, staff_lastlogin FROM tblstaff ORDER BY staff_lastname ASC, staff_firstname ASC ";
$result_staff = mysqli_query($link,$sql_staff);
while($row = mysqli_fetch_array($result_staff)){
$results[0] = $row['staff_id'];
$results[1] = $row['staff_firstname'] . " " . $row['staff_lastname'];
$results[2] = $row['staff_username'];
$results[3] = $row['staff_chargerate'];
$results[4] = $row['staff_lastlogin'];
echo json_encode($results);
$data = json_encode($results);
}
?>
<script>
function generate() {
var head = [["ID", "Staff Name", "Username", "Charge-rate", "Last Log-in"]];
var body = [
<?echo $data;?>
];
var doc = new jsPDF();
doc.autoTable({head: head, body: body});
doc.output("dataurlnewwindow");
}
</script>
I think that the problem lays around the line $data = json_encode($results); but I don't know enough about either PHP or Javascript to determine how the code needs to be altered to produce a full PDF report. Can anyone assist please?
Your issue is probably related to overwriting the values in the $results array which means you will get one item instead of an array of items. You probably want something like this:
$results = array();
while($row = mysqli_fetch_array($result_staff)){
$dataRow = array();
array_push($dataRow, $row['staff_id']);
array_push($dataRow, $row['staff_firstname'] . " " . $row['staff_lastname']);
// etc
array_push($results, $dataRow);
}
$data = json_encode($results);
I am trying to pass a javascript variable into an SQL WHERE query and I keep getting null in return.
On-click of a button, the buttonClick function is ran:
<script>
var var1;
function buttonClick(elem){
var1 = elem.src //this gets the url from the element
var path = var1.slice(48); //this cuts the url to img/art/9/1.jpg
ajax = theAjax(path);
ajax.done(processData);
ajax.fail(function(){alert("Failure");});
}
function theAjax(path){
return $.ajax({
url: 'info.php',
type: 'POST',
data: {path: path},
});
}
function processData(response_in){
var response = JSON.parse(response_in);
console.log(response);
}
</script>
Here is the code stored in the info.php file:
<?php
$path = $_POST['path'];
$result3 = mysqli_query("SELECT itemName from images WHERE imgPath='$path'");
$json = json_encode($result3);
echo $json
?>
As you can see, once I click the button, the buttonClick() function is ran and a variable stores the image path or src. That path variable is send to theAjax() function where it is passed to the info.php page. In the info.php page, the SQL WHERE query is ran and returned to the processData() function to be parsed and printed in the developer console. The value printed shows null.
Below is a picture of what I am trying to get from the database:
1.Check that path is correct or not? you can check inside jquery using console.log(path); or at PHP end by using print_r($_POST['path']);
2.Your Php code missed connection object as well as record fetching code.
<?php
if(isset($_POST['path'])){
$path = $_POST['path'];
$conn = mysqli_connect ('provide hostname here','provide username here','provide password here','provide dbname here') or die(mysqli_connect_error());
$result3 = mysqli_query($conn,"SELECT itemName from images WHERE imgPath='$path'");
$result = []; //create an array
while($row = mysqli_fetch_assoc($result3)) {
$result[] = $row; //assign records to array
}
$json = json_encode($result); //encode response
echo $json; //send response to ajax
}
?>
Note:- this PHP query code is wide-open for SQL INJECTION. So try to use prepared statements of mysqli_* Or PDO.
mysqli_query() required 1st parameter as connection object.
$result3 = mysqli_query($conn,"SELECT itemName from images WHERE imgPath='$path'"); // pass your connection object here
I think your issue is that you're trying to encode a database resource.
Try adjusting your PHP to look like the following:
<?php
$path = $_POST['path'];
$result3 = mysqli_query("SELECT itemName from images WHERE imgPath='$path'");
$return_data = [];
while($row = mysqli_fetch_assoc($result3)) {
$return_data[] = $row;
}
$json = json_encode($return_data);
echo $json
?>
I am a newbie to scripting and am trying to use the following php code (taken from another post that was already answered: PHP Script to convert .CSV files to .XML, to convert csv data to xml (I named this file csv2xml.php). I am trying to pull the outputted xml file that is created in the php script into javascript using the DownloadURL function so that I can parse the data further, but I'm not sure if I can use a php file in the downloadURL function in order to parse it. Can anyone point me in the right direction? I have to have this done by tomorrow so any help would be appreciated. PHP code is first, followed by the section of javascript I am referring to.
<?php
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', true);
ini_set('auto_detect_line_endings', true);
$inputFilename = 'input.csv';
$outputFilename = 'output.xml';
// Open csv to read
$inputFile = fopen($inputFilename, 'rt');
// Get the headers of the file
$headers = fgetcsv($inputFile);
// Create a new dom document with pretty formatting
$doc = new DomDocument();
$doc->formatOutput = true;
// Add a root node to the document
$root = $doc->createElement('rows');
$root = $doc->appendChild($root);
// Loop through each row creating a <row> node with the correct data
while (($row = fgetcsv($inputFile)) !== FALSE)
{
$container = $doc->createElement('row');
foreach ($headers as $i => $header)
{
$child = $doc->createElement($header);
$child = $container->appendChild($child);
$value = $doc->createTextNode($row[$i]);
$value = $child->appendChild($value);
}
$root->appendChild($container);
}
echo $doc->saveXML();
?>
downloadUrl("csv2xml.php", function(data) {
var xmlDoc = xmlParse(data);
var records = xmlDoc.getElementsByTagName("row");
...(parsing code)
I am using to Fullcalendar jquery with php for event management. I using ajax call for adding events. The call works fine for the first event entry after refresh. But for the following event entries duplicate events are created for each entry. Not sure what causing this.
This is the error:
This is the jquery call:
Jquery
$('#evesav').bind('click',function(){
$('#evesav').attr('disabled','disabled');
var title = $('#evename').val();
var edes = $('#evedes').val();
var everegion = $('#everegion').val();
var eveserv = $('#eveserv').val();
$.ajax({
url: 'add_events.php',
data: 'title='+ title+'&start='+ start +'&end='+ end +'&edes='+ edes +'&everegion='+ everegion +'&eveserv='+ eveserv,
type: "POST",
success: function(json) {
$('#myModal').modal('hide');
$('#alertcon').html(json);
$('#alert').modal('show');
$('#evename').val("");
$('#evedes').val("");
$('#evesav').removeAttr('disabled');
$('#calendar').fullCalendar( 'refetchEvents' );
}
});
$('#calendar').fullCalendar( 'rerenderEvents' );
});
This is the PHP Code:
PHP
<?php
if(($_POST['title'] && $_POST['start'] && $_POST['end'] && $_POST['edes'] && $_POST['everegion'] && $_POST['eveserv'])!= NULL)
{
// Values received via ajax
$title = $_POST['title'];
$start = $_POST['start'];
$end = $_POST['end'];
$edes = $_POST['edes'];
$region = $_POST['everegion'];
$server = $_POST['eveserv'];
//echo $title."".$start."".$end."".$edes."".$region."".$server;
// connection to the database
include('includes/db.php');
// insert the records
$sql = "INSERT INTO evenement (title, start, end, edes, region, server) VALUES (:title, :start, :end, :edes, :region, :server)";
$q = $bdd->prepare($sql);
$q->execute(array(':title'=>$title, ':start'=>$start, ':end'=>$end, ':edes'=>$edes, ':region'=>$region, ':server'=>$server));
if($q->execute(array(':title'=>$title, ':start'=>$start, ':end'=>$end, ':edes'=>$edes, ':region'=>$region, ':server'=>$server))){
var_dump($q->execute(array(':title'=>$title, ':start'=>$start, ':end'=>$end, ':edes'=>$edes, ':region'=>$region, ':server'=>$server)));
}
$eveid=$bdd->lastInsertId();
// Get array of all source files
$files = scandir("uploads/");
// Identify directories
$source = "uploads/";
$destination = "evedata/".$eveid."/";
mkdir("evedata/".$eveid);
// Cycle through all source files
foreach ($files as $file) {
if (in_array($file, array(".",".."))) continue;
// If we copied this successfully, mark it for deletion
if (copy($source.$file, $destination.$file)) {
$delete[] = $source.$file;
}
}
// Delete all successfully-copied files
foreach ($delete as $file) {
unlink($file);
}
echo "Added Successfully";
}
else {
echo "Please Fill the data";
}
?>
Some one please help me with this.
I'd give each event addition form a control, for instance a dynamic GUID, which then can be used to save to DB. This way you have a GUID to work with in dealing with CalDAV protocol, if you ever choose to do as such with your calendar, as well as have a way to make certain nothing is duplicated by chance in your database.
Now, do keep in mind this is simply a patch, not a fix. Therefore, you'll do yourself a lot of good to find a way to stop the multiple attempts to add an event to your DB. Regardless of your success in finding your bug, using a control mechanism or unique identifier is a good idea.