I am trying to run a php script that says basically, whilst two cells in my MySQL database are empty (t_trailerarrival and t_endsort), do something.
My code is as follows:
<?php
// Start Session, include authentication and dBConnection script
session_start();
include 'dbcon.php';
include 'sql_actuals.php';
$current_time = date("G");
while($query9_row['a_trailerarrival'] == NULL && $query10_row['a_endsort'] == NULL) {
echo "Trailer Arrival";
}
The $queryx_row['abc'] are all in the sql_actuals script that is included into this script.
For some reason, every time i run this script - my browser wont load the result (just loads for ever) and then my website at windows azure seems to crash and take a few minutes to restart.
Could someone please advise if there is a massively obvious error with my script? or point me at what the possible issue could be.
Many thanks in advance.
FYI, i have tried adding a line sleep(1); so that it gave the server it runs off a delay before having to run the program again but no luck.
You are never closing the while loop.
while($query9_row['a_trailerarrival'] == NULL && $query10_row['a_endsort'] == NULL) {
echo "Trailer Arrival";
}
Without modifying the while conditions during a while statement, once you start, you'll never stop. Therefore hanging the script and server.
You are not actually doing anything in your while statement except echoing a line.
Therefore
$query9_row['a_trailerarrival'] == NULL
and
$query10_row['a_endsort'] == NULL
are always true and never changing, and it will never exit the while loop. You need to put exit criteria in the while loop, such as:
$i=0;
while(($query9_row['a_trailerarrival'] == NULL
&& $query10_row['a_endsort'] == NULL )
|| $i==10) {
$i++;
echo "Trailer Arrival";
}
Although, logically speaking, you still need to run the query data.
** Edit **
Based upon your feedback, this doesn't sound like a while loop at all, but rather an if statement you need (with multiple elseif s).
if ($query9_row['a_trailerarrival'] == NULL && $query10_row['a_endsort'] == NULL){
echo "Trailer Arrival";
} elseif ($query9_row['a_trailerarrival'] == NULL && $query10_row['a_endsort']){
echo "End Sort";
} elseif ($query9_row['a_trailerarrival'] && $query10_row['a_endsort']){
echo "First Van";
}else {
// fourth condition:
// $query9_row['a_trailerarrival'] != NULL && $query10_row['a_endsort'] == NULL
}
I included a fourth condition when $query9_row isn't null, and $query10_row is null.
Related
I have a basic if/else statement is Laravel.
$model = MyModel::where('row', 'abc123')->first();
// Returns 3 statuses - connected, inactive, disconnected
$status = getStatus();
if ($status === 'connected') {
if (!$model->is_active) {
$model->timed_at = now();
}
$model->is_active = true;
}
else {
if ($model->is_active) {
$model->last_timed_at = $model->updated_at;
}
$model->is_active = false;
}
$model->save();
NOTE: This function is called repeatedly at an interval of 10 seconds.
The ELSE functionality works flawlessly outside the ELSE statement.
But the moment it's in the ELSE, it doesn't run at all.
I have proven that it does reach the ELSE by adding an echo which works fine.
Another odd thing, when I place the ELSE in the IF side, it works perfectly fine.
Thanks everyone for the input.
Turns out the data I was tweaking during my testing gave me unexpected (they were actually expected) results.
Not sure how to fully close a question, but leaving this here to say it was a non-issue.
I would like to set the disabled state of a form field based on the combination of 4 variables: processed, process started, process ended, user id
If it is not going to be processed, the form field should be disabled
If the process has started OR ended, it should be also disabled, except if the user id == 1. So User 1 can still fill the form field, even if the process has started OR ended. And it should be also disabled for User 1 also if it is not going to be processed.
I was trying this way, but doesn't work as I expect, so there must be a flaw in my logic or understanding how PHP works:
'disabled' => !$proc || (($proc_started || $proc_ended) && !$user_id == 1)
This way other users see the form field also enabled, which I don't want. Is it the hierarchy of the Logical Operators ?
Can you please point me to the right direction? Thanks.
!$user_id == 1 is (!$user_id) == 1
$foo = 42;
!$foo == false;
You want to write !($user_id == 1) or $user_id != 1
Should work.
if($user_id === 1) {
if($state != "processed") {
$state = "Enabled" // or anything else of your choice
}
} else {
$state = "Disabled";
}
We have a web page want to limit uo to 100 people can access concurrently, so we use a memcached to implement a global counter, e.g.
We are using http://www.php.net/manual/en/class.memcache.php so there is not cas, current code is something like
$count = $memcache_obj->get('count');
if ($count < 100) {
$memcache_obj->set('count', $count+1);
echo "Welcome";
} else {
echo "No luck";
}
As you can see there is race condition in the above code and but if we are not going to replace memcached extension which support cas, it is able to support it using PHP code only?
As answer to "emcconville". This is non-blocking even without CAS.
If your concerned about race conditions, and the count value is completely arbitrary, you can use Memcache::increment directly before any business logic.
The increment method will return the current value after the incrementation takes place; of which, you can compare results. Increment will also return false if the key has yet to be set; allowing for your application to deal with it as needed.
$current = $memcache_obj->increment('count');
if($current === false) {
// NOT_FOUND, so let's create it
// Will return false if has just been created by someone else.
$memcache_obj->add('count',0); // <-- no risk of race-condition
// At this point 'count' key is created by us or someone else (other server/process).
// "increment" will update 0 or whatever it is at the moment by 1.
$current = $memcache_obj->increment('count')
echo "You are the $current!";
}
if ($current < 100) {
echo "Hazah! You are under the limit. Congrats!";
} else {
echo "Ah Snap! No Luck - you reached the limit.";
// If your worried about the value growing _too_ big, just drop the value down.
// $memcache_obj->decrement('count');
}
If your concerned about race conditions, and the count value is completely arbitrary, you can use Memcache::increment directly before any business logic.
The increment method will return the current value after the incrementation takes place; of which, you can compare results. Increment will also return false if the key has yet to be set; allowing for your application to deal with it as needed.
$current = $memcache_obj->increment('count');
if($current === false) {
// NOT_FOUND, so let's create it
$memcache_obj->set('count',1); // <-- still risk of race-condition
echo "Your the first!";
} else if ($current < 100) {
echo "Hazah! Your under the limit.";
} else {
echo "Ah Snap! No Luck";
// If your worried about the value growing _too_ big, just drop the value down.
// $memcache_obj->decrement('count');
}
function memcache_atomic_increment($counter_name, $delta = 1) {
$mc = new Memcache;
$mc->connect('localhost', 11211) or die("Could not connect");
while (($mc->increment($counter_name, $delta) === false) &&
($mc->add($counter_name, ($delta<0)?0:$delta, 0, 0) === false)) {
// loop until one of them succeeds
}
return intval($mc->get($counter_name));
}
The comments in Memcache::add include an example locking function, have you tried it out?
I'm attempting to run a fairly large amount of updates/inserts on a table using multi_query. There are ~14,000 queries total, but the function only executes ~480, then it stops without errors and PHP continues the script beyond the snip below:
if($this->db->conn_id->multi_query($sql)){
do{
// echo $line.' '.mysqli_sqlstate($this->db->conn_id).'<br>';
}while($this->db->conn_id->more_results() && $this->db->conn_id->next_result());
$this->message->set('Import complete.','success',TRUE);
}else{
$this->message->set('Import could not be completed. '.mysqli_error($this->db->conn_id),'error',TRUE);
}
mysqli::multi_query only returns false if the first statement fails. To get the errors from the other queries in your set, you need to call mysqli::next_result() first, which is what your do while() is doing.
However, since mysqli::next_result() returns false on failure, it will cause the loop to end and the 'Import complete' message to be displayed. You probably need to check for an error before setting the success message, and only if the error is blank, return success.
The following should at least show you the error if there was one later in the statement.
if($this->db->conn_id->multi_query($sql)){
do{
// echo $line.' '.mysqli_sqlstate($this->db->conn_id).'<br>';
} while($this->db->conn_id->more_results() && $this->db->conn_id->next_result());
if ($error = mysqli_error($this->db->conn_id)) {
$this->message->set('Import could not be completed. ' . $error,'error',TRUE);
} else $this->message->set('Import complete.','success',TRUE);
} else {
$this->message->set('Import could not be completed. '.mysqli_error($this->db->conn_id),'error',TRUE);
}
i have to value
$mo=strtotime($input_array['MondayOpen']);
$mc=strtotime($input_array['MondayClose']);
now i need a if condition to display an error on below conditions
if one of them($mo or $mc) are empty, null or blank.
if close time($mc) is less than open time($mo)
means if both are empty(null) or $mc>$mo then go further
please suggest optimized one line if condition for this
i know it seems very basic question, but i m facing problem when both are null
either i was using simple
if(($mo==NULL && $mc!=NULL) || ( $mo>=$mc && ($mo!=NULL && $mc!=NULL)) )
Keep in mind that 0, null, and blank all mean completely different things here. As indicated previously, strtotime will never return NULL. However, 0 is a valid unix timestamp, whereas false means that the strtotime function was unable to process the value provided.
Also, you've requested that a single-line solution; however, in my opinion, it is much better in this case to write out each condition and display a different error message for each condition. That way, the user knows what actually went wrong. Perhaps this is a better way:
// Only check for errors if we have at least one value set
if (!empty($input['MondayOpen']) || !empty($input['MondayClosed']) {
$mo = strtotime($input['MondayOpen']);
$mc = strtotime($input['MondayClosed']);
$invalid = false;
if (false === $mo) {
echo "Invalid Opening Time\n";
$invalid = true;
}
if (false === $mc) {
echo "Invalid Closing Time\n";
$invalid = true;
}
if (!$invalid && $mc <= $mo) {
echo "Closing time must be After Opening Time\n";
$invalid = true;
}
if ($invalid) {
exit(); // Or handle errors more gracefully
}
}
// Do something useful
All right. How about this.
It checks whether $mo and $mc are valid dates using is_numeric. Any NULL or false values will be caught by that.
I haven't tested it but it should work.
I spread it into a huge block of code. In the beginning, when learning the language, this is the best way to make sense out of the code. It is not the most elegant, nor by far the shortest solution. Later, you can shorten it by removing whitespace, or by introducing or and stuff.
I'm not 100% sure about the number comparison part, and I don't have the time to check it right now. You'll have to try out whether it works.
You need to decide how you want to handle errors and insert the code to where my comments are. A simple echo might already do.
// If $mo or $mc are false, show error.
// Else, proceed to checking whether $mo is larger
// than $mc.
if ((!is_numeric($mo)) and (is_numeric($mc)))
{
// Error: $mo is either NULL, or false, or something else, but not a number.
// While $mc IS a number.
}
elseif ((!is_numeric($mc)) and (is_numeric($mo)))
{
// Error: $mc is either NULL, or false, or something else, but not a number.
// While $mo IS a number.
}
else
{
if (($mc <= $mo) and ((is_numeric($mc) or (is_numeric($mo)))))
{
// Error: closing time is before opening time.
}
else
{
// Success!!
}
}
in php, strotime will return a integer or false. Checking for null in this case will never bear fruit, but otherwise...
if((!$mo xor !$mc) || ($mc && $mc<=$mo)){
print('error');
}else{
print('no_error');
}
oops, edited for correctness. I transposed $mc and $mo. XOR should be correct though.
You can try:
print ((empty($mo) && empty($mc)) || ($mc > $mo)) ? 'case_true_message' : 'case_false_message';
But you should also check the manual :) - for basic control structures