I have a code below
<?php
/* Error display */
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('memory_limit', '512M');
/* Requires */
require 'conn.php';
/* Parameters (DIM) */
$param_customer = $_POST['param_customer'];
$param_user = $_POST['param_user'];
/* Others */
$param_email = $_POST['email'];
$file_dump_area = "../general_sync/";
/* Array */
$jsonData = array();
$arr_result = array();
/******************************** Download customer *********************************/
$cur_filename = $file_dump_area . removeCharEmail($param_email) . "_" . $param_customer . ".csv";
$cur_file = fopen($cur_filename, "w");
$cur_sql = "CALL android_getCustomer('" .$param_email. "')";
$cur_result = mysqli_query($con,$cur_sql);
if ($cur_file && $cur_result) {
while ($row = $cur_result->fetch_array(MYSQLI_NUM)) {
fputcsv($cur_file, array_values($row));
}
array_push($arr_result, array('done_process' => "done_cus"));
}
fclose($cur_file);
/******************************** Download user *********************************/
$cur_filename = $file_dump_area . removeCharEmail($param_email) . "_" . $param_customer . "1.csv";
$cur_file = fopen($cur_filename, "w");
$cur_sql = "CALL android_getCustomer('" .$param_email. "')";
$cur_result = mysqli_query($con,$cur_sql);
if ($cur_file && $cur_result) {
while ($row = $cur_result->fetch_array(MYSQLI_NUM)) {
fputcsv($cur_file, array_values($row));
}
array_push($arr_result, array('done_process' => "done_user"));
}
fclose($cur_file);
$jsonData = array("received"=>$arr_result);
echo json_encode($jsonData,JSON_PRETTY_PRINT);
function removeCharEmail($val) {
$new_val1 = str_replace(".", "", $val);
$new_val2 = str_replace("#", "", $new_val1);
return $new_val2;
}
?>
The target output of that code is to create 2 csv which is it does but the problem is the 2nd csv has no data although the query shows some it does not write. I tried to copy the 1st line of codes. it does create the file but it didnt write
Whats the problem?
Updated with help of Mr. Barmar
i got this error Commands out of sync; you can't run this command now
The stored procedure is apparently returning two result sets. You need to fetch the next result set before you can start another query. Add:
$cur_result->close();
$con->next_result();
After each loop that fetches the results. See https://stackoverflow.com/a/14561639/1491895 for more details.
Related
Currently, I created a system that uses daypilot calendar. For example, when I clicked a date, it will show the list of activities on that selected date.
Below code is successful display the list:
<?php
require_once '../../../config/configPDO.php';
$Fac_ID = strtolower($_GET['Fac_ID']);
$Room_Desc = strtolower($_GET['Room_Desc']);
$stmt = $conn->prepare("SELECT * FROM booking LEFT JOIN room ON booking.Room_ID = room.Room_ID
WHERE room.Fac_ID = '$Fac_ID' AND room.Room_Desc = '$Room_Desc' AND Book_Status <> 'Reject'");
$stmt->execute();
$result = $stmt->fetchAll();
class Event {}
$events = array();
foreach($result as $row) {
$e = new Event();
$e->id = $row['Book_No'];
$e->text = "Meeting Name: ". $row['Meeting_Description']. " || " ."Requested by: ".$row['Requested_by']. " || " ."Location: ".$row['Fac_ID']. ", " .$row['Room_Desc'];
$e->start = $row['StartTime'];
$e->end = $row['EndTime'];
$events[] = $e;
}
header('Content-Type: application/json');
echo json_encode($events);
?>
But, when I change the code (Because want to retrieve json data), the data doesn't display at calendar.
Below is the code:
<?php
require_once '../../../config/configPDO.php';
$Fac_ID = strtolower($_GET['Fac_ID']);
$Room_Desc = strtolower($_GET['Room_Desc']);
//retrieve json
$url = "http://172.20.0.45/TGWebService/TGWebService.asmx/displayPABooking?Fac_ID=$Fac_ID&Room_Desc=$Room_Desc&Room_ID=&Book_No=&Book_Date_From=&Book_Date_To=";
$data = file_get_contents($url); //line 10
$json = json_decode($data);
$result = $json->bookingList; //line 12
class Event {}
$events = array(); //
foreach($result as $row) { //line 17
$e = new Event();
$e->id = $row->bookNo;
$e->text = "Meeting Name: ".$row->desc. " || " ."Requested by: ".$row->requestedBy." || " ."Location: ".$row->facID.", " .$row->roomName;
$e->start = $row->startTime;
$e->end = $row->endTime;
$events[] = $e;
}
header('Content-Type: application/json');
echo json_encode($events);
?>
And, This is the error that I found at console:
PHP Warning: file_get_contents(http://172.20.0.45/TGWebService/TGWebService.asmx/displayPABooking?Fac_ID=TGT&Room_Desc=LEVEL 1 &Room_ID=&Book_No=&Book_Date_From=&Book_Date_To=): failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request
in C:\inetpub\wwwroot\ebooking\pages\manual_booking\backend\backend_events.php on line 10
PHP Notice: Trying to get property 'bookingList' of non-object in C:\inetpub\wwwroot\ebooking\pages\manual_booking\backend\backend_events.php on line 12
PHP Warning: Invalid argument supplied for foreach() in C:\inetpub\wwwroot\ebooking\pages\manual_booking\backend\backend_events.php on line 17
Can I know where I need to change? Thanks
This is probably because of the space in "Level 1". Try urlencoding your $_GET parameters:
$url = "http://172.20.0.45/TGWebService/TGWebService.asmx/displayPABooking?Fac_ID=" . urlencode($Fac_ID) . "&Room_Desc=" . urlencode($Room_Desc) . "&Room_ID=&Book_No=&Book_Date_From=&Book_Date_To=";
If you want to make the variable substitution more explicit, you could use strtr:
$template = "http://172.20.0.45/TGWebService/TGWebService.asmx/displayPABooking?Fac_ID={Fac_ID}&Room_Desc={Room_Desc}&Room_ID=&Book_No=&Book_Date_From=&Book_Date_To=";
$url = strtr($template, array(
'{Fac_ID}' => $Fac_ID,
'{Room_Desc}' => $Room_Desc
));
I am working on a JSON file in which I want to increment instead of overwriting the data. However I cannot seem to do this (since it keeps on overwriting instead of adding data with an incremented ID).
The code underneath is: database_json.php (as u can see I include it in saveJson.php)
$databaseFile = file_get_contents('json_files/database.json');
$databaseJson = json_decode($databaseFile, true);
$database = $databaseJson['data'];
the below is the code of the file saveJson.php contains the following code:
// below starts a new page, the page that submits the form called saveJson.php
include_once('database_json.php');
$data = $_POST;
//Setup an empty array.
$errors = array();
if (isset($data)) {
$newExerciseData = $data;
$exerciseArray = $data['main_object'];
$databaseFile = 'json_files/database.json';
$textContent = file_get_contents($databaseFile);
$database = json_decode($textContent, true);
if ($data['id'] === 'new') {
if (count($database['data']) == 0) {
$ID = 0;
}
else {
$maxID = max($database['data']);
$ID = ++$maxID["id"];
}
$newJsonFile = 'jsonData_' . $ID . '.json';
$newJsonFilePath = 'json_files/' . $newJsonFile;
//Create new database exercise_txt
$newArrayData = array(
'id' => $ID,
// a lot of variables that aren't related to the problem
);
$database['data'][] = $newArrayData;
file_put_contents($databaseFile, json_encode($database, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
file_put_contents($newJsonFilePath, json_encode($newExerciseData, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
}
else {
$index = array_search((int) $_POST['id'], array_column($database['data'], 'id'));
$correctJsonFile = 'json_files/jsonData_' . $_POST['id'] . '.json';
$newJsonFile = 'jsonData_' . $_POST['id'] . '.json';
$newJsonFilePath = 'json_files/' . $newJsonFile;
//Create new database exercise_txt
$newArrayData2 = array(
'id' => (int) $_POST['id'],
// more not related to problem variables
);
$database['data'][$index] = $newArrayData2;
file_put_contents($databaseFile, json_encode($database, JSON_UNESCAPED_UNICODE));
file_put_contents($newJsonFilePath, json_encode($newExerciseData, JSON_UNESCAPED_UNICODE));
}
echo json_encode($newExerciseData, JSON_UNESCAPED_UNICODE);
}
so, what I wish for: To increment the IDs and NOT to overwrite the data.
I already did some research and didn't find any useful information besides this --> Auto increment id JSON, but to me it looks like I have the same principle applied.
This question already has answers here:
How to store values from foreach loop into an array?
(9 answers)
Closed 1 year ago.
Basically I want to make a download button for my project that will produce different csv files (one csv file per table) in memory and zip before download. It works fine but the problem is that I am only getting one row (the last result) on each mysql_fetch_array where it is supposed to return rows depending on how many are stored in the database. This code is depreciated, sorry for that.
Here is my code:
<?php
require("../includes/connection.php");
require("../includes/myLib.php");
//get the ID that is passed
$ID = $_REQUEST['q'];
$ID = xdec($ID);
//All queries to fetch data
$query = mysql_query("SELECT * FROM `ge2`.`projects` WHERE `projects`.`proj_id`='$ID'");
$query2 = mysql_query("SELECT * FROM `ge2`.`attributes` WHERE `attributes`.`proj_id`='$ID'");
$query3 = mysql_query("SELECT * FROM `ge2`.`category` WHERE `category`.`proj_id`='$ID'");
$query4 = mysql_query("SELECT * FROM `ge2`.`multipletarget` WHERE `multipletarget`.`proj_id`='$ID'");
$query5 = mysql_query("SELECT * FROM `ge2`.`data_cut` WHERE `data_cut`.`proj_id`='$ID'");
$query6 = mysql_query("SELECT * FROM `ge2`.`raw` WHERE `raw`.`proj_id`='$ID'");
//getting all array
while ($row = mysql_fetch_array($query)) {
$proj_alias = $row['proj_alias'];
$proj_id = $row['proj_id'];
$date_added = $row['date_added'];
}
while ($row1 = mysql_fetch_array($query2)) {
$attrib_param_id = $row1['param_id'];
$attrib_proj_id = $row1['proj_id'];
$attrib_cat_id = $row1['cat_id'];
$attrib_val_id = $row1['val_id'];
$attrib_name = $row1['name'];
$attrib_isCust = $row1['isCust'];
}
while ($row2 = mysql_fetch_array($query3)) {
$category_cat_id = $row2['cat_id'];
$category_name = $row2['name'];
$category_proj_id = $row2['proj_id'];
$category_desc = $row2['desc'];
}
while ($row3 = mysql_fetch_array($query4)) {
$multipletarget_id = $row3['id'];
$multipletarget_proj_id = $row3['proj_id'];
$multipletarget_mtarget1 = $row3['mtarget1'];
$multipletarget_mtarget2 = $row3['mtarget2'];
}
while ($row4 = mysql_fetch_array($query5)) {
$data_cut_id = $row4['id'];
$data_cut_proj_id = $row4['proj_id'];
$data_cut_name = $row4['name'];
$data_cut_param = $row4['param'];
$data_cut_lvl = $row4['lvl'];
$data_cut_val = $row4['val'];
}
while ($row5 = mysql_fetch_array($query6)) {
$raw_id = $row5['raw_id'];
$raw_proj_id = $row5['proj_id'];
$raw_p_id = $row5['p_id'];
$raw_url = $row5['url'];
$raw_ip = $row5['ip'];
$raw_pos = $row5['pos'];
$raw_datetaken = $row5['datetaken'];
$raw_used = $row5['used'];
$raw_fdc_id = $row5['fdc_id'];
$raw_dq = $row5['dq'];
}
// some data to be used in the csv files
$records = array(
$proj_alias, $proj_id, $date_added
);
$records2 = array(
$attrib_param_id, $attrib_proj_id, $attrib_cat_id, $attrib_val_id, $attrib_name, $attrib_isCust
);
$records3 = array(
$category_cat_id, $category_name, $category_proj_id, $category_desc
);
$records4 = array(
$multipletarget_id, $multipletarget_proj_id, $multipletarget_mtarget1, $multipletarget_mtarget2
);
$records5 = array(
$data_cut_id, $data_cut_proj_id, $data_cut_name, $data_cut_param,$data_cut_lvl,$data_cut_val
);
$records6 = array(
$raw_id, $raw_proj_id, $raw_p_id, $raw_url,$raw_ip,$raw_pos,$raw_datetaken,$raw_used,$raw_fdc_id,$raw_dq
);
//making an array to be used in loop
$set = array($records,$records2,$records3,$records4,$records5,$records6);
//names to be named for each csv file
$names = array('projects', 'attributes', 'category', 'multipletarget', 'data_cut', 'raw');
// create zip file
$zipname = $proj_alias;
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
// loop to create csv files
$n = 0;
foreach ($set as $setk => $sets) {
$n += 1;
$fd = fopen('php://temp/maxmemory:1048576', 'w');
if (false === $fd) {
die('Failed to create temporary file');
}
fputcsv($fd, $sets);
// return to the start of the stream
rewind($fd);
// add the in-memory file to the archive, giving a name
$zip->addFromString('BrainLink-' . $proj_alias . "-" . $names[$setk] . '.csv', stream_get_contents($fd));
//close the file
fclose($fd);
}
// close the archive
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname.'.zip');
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
// remove the zip archive
// you could also use the temp file method above for this.
unlink($zipname);
?>
Thanks in advance.
Well, it seems that you're independently iterating over all query results and overwriting the variables over and over again. So in the end, you have only last table results to work with.
You might try using JOIN OR UNION SELECT in MySQL to get all the items in one big query result row:
$query = mysql_query('SELECT proj.*, attrs.*
FROM `projects` AS proj
JOIN `attributes` AS attrs ON (attrs.project_id=proj.project_id)
<..more tables to join in the same manner..>
WHERE proj.`proj_id`= ' . $projectId);
And then, you'll just have to iterate only over a single query resource.
while ($row = mysql_fetch_array($query)) {
//your code here
}
Note, that if tables being JOIN'ed have the same column names, they will "overwrite" each other and you'll have to rename them yourself "on the fly".
Like so:
SELECT proj.field, proj.another_field, proj.conflicting_field_name AS unique_field_name
I did not read all of your code, but in each while loop, you only save last record. It should be something like this.
while($row = mysql_fetch_array($query)){
$proj_alias[] = $row['proj_alias'];
$proj_id[] = $row['proj_id'];
$date_added[] = $row['date_added'];
}
and the others like above.
Details: I have a php file that runs some sql and retrieve a list of information. I run through a loop of that information and want to call another php page and pass it some parameters from the data I am looping through.
Question: How do I execute another php page from within my php?
What I Have Tried: This is the php code that should be calling the second php page (the while loop should be calling the simplepush.php page for each result I get):
<?php
require_once "../database/config.php";
header("Content-type: application/json");
$sql = "SELECT user_ip_address FROM ft_users";
$res = mssql_query($sql);
if (mssql_num_rows($res)) {
while ($op = mssql_fetch_assoc($res)) {
exec('simplepush.php?token = ' . $op . '');
$arr[] = $op;
}
echo json_encode($arr);
//$op = mssql_fetch_assoc($res);
//$op['response'] = 200;
} else {
http_response_code(420);
$op = array(
'response' => 420
);
echo json_encode($op);
}
mssql_close();
?>
I have tried the following:
include ('simplepush.php?token = '.$op.'');
exec ('simplepush.php?token = '.$op.'');
require ('simplepush.php?token = '.$op.'');
shell_exec ('simplepush.php?token = '.$op.'');
Just do:
include ('simplepush.php');
Now $op will be available in simplepush.php. Consider this example:
//index.php
while ($op = mssql_fetch_assoc($res)) {
include ('simplepush.php');
$arr[] = $op;
}
//simplepush.php
print_r($op);
The contents of $op will be output each time through the loop.
I have this code to make a request to a file that process some xls files ( with phpexcel library ) :
$("#applyCalls").click(function(){
$.get("admin/processCalls.php");
});
the processCalls.php looks like this:
include '../phpexcel2/Classes/PHPExcel.php';
include '../phpexcel2/Classes/PHPExcel/IOFactory.php';
date_default_timezone_set('Europe/Bucharest');
$fisierInbound = "inbound.xls";
$fisierOutbound = "outbound.xls";
callsInbound();
function callsInbound() {
global $fisierInbound;
global $current;
global $con;
$identify = PHPExcel_IOFactory::identify('daily/' . $fisierInbound);
$objReader = PHPExcel_IOFactory::createReader($identify);
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load('daily/' . $fisierInbound);
$worksheet = $objPHPExcel->setActiveSheetIndex(0);
$query = mysqli_query($con, "SELECT * FROM users WHERE tip_user='agent' AND NOT (departament='online')");
while($usr = mysqli_fetch_array($query)) {
$data[] = $usr;
}
$worksheetTitle = $worksheet->getTitle();
$highestRow = $worksheet->getHighestRow(); // e.g. 10
$highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
$dataCalls = $worksheet->getCellByColumnAndRow(2, 2)->getValue();
$dataSubstr = substr($dataCalls, 53);
echo $dataSubstr;
foreach ($data as $db) {
for ($row = 6; $row <= $highestRow; ++ $row) {
$marca = $worksheet->getCellByColumnAndRow(3, $row)->getValue();
$nr = $worksheet->getCellByColumnAndRow(4, $row)->getValue();
if($db['marca'] == $marca) {
mysqli_query($con, "INSERT INTO dailycalls(data, nr, departament, oras, tip, id_user)
VALUES('$dataSubstr', '$nr', '" . $db['departament'] . "', '" . $db['oras'] . "', 'inbound', '" . $db['id'] . "')");
}
}
}
}
The thing is that I get "No data receive Error code: ERR_EMPTY_RESPONSE" (chrome) from processCalls, so the ajax request fails. As it fails I think it is running the file more than once, because I get more results than I need in the db. If I run the file manually I get the results I need. ( side note: the processCalls.php's query runs despite the error I get ). I hope that makes sense.
Thanks!
Check if the click function is getting binded more than once.
If the click function is binded more than once the function will be called multiple times.
$("#applyCalls").off('click', callServer).on('click', callServer);
var callServer = function(){
$.get("admin/processCalls.php");
};
Have you tried this?
$("#applyCalls").unbind("click").click(function(){$.get("admin/processCalls.php");});
Try to use stopPropagation() function.
Also as your PHP doesn't return anything you should use POST instead of GET
To understand the difference between POST and GET have a look at this article
$("#applyCalls").click(function(event){
event.stopPropagation()
$.post("admin/processCalls.php");
});