Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
my problem is that i have to implement variable conditions which means that the user is able to define a VALUE for period of time.This data will be stored in mysql. PHP is used on server-side.
i.e.
FROM 2018-01-01 TO 2018-01-03 VALUE 10;
FROM 2018-01-04 TO 2018-01-06 VALUE 20;
DEFAULT (used if not in time gap) VALUE 100;
Therefore I thought a switch case can be an option. But is it possible to have a foreach loop on cases?
like:
$date = "2018-01-01";
switch ($date) {
foreach(... as $data){
case $data:
//load variable
break;
}
default:
//load default values
}
Maybe i'm on the wrong way - pls hlp.
No, your syntax is wrong. In all programming languages that I can think of, you are not allowed to overlap blocks. A switch block can be contained in a loop, or one or more of it's cases' blocks may contain their own loops. (switch is a special case, in that may not have code outside it's case statements.)
You're (in a sense) trying to terminate a for-loop block, inside the block of an if statement within it.
The problem with your code, is that it will be unmaintainable, difficult to understand, and slightly inefficient.
The easiest thing to do, would be to run a cron job or something else which would be periodical and check if today's date falls in the date region defined by your user in the mysql data.
You could simply do with a better SQL statement to grab the data and store it in a slightly different way - for example:
start_date
end_date
and then your SQL result would do all the work of your current switch statement (the switch statement won't work as expected anyway).
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I have the following simple PHP code:
$timeRange = new DatePeriod(
new DateTime('09:00:00'),
new DateInterval('PT30M'),
new DateTime('18:00:00')
);
foreach ($timeRange as $time) {
$options[$time->format('H:m')] = $time->format('H:m');
}
I am expecting to get a list of times out of this that starts at 09:00, 09:30, 10:00, 10:30... and every half hour to ...16:30, 17:00, 17:30, 18:00.
What I'm actually getting is this list of times:
09:10, 10:10, 11:10, 12:10, 13:10, 14:10, 15:10, 16:10, 17:10
As you can see, this is wrong on two counts: it is incrementing by an hour each time rather than half an hour, and it is starting at an arbitrary time ten minutes past the hour.
Both of these are consistent; it isn't based on the time I ran the code, for example.
I also tried adding a hard-coded date to the DateTime classes, so that they looked like this:
new DateTime('2018-01-01 09:00:00')
This changed the output such that all the results were one minute past the hour. Again, it incremented by an hour each time.
I can't explain this behaviour. It seems to be completely wrong. Can anyone explain it, and tell me what I need to do to fix this.
I can, of course, revert to using timestamps; I have code for this that works already. But I would like to know what is going on with the DatePeriod.
For reference, this is running under PHP 7.2.4.
$options[$time->format('H:m')] = $time->format('H:m');
m is the month identifier. You want i:
$options[$time->format('H:i')] = $time->format('H:i');
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I am a beginner at PHP and MYSQL. Here is my simple code to add data to a data base. it is not working
the connection.php(sets up the mysql connection variables) files have already been created and are working fine with other files and functions. Am receiving no errors while this code here does not add the data to the database
could someone please tell me where the problem could be?
<?php
if (isset($_POST['bookt']) & isset($_POST['type']) & isset($_POST['publisher']) & isset($_POST['year']) & isset($_POST['class']) & isset($_POST['subject'])) {
//set the values
$bookt= $_POST['bookt'];
$type= $_POST['type'];
$publ=$_POST['publisher'];
$year=$_POST['year'];
$class= $_POST['class'];
$subj= $_POST['subject'];
//INSERTING A ROW
$add_query= "INSERT INTO books ('Book Title','Type','Publisher','Yearp', 'Class','Subject')
VALUES ('$bookt','$type','$publ','&year','$class','$subj')";
//query
$result=mysql_query($add_query);
if (!$result) {die("couldn't perform query".mysql_error());}
if ($result) {echo " </ br> <p><script type='text/javascript'>alert('INSERT SUCCESSFUL!!!');</script></p><br /><br /> insert id was ".mysql_insert_id();}
};
?>
You have a lot of major problems with this code.
First, please don't use mysql_*; the mysql_* functions are outdated, deprecated, and insecure. They were removed entirely from PHP 7. Use MySQLi or PDO instead.
Second, the Boolean "and" operator is &&, not & (the bitwise "and" operator).
Third, it's $year, not &year.
Fourth, put column names in backticks, not single quotes ('...'):
$add_query= "INSERT INTO books (`Book Title`,`Type`,`Publisher`,`Yearp`, `Class`,`Subject'`)
VALUES ('$bookt','$type','$publ','$year','$class','$subj')";
Single quotes will cause your query to fail. This is why your query isn't working at all.
Fifth, you aren't doing any error checking or data validation.
Sixth, you are wide open to SQL injection. You need to use prepared statements and never put user input directly into SQL.
There may be even more issues, but these are the big ones.
If you want multiple conditions in your if-statement use a logical operator "&". Also mysql_ has been gone from PHP7 for a long time.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
What is the best alternative of using several (23 in my case) if-elseif nested loops in PHP?
If performance is your concern, if statements use check followed by a jump to the next clause where as in a switch the value is loaded first, compared and iterated through the value table to find a match, which is faster in most cases.
For readability I think switch is better when you have more than two conditions.
But primarily everything depends on the usage circumstance.
If you are in doubt of which to choose:
Choose switches when you have an easy to read expression that will
generate multiple results that you must then execute logic based
upon.
If your expressions are unrelated, result in boolean conditions only,
or become complex/related (like if a then b, if c then b, if d then a sometimes b), then stick with ifs. (As said here)
The switch statement will do it.
http://php.net/manual/en/control-structures.switch.php
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am trying to run a PHP if statement that says if there are more than 3600 seconds between two MySQL timestamps than do something. I think I have the IF statement written correctly but something is going on where it is always being resolved to true.
$time1=mysqli_query($con,"SELECT time_to_sec(max(time)) as time FROM table");
$time2=mysqli_query($con,"SELECT time_to_sec(max(time)) as time FROM table and time <>(SELECT max(time) FROM table)");
if (($time1->fetch_object()->time) - ($time2->fetch_object()->time) > 3600);
{
echo $test
}
When I run:
echo $time1->fetch_object()->time-$time2->fetch_object()->time;
It shows the correct value that I would expect but even if its less than 3600 it still does the echo $test. Any ideas what can be causing this?
Thank you!!!
Use CASE statements, a better and efficient approach:
Select event, case when TIMESTAMPDIFF(SECOND, last_timstamp, first_timestamp)<3600 then `under_time` when TIMESTAMPDIFF(last_timstamp, first_timestamp)>3600 then `over_time` end case as `duration_flag` from your_table where your_conditions
Then in your PHP you condition the output based on the queried flag.
This way you make less requests to the server, and has a cleaner query.
Maybe mysql has an old bug with TIMESTAMPDIFF, so if it doesn`t work, use this instead:
Time_To_Sec(last_timstamp) - Time_To_Sec(first_timestamp)
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
This question made me curious.
The correct answer demonstrates using MySQL syntax to add values of a certain range within a database and return the result. Would it be better done retrieving the results within the daterange and computing the total in PHP? Or should the DB be used wherever applicable? Obviously with the example given in that question, it won't really matter unless we're talking thousands of orders, but for arguments sake...
Simple calculations, especially for aggregation type scenarios, should definitely be handled on the database for multiple reasons:
Less data returned over the wire from the database
Database can take advantage of indexing
Database is faster at aggregating data, because that's what they're made for.
Using code such as PHP makes sense only when you have really complex calculations or business logic that are not handled easily by a database tool, or when using logic that databases do not do efficiently, such as string manipulation.
The general rule of thumb is something like this:
Return as little data as absolutely necessary from the database, and apply any logic that reduces the number of rows at the database side.
Work with the data returned to do complex business logic and markup (i.e., HTML) with your coding language.
Why would you rewrite code? SUM(somefield) WHERE (condition) gives you exaclty what you need.
$rows = mysql_query('SELECT SUM(somefield) AS `sum` FROM table WHERE (condition)');
$row = mysql_fetch_array($rows);
$sum = $row['sum'];
On the contrary, you suggest to do something like this:
$rows = mysql_query('SELECT somefield FROM table WHERE (condition)');
$sum = 0;
while ($row = mysql_fetch_assoc($rows)) {
$sum += $row['somefield']; }
}
I don't see why. ;-)
And that's pure for the code, indeed more data is being transported in the second case, to name one thing.