I have a script that updates the information of various livestream channels while they are active. I want to check if $max_viewers is greater than $current_viewers.
In this case I do not need to take action, however if $current_viewers is larger I want to update the max_viewers field in the database.
I have tried several ways and methods from research, but my PHP is limited and self taught and I think I am misunderstanding the outcome of my statements.
I have tried:
$current_viewers > $max_viewers
$current_viewers >= $max_viewers
But these seem to always update the max_viewer count, or never if reversed. Hence I think I am misunderstanding how these work and what they return.
You should have something like:
$max_viewers = 4;
$current_viewers = 2;
if ($current_viewers > $max_viewers) {
// Current viewers has exceeded the maximum
echo 'exceeded';
} else {
// Current viewers is either less than or equal to the maximum
echo 'not exceeded';
}
In the above example, not exceeded would be shown. For your example, you probably want to replace echo 'exceeded'; with your call to update the database record.
Related
im currently stuck with an issue. Ive built a basic "team-work platform" in which you can set tasks in a to-do list. I've implemented the functionality that can mark a task as complete by setting the value of done to 1
I need to be able to check if all of the tasks in the list are set to done, and if so echo something. My code checks for the value 1, but it settles with a single entry being set to 1. But i need it to check if all tasks have the value 1 and if they do it should echo something.
$res3 = mysql_query("SELECT * FROM tasks WHERE tasks.planet_id=1 AND team_id=$teamid AND done=1")
or die(mysql_error());
if ($res3 && mysql_num_rows($res3) > 0)
{
echo 'Complete!';
}
else
{
echo 'Not done yet!';
}
I'll try to give you an example of how i want it to work: Lets say i have 10 tasks in the table. I want the code to recognise when all 10 of these tasks are marked as done with the value 1 set. And then echo "all your tasks are complete". So it needs to somehow loop through all the entries in the table and check if they are all set to 1, and when they are all set to 1 it echoes something.
Please help! :)
Assuming that done is an integer can can be either 0 or 1, you could do something like:
SELECT COUNT(*) total, SUM(done) totalDone FROM tasks WHERE tasks.planet_id=1 AND team_id=$teamid;
And then test in your PHP code that total == totalDone.
Alternatively, if you really want to only get a row out of the database when total == totalDone (as your comments seem to suggest), you could write something like this:
SELECT * FROM (SELECT COUNT(*) total, SUM(done) totalDone FROM tasks WHERE tasks.planet_id=1 AND team_id=$teamid) _X WHERE _X.total = _X.totalDone;
But that just adds a lot of extra complexity for no real gain, and I wouldn't recommend doing it that way.
Note that you should not use mysql_* functions in new code, and should instead use either mysqli or PDO. mysql_* is not recommended for new code.
Also, you should be careful with using variables directly in query strings. That can easily lead to sql injection vulnerabilities. Instead, use parameterized queries with mysqli or PDO.
The answer to 'all tasks done' is best done with the question of how many tasks where done <> 1.
I.e.
SELECT count(*) as 'incomplete'
FROM tasks
WHERE tasks.planet_id=1
AND team_id=$teamid and done <> 1;
Therefore you're able to use the code:
if($res3) {
$incompleteQueryResult = mysql_fetch_assoc($res3);
if ($incompleteQueryResult['incomplete'] > 0) {
echo "Not done yet";
} else {
echo "Complete!";
}
} else {
echo "Could not retrieve completed tasks";
}
If you still need to retrieve both the number of completed tasks as well as the number of incomplete, you could modify the query similar to the following.
SELECT
IF(done = 1, 'complete', 'incomplete') as status,
COUNT(*) AS 'number_in_status'
FROM tasks
WHERE tasks.planet_id=1
AND team_id=$teamid
GROUP BY done
And you'll need to modify how you retrieve it in the PHP as well if so.
If you need to know all of the above, then either execute two queries (one as an aggregate/summary and one as the full data set) or keep track of it in a variable. e.g.
$numIncompleteTasks = 0;
while($row = mysql_fetch_assoc($res3)) {
$numIncompleteTasks += ! (bool) $row['done'];
}
// you now know how many tasks are incomplete.
You could modify this code to track both complete and incomplete.
Deprecation notice.
I'd recommend reviewing your use of mysql_* functions - PHP deprecated and removed these functions in recent versions of PHP.
The answer from jbafford will not work in certains conditions.
Let's imagine we have only three possible values: 0,1 and 2. In the case of 0+1+2, the algorithm will say that COUNT = SUM, when in reality, we have a {0,1,2} and not {1,1,1}.
Why do I ask? Because I'm looking for a way in MYSQL to check if it is all ones, and I ruled out COUNT=SUM or in my case, taking the average, as I have this exception in my data.
A way to handle this exception is to add a COUNT DISTINCT. If COUNT DISTINCT=1 and COUNT=SUM, then the dataset is only 1s.
Image : http://i40.tinypic.com/2hodx55.png
I have built a Network Interface Monitor using Php and SNMP , but now when i execute it on localhost i see my graph goes to origin(0) again and again (Please see the image) and also the speed on Y axis is wrong. At times it goes in Millons and Millions.
please can anyone tell me what is the problem in the code below
<?php
$int="wlan0";
session_start();
$rx0 =snmpget('localhost','public','.1.3.6.1.2.1.2.2.1.10.3');
$tx0 =snmpget('localhost','public','.1.3.6.1.2.1.2.2.1.16.3');
sleep(5);
$rx1 =snmpget('localhost','public','.1.3.6.1.2.1.2.2.1.10.3');
$tx1 =snmpget('localhost','public','.1.3.6.1.2.1.2.2.1.16.3');
$rx0 = substr($rx0, 11);
$tx0 = substr($tx0, 11);
$rx1 = substr($rx1, 11);
$tx1 = substr($tx1, 11);
$tBps = $tx1 - $tx0;
$rBps = $rx1 - $rx0;
$round_rx=$rBps;
$round_tx=$tBps;
$time=date("U")."000";
$_SESSION['rx'][] = "[$time, $round_rx]";
$_SESSION['tx'][] = "[$time, $round_tx]";
$data['label'] = $int;
$data['data'] = $_SESSION['rx'];
if (count($_SESSION['rx'])>60)
{
$x = min(array_keys($_SESSION['rx']));
unset($_SESSION['rx'][$x]);
}
echo '{"label":"'.$int.'","data":['.implode($_SESSION['rx'], ",").']}';
?>
What you are seeing here is a classic case of polling a counter faster than its refresh interval. It is often the case that counters (in this case, interface counters) are updated every few seconds (10-15 seconds is a common value).
If the counter updates every 15 seconds, and you ask for data every 5 seconds, then you will receive the same value once or twice in a row (depending on latency, processing time, etc.). If you receive the same value twice, then you will see a zero value for the delta (which is what your image shows).
There are two ways to get around this:
Ask for data less frequently than the counters are updated (30-second polling usually works fine). Obviously, if you can find out the exact refresh interval, then you can use that.
Modify the configuration of your equipment to refresh its counters faster. Sometimes this is possible, sometimes it is not; it just depends on the manufacturer, the software, and what has been implemented.
For Net-SNMP "snmpd" daemons, you can walk NET-SNMP-AGENT-MIB::nsCacheTable (1.3.6.1.4.1.8072.1.5.3) for more information about its internal caching of counters.
For example:
snmpwalk -v2c -cpublic localhost 1.3.6.1.4.1.8072.1.5.3 | grep .1.3.6.1.2.1.2.2
NET-SNMP-AGENT-MIB::nsCacheTimeout.1.3.6.1.2.1.2.2 = INTEGER: 3
NET-SNMP-AGENT-MIB::nsCacheStatus.1.3.6.1.2.1.2.2 = INTEGER: cached(4)
Here, you can see that my particular box is caching IF-MIB::ifTable (.1.3.6.1.2.1.2.2), which is the table that you're using, every three seconds. In my case, I would not ask for data any more often than every three seconds. NET-SNMP-AGENT-MIB::nsCacheTimeout (.1.3.6.1.4.1.8072.1.5.3.1.2) is marked as read-write, so you might be able to issue an a "set" command to change the caching duration.
I have to do some php work for a student group I am part at in school. Clients make use of our provided services, and every ten requests (which are made online) they make of our service, they are required to do a check-in.
When we receive the request, we get all the info (id, special requests, notes, etc) from our database. I've added the form that indicates if a check-in is required no problem...no issues with the front end. It's just a matter of the backend that I'm unsure of due to my lack of experience in php and mysql.
Here is an example:
echo "<td>Half Size</td>";
echo "<td>". ($value["halfsize"] == 1 ? "Yes" : "No") . "<br/>";
echo "</td>";
echo "</tr><tr>";
If clients want half size for the request, they fill it out...when we receive it, we see whether that want a full size of half size.
Here is what I want to do with pseudocode, but since I'm lacking in SQL knowledge, I'm not sure what to do.
echo "<td>Check-in Required</td>";
**//Check count of rows (any table)
//If divisible by 10 (%10), return "Yes", else "No"**
echo "</td>";
echo "</tr><tr>";
What I need to figure out is how to check the number of rows, if that can be divisible by 10 then a check-in is required.
Hopefully that was clear enough and you understand what I'm asking, because reading it back it still sounds a bit hard to follow. I'll be happy to clarify if you have any questions. Thank you!
I'm not sure I completely get what you're doing, but I think what you need is the modulo operator (%).
if(count($rows) % 10 == 0){ // divisible by 10
}
else{ //not divisible by 10
}
PHP supports modulo which gets the remainder.
$divisor = 10;
$rowCount = 4; // put your method here that returns the number of rows
$result = $rowCount % $divisor == 0 ? "Yes" : "No";
PHP Modulo
You can alter the database table for clients, add one more column to store the count value.
Add: a column, say, counter --> integer to clients table.
Change your code to do:
Every time client makes a request, query select * from clients where id =
take out counter value and check if (counter%10 == 0).
if(counter%10 == 0)
{
request to check in;
}
accept request;
then update clients counter column (increment by 1)
Updating table will remember requests from previous sessions too. But if you want to check number of requests in only current session, then you just have to add a counter variable in your PHP code and check for %10 before every request.
This was just a pseudo-code. If its tenth request, you request check in, and then accept request and increment clients counter.
else you just accept request and increment counter.
(Sorry for writing just pseudo code, instead of actual code. But that is one way to do it. I may have misunderstood the question, but if this solves your problem, I'm happy.)
I'm trying to generate a unique "dosieid" number for my web site. My web site is a human resources program solution, in that program users create dosie of their workers in their firm ...random dosieid needs me so when user creating dosie in field dosieid automatically show the dosieid-s that are not used before...the dosieid that don't exist in database. In other case I would use auto increment but in this case dosie is not created yet. And in form dosieid must be option to change the number if random is not fine with a user. One more hint the numbers must bee from 1 to 9999. Can someone help me? I have try many codes but I have not find something like one with this spec.
This is what I have do so far. It gets the random number but I don't know how to compare that random number with database row "dosieid" ?
$id_num = mt_rand(1,9999);
$query = "SELECT dosjeid FROM albums";
$result = mysql_query($query) or die(mysql_error());
while($account = mysql_fetch_array($result)){
if ($id_num == $account['id']){
$id_num = mt_rand(1,9999);
}
}
echo"$id_num<br>";
This is extraordinarily convoluted... why is an auto-incrementing number not enough? This code would also never work properly. If for whatever reason you HAVE to use a random number, then you'd do it like this:
while(true) {
$id_rand = mt_rand(1,9999);
$result = mysql_query("SELECT count(*) FROM albums WHERE dosjeid=$id_rand") or die(mysql_error());
$row = mysql_fetch_row($result);
if ($row[0] == 0) {
break; // our random number isn't in the database, so exit the loop
}
}
However, here's some problems with this:
1) You'll get an infinite loop when you reach 9999 dosie records
2) The more records there are in the database, the longer this loop will take to find a "vacant" slot. As you get closer and closer to 9999 records, you'll be taking a LONG time to find that one empty slot
3) If you're trying to "cloak" the IDs of anyone member so that users can't simply increment an ID parameter somewhere to see other people's records, there's FAR FAR FAR better/easier ways of doing this, such as encrypting the ID value before sending it out to clients.
Use a auto-increment number as your primary key and an additional display id with the UNIQUE attribute as the ID shown to the user. This way you have a unique ID for your internal processing and a display ID that can be easily changed.
This is a terrible design. You should either:
not let users create the dosieid (create it yourself, give it to them after record created)
Try to create a stub record first with an assigned dosieid, and then update it with information
or use UUIDs, which requires a much bigger range than 1-9999
Even if you check that the number was unique, in between the time when you check it and the time you insert the record someone else may have taken it.
And under no circumstances should you find an empty id by picking numbers at random. This makes your program execution time non-deterministic, and if you eventually get 5000 employees you could be waiting a long time.
Also, This range is way too small for a randomness requirement.
You may also want to read about number only hashes (check upon the algorithm's collision rate) - php: number only hash?
function doesIdExists($id)
{
$query = "SELECT dosjeid FROM albums";
$result = mysql_query($query) or die(mysql_error());
while($account = mysql_fetch_array($result))
{
if ($id_num == $account['id'])
return true; /* The id is taken */
}
return false; /* Not taken */
}
$recNotAdded = true;
while($recNotAdded)
{
$rand = mt_rand(1,1000); //Whatever your numbers
$doesExist = doesIdExists($rand);
if(!$doesExist)
{
/* Add to DB */
$recNotAdded = false;
}
}
I have two msyql tables, Badges and Events. I use a join to find all the events and return the badge info for that event (title & description) using the following code:
SELECT COUNT(Badges.badge_ID) AS
badge_count,title,Badges.description
FROM Badges JOIN Events ON
Badges.badge_id=Events.badge_id GROUP
BY title ASC
In addition to the counts, I need to know the value of the event with the most entries. I thought I'd do this in php with the max() function, but I had trouble getting that to work correctly. So, I decided I could get the same result by modifying the above query by using "ORDER BY badgecount DESC LIMIT 1," which returns an array of a single element, whose value is the highest count total of all the events.
While this solution works well for me, I'm curious if it is taking more resources to make 2 calls to the server (b/c I'm now using two queries) instead of working it out in php. If I did do it in php, how could I get the max value of a particular item in an associative array (it would be nice to be able to return the key and the value, if possible)?
EDIT:
OK, it's amazing what a few hours of rest will do for the mind. I opened up my code this morning, and made a simple modification to the code, which worked out for me. I simply created a variable on the count field and, if the new one was greater than the old one, changed it to the new value (see the "if" statement in the following code):
if ( $c > $highestCount ) {
$highestCount = $c; }
This might again lead to a "religious war", but I would go with the two queries version. To me it is cleaner to have data handling in the database as much as possible. In the long run, query caching, etc.. would even out the overhead caused by the extra query.
Anyway, to get the max in PHP, you simply need to iterate over your $results array:
getMax($results) {
if (count($results) == 0) {
return NULL;
}
$max = reset($results);
for($results as $elem) {
if ($max < $elem) { // need to do specific comparison here
$max = $elem;
}
}
return $max;
}