I'd like to store a datetime variable into different tables by using two functions. I use constraint in CI but still have no luck.
This is the constraint:
$date_now = date("ymdhis");
define('TODAY_DATE',$date_now);
These are the functions:
public function save_activity_m(){
foreach($details as $rows){
$stock_in = $rows['product']."_".TODAY_DATE;
$data['STOCK_IN'] = ($rows['product'] == "") ? NULL : $stock_in;
$this->MProduct->ins_product_m($data);
}
echo "<script type='text/javascript'>alert('New stock arrived');window.top.location.reload();</script>";
}
public function save_notifikasi(){
$lampiran = $this->input->post('lamp');
$data['note_date'] = $lampiran."_".TODAY_DATE;
$data['note'] = $this->input->post('isi');
$this->MProduct->ins_notif($data);
echo "<script type='text/javascript'>alert('You have a notification');</script>";
}
How to make the datetime is the same for $data['STOCK_IN'] and $data['note_date']?
Since the web is stateless, no data in a PHP variable will be held from one page (or load) to another; essentially you're booting the application from scratch each time.
The only way around this is to use some sort of semi-persistent storage such as a cookie or session variable (or persistent storage like the database) - setting a constant, e.g. define('TODAY_DATE',$date_now); will only make that data constant for the current execution of the script(s).
This is a basic example using session storage ($_SESSION):
<?php
// crank up the session
// you may well have one running already,
// in which case ignore this
session_start();
// store the execution time for this script
// as a session variable if it's NOT already set
// i.e. don't overwrite it
if(empty($_SESSION['time_now'])) $_SESSION['time_now'] = date("ymdhis");
public function save_activity_m() {
foreach($details as $rows) {
$stock_in = $rows['product'] . "_" . $_SESSION['time_now'];
$data['STOCK_IN'] = ($rows['product'] == "") ? NULL : $stock_in;
$this->MProduct->ins_product_m($data);
}
echo "<script type='text/javascript'>alert('New stock arrived');window.top.location.reload();</script>";
}
/**
* Assuming this is the last thing you want to
* do with 'time_now' you should unset it here
*/
public function save_notifikasi() {
$lampiran = $this->input->post('lamp');
$data['note_date'] = $lampiran . "_" . $_SESSION['time_now'];
$data['note'] = $this->input->post('isi');
$this->MProduct->ins_notif($data);
// since we're done with the 'time_now' session
// variable we need to unset it...
unset($_SESSION['time_now']);
echo "<script type='text/javascript'>alert('You have a notification');</script>";
}
// just to be on the safe side unset the 'time_now' session var
// if it's older than 1 minute - otherwise future calls to this
// script, by the same user, during the same session will use
// the stored value from $_SESSION['time_now']
if(isset($_SESSION['time_now'])) {
$sessionTime = DateTime::createFromFormat('ymdhis', $_SESSION['time_now']);
$oneMinuteAgoTime = new DateTime('-1 minute');
if($sessionTime < $oneMinuteAgoTime) {
unset($_SESSION['time_now']);
}
}
The caveat is that because you've stored the time in a session variable, unless you update or unset it, it will always be there (for the current session) - so if the user runs the script again it'll just use the stored time from the session.
I've put in a couple of unset() calls to try and work around this.
See PHP: define. It's a constant and it should have the same value if the two functions executed in the same time the script is running.
Related
I'm tying to extract data from thousands of premade sql files. I have a script that does what I need using the Mysqli driver in PHP, but it's really slow since it's one sql file at a time. I modified the script to create unique temp database names, which each sql file is loaded into. Data is extracted to an archive database table, then the temp database is dumped. In an effort to speed things up, I created a script structured 4 scripts similar to the one below, where each for loop is stored in it's own unique PHP file (the code below is only for a quick demo of what's going on in 4 separate files), they are setup to grab only 1/4 of the files from the source file folder. All of this works perfectly, the scripts run, there is zero interference with file handling. The issue is that I seem to get almost zero performance boost. Maybe 10 seconds faster :( I quickly refreshed my PHPmyadmin database listing page and could see the 4 different databases loaded at anytime, but I also noticed that it looked like it was still running more or less sequentially as the DB names were changing on the fly. I went the extra step of creating an unique user for each script with it's own connection. No improvement. Can I get this to work with mysqli / PHP or do I need to look into some other options? I'd prefer to do this all in PHP if I can (version 7.0). I tested by running the PHP scripts in my browser. Is that the issue? I haven't written any code to execute them on the command line and set them to the background yet. One last note, all the users in my mysql database have no limits on connections, etc.
$numbers = array('0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20');
$numCount = count($numbers);
$a = '0';
$b = '1';
$c = '2';
$d = '3';
$rebuild = array();
echo"<br>";
for($a; $a <= $numCount; $a+=4){
if(array_key_exists($a, $numbers)){
echo $numbers[$a]."<br>";
}
}
echo "<br>";
for($b; $b <= $numCount; $b+=4){
if(array_key_exists($b, $numbers)){
echo $numbers[$b]."<br>";
}
}
echo "<br>";
for($c; $c <= $numCount; $c+=4){
if(array_key_exists($c, $numbers)){
echo $numbers[$c]."<br>";
}
}
echo "<br>";
for($d; $d <= $numCount; $d+=4){
if(array_key_exists($d, $numbers)){
echo $numbers[$d]."<br>";
}
}
Try this:
<?php
class BackgroundTask extends Thread {
public $output;
protected $input;
public function run() {
/* Processing here, use $output for... well... outputting data */
// Here you would implement your for() loops, for example, using $this->input as their data
// Some dumb value to demonstrate
$output = "SOME DATA!";
}
function __construct($input_data) {
$this->input = $input_data;
}
}
// Create instances with different input data
// Each "quarter" will be a quarter of your data, as you're trying to do right now
$job1 = new BackgroundTask($first_quarter);
$job1->start();
$job2 = new BackgroundTask($second_quarter);
$job2->start();
$job3 = new BackgroundTask($third_quarter);
$job3->start();
$job4 = new BackgroundTask($fourth_quarter);
$job4->start();
// ==================
// "join" the first job, i.e. "wait until it's finished"
$job1->join();
echo "First output: " . $job1->output;
$job2->join();
echo "Second output: " . $job2->output;
$job3->join();
echo "Third output: " . $job3->output;
$job4->join();
echo "Fourth output: " . $job4->output;
?>
When using four calls to your own script through HTTP, you're overloading your connections for no useful reason. Instead, you're taking away spaces for other users who may be trying to access your website.
On Page Variable =
$lgc_code = '1,2,3,15,23,30';
Cookie = 'lgc_cntl'
My cookie is housing logic codes for each user to determine what banners or icons should show based on previous web pages visited. I have written the following function:
$lgc=$lgc_code;
// check for variable for multiple codes
$expEncArr = explode(",", $lgc);
$results = count($expEncArr);
if(isset($_COOKIE['lgc_cntl'])) {
// read cookie
$cookie_codes = $_COOKIE['lgc_cntl'];
// Build Array of cookie codes
$expEncArr2 = explode(",", $cookie_codes);
foreach($expEncArr as $l_code) {
if(in_array($l_code, $expEncArr2)) {
$lgc_codes=$_COOKIE['lgc_cntl'];
} else {
$lgc_codes=$_COOKIE['lgc_cntl'].','.$l_code;
} // end array search statement
// add campaign to cookie
setcookie('lgc_cntl',$lgc_codes,time() + (86400 * 365), "/", ".oru.edu"); // 86400 = 1 day
} // end foreach statement
} else {
$lgc_codes = $lgc;
// add campaign to cookie
setcookie('lgc_cntl',$lgc_codes,time() + (86400 * 365), "/", ".oru.edu"); // 86400 = 1 day
} // end isset(cookie) if / else statement
If there is no cookie set, the function works perfectly but if there is a cookie found it only adds the last variable in the array versus any codes not found in the cookie already.
The function should work as follows:
Separate on-page variable into an array
Check for the cookie
Separate Cookie values into an array
Compare the variables on page to values in cookie
Add any on page variables not found in the cookie
It is working all the way through but when the cookie is set, it is only adding the last variable in the string even if none of the others are not located in the cookie array. What am I doing wrong or how can I solve this?
This is a common mistake - $_COOKIE is not affected by calling setcookie. This is because $_COOKIE is created at the beginning of the PHP script execution based on data sent from the browser, and setcookie sends data to the browser.
Consequently, each time you run this line:
$lgc_codes=$_COOKIE['lgc_cntl'].','.$l_code;
Your value of $lgc_codes is the cookie string originally sent by the browser plus exactly one extra code.
The solution is to instead use a local variable, such as $new_cookie_value, to build up the full string, and then call setcookie once:
$new_cookie_value = $_COOKIE['lgc_cntl'];
foreach($expEncArr as $l_code) {
// if statement removed to keep example brief
// Add extra code to list
$new_cookie_value = $new_cookie_value .','.$l_code;
}
// Now call setcookie once with the desired value
setcookie('lgc_cntl',$new_cookie_value,time() + (86400 * 365), "/", ".oru.edu");
[Aside: Do not underestimate the value of good variable names. Your code would be much clearer if $expEncArr and $expEncArr2 had longer names which described what the difference was between them. Similarly, $lgc, $lgc_code, $lgc_codes, etc.]
Your logic is very muddled. This is what should be in the first portion of your if block
// read cookie
$cookie_codes = $_COOKIE['lgc_cntl'];
// Build Array of cookie codes
$expEncArr2 = explode(",", $cookie_codes);
$lgc_codes = $_COOKIE['lgc_cntl'];
foreach ($expEncArr as $l_code)
{
if (!in_array($l_code, $expEncArr2))
{
$lgc_codes .= ',' . $l_code;
}
}
setcookie('lgc_cntl', $lgc_codes, time() + (86400 * 365), "/", ".oru.edu");
I am using Zend framework 1 and I need to change the session id at runtime with a predefined prefix, however I am getting the following error "The session has already been started. The session id must be set first." The issue is that the session state still remains started even after calling the destroy and writeclose. I also tried using the php methods unset & destroy but still same issue.
$oldSession = new Zend_Session_Namespace();
Zend_Session::destroy();
Zend_Session::writeClose();
$sessId = "dskjfghdsjfhsdkf"; //Random hash
Zend_Session::setId("myprefix".$sessId);
$newSession = new Zend_Session_Namespace();
foreach($oldSession as $idx => $data){
$newSession->$idx = $data;
}
Looks like it is not possible,
Snippet from Zend_Session.php:
if (!self::$_unitTestEnabled && defined('SID')) {
/** #see Zend_Session_Exception */
require_once 'Zend/Session/Exception.php';
throw new Zend_Session_Exception('The session has already been started. The session id must be set first.');
}
I am stuck, I can't find any reference to this problem. It shouldn't be happening. The global variable $assignmentInfo is passed into the function, manipulated, and returned as a different variable.
BUT, the local manipulations within the function are propagated to the global variable, so that the next time the function gets called, $assignmentInfo has been changed. I want to pass in the same, unchanging version of $assignmentInfo each time I call the function.
Any suggestions?
function studentScores($submissionInfo, $assignmentInfo){
//********************************** Add submission data to assignment data ****************************************************************************
foreach($assignmentInfo as $assignmentGroup){
foreach($assignmentGroup->assignments as $assignment){
foreach($submissionInfo as $submission){
if(isset($assignment->id) and isset($submission->assignment_id) and $assignment->id == $submission->assignment_id){
if (isset($submission->score)){$assignment->score = $submission->score;}
if (isset($submission->submitted_at)){$assignment->submitted_at = $submission->submitted_at;}
if (isset($submission->workflow_state)){$assignment->workflow_state = $submission->workflow_state;}
break;
}
}
}
}
$studentScores = $assignmentInfo;
return $studentScores;
}
$studentScores = studentScores($submissionInfo->submissions, $assignmentInfo);
Though after reading explanations about setting cookie and not working for first time i find it difficult to resolve the below problem as am new to php and cookies.
I have a webpage with for (e.g) cp.php, login.php, header.php, maindata.php , bottom.php. Whenever i login to the webpage cp.php will be processed from there 1.header.php will be called first 2.maindata.php will be called and 3.bottom.php will be called.
So am setting my cookie at maindata.php and the code is like,
<?php
$cid = $_GET["id"];
$XmlPath = $_GET["path"];
$numpath = $_GET["numpath"];
$finepath =$_GET["finepath"];
$Tech =$_GET["tech"];
$read_str="";
function read($Path)
{
$temp="";
if(file_exists($Path))
{
$library = new SimpleXMLElement($Path,null,true);
foreach($library->children("SAS") as $info){
foreach($info->children("SAS") as $attributes){
$nameVal = $attributes->Name."=".$attributes->Value;
$str_temp .=$nameVal."#";
}
}
}else
{
$str_temp ="NA";
}
return $str_temp;
}
$arrpath =explode(",",$XmlPath);
/*Reading and storing arrpath[0] has the path of xml to be parsed*/
$strG=read($arrpath[0]);
$strC=read($arrpath[1]);
$strB =read($arrpath[2]);
setcookie($cid.'strE',$strG);
setcookie($cid.'comstr',$strC);
setcookie($cid.'basstr',$strB);
(....)
in the same file am reading the cookie using the below code,
$read_str =$_COOKIE[$cid.'strE'].$_COOKIE[$cid.'comstr'].$_COOKIE[$cid.'basstr'];
after this process is done bottom.php will be called and for the first time loading is completed.As i said for the first time am not getting any value in $read_str, but if i refresh the page and do all the process again i am getting the value.
As SETCOOKIE will return TRUE incase of successfully setting cookie i tried putting it in an if-loop and it returned false even for the first time.
kindly assist me in finding where the problem exists!
Make use of isset to check if a cookie exists and then try setting one.
Something like this.
if(!isset($_COOKIE['yourcookie'])) {
setcookie('yourcookie', 'Some data !');
$_COOKIE['yourcookie'] = 'Some data !';
}
echo $_COOKIE['yourcookie'];
I arrived here looking for an answer as well. Here's the deal.
When you set a cookie it can only be accessed on the next page load, that is why you can't access it after you set it. If you really need to work with the cookie data right away, you could set the value directly in global cookie such as:
$_COOKIE['my_cookie'] = 'i am a cookie';
Use setcookie()just the same so you can set expiration, domain, etc..