Adding a value to all elements in an array (php) - php

I have a query to get an array from a database.
$result = mysqli_query($con,"SELECT `Time_D` from `Schedule` where `Stop` = 1 ");
while ($row = mysqli_fetch_array($result) ) {
echo $row['Time_D'] . "<br>";
}
This array ($row) contains a lot of times, if I'm not mistaken.
I now want to add for example 10 minutes to all the elements in the array.
How do I do that?

Well, figured it out myself after all.
$result = mysqli_query($con,"SELECT `Time_D` from `Schedule` where `Stop` = 1 ");
//get database result
while ($row = mysqli_fetch_array($result) ) {
$rows[] = $row['Time_D']; //store all the times in one array
}
print_r ($rows);
echo "<br>";
$time_difference=600;
$i=0;
while (($i) < (count($rows)) ) {
$rows[$i] = ( strtotime($rows[$i]) ) + ($time_difference); //with timestamps, because, well, php and times...
$rows[$i] = date('H:i:s', ($rows[$i]) ); // back from timestamp to time
$i = $i +1;
}
print_r($rows);

You need to update like this
$row['Time_D'] = time() + 600;
or just 10 seconds
$row['Time_D'] += 600;
Then push it back to the database
mysql_query('update table_name set Time_D = '{$row['Time_D']}' where id = '{$row['id']}'
OR something to that end.

You can do it in SQL only:
"UPDATE `Schedule` SET `Time_D` VALUES = DATE_ADD(`Schedule`.`Time_D`,INTERVAL 10 MINUTE) where `Stop` = 1"

You might be mistaken. $row does not contain a lot of times. As long as there are still records available, $row is assigned the next row of the query result as an array. If you want to alter all the times, save them to a new array. In your while-loop (don't forget to declare $rows):
$rows[] = $row['Time_D'];
$rows now stores all the times. You can then (after the while-loop) iterate over $rows and alter the data.
$rows = array_map(function($time) {
return $time + (60 * 10); // Given $time is a timestamp
}, $rows);
If you don't want to save the times (i.e. directly output them in the while-loop), save the overhead of array_map and do it directly in the while-loop:
echo $row['Time_D'] + 60*10;
Depending on your exact situation you might want to use a key-value (i.e. id-to-time) storage for the times - otherwise you won't be able to refer them back to the "schedule" you are using.
If you only want to update the database records see Axel's answer.

You can do it from the mysql query itself by using DATE_ADD.
"SELECT DATE_ADD(`Time_D`,INTERVAL 10 MINUTE) AS 'Time_D' FROM `Schedule` WHERE `Stop` = 1 "
You can have a parameter like this in your php script:
$minutes_to_add = 10;
$result = mysqli_query($con,"SELECT DATE_ADD(`Time_D`,INTERVAL ".$minutes_to_add." MINUTE) AS 'Time_D' FROM `Schedule` WHERE `Stop` = 1 ");
while ($row = mysqli_fetch_array($result) )
{
echo $row['Time_D'] . "<br>";
}

Related

How can i print how many Id's i have in my database in php

I don't understand why this isn't working and i don't know how to fix it:
$sum=0;
$queryone="SELECT SUM(ID) FROM seriestwo";
$result = mysqli_query($link,$queryone);
$row = mysqli_fetch_array($result, MYSQLI_NUM);
while($row = $result->fetch_assoc()){
$sum = $sum + 1;
}
echo $sum
it always prints 0.
What you are doing is wrong because the $result stores only 1 row, that is the sum of ID. You can try two things:
Method 1: Use COUNT() in mysqli. Check MySQL Reference
For eg. check: select count(*) from table of mysql in php
$queryone="SELECT COUNT(ID) as total FROM seriestwo";
$result = mysqli_query($link,$queryone);
$row = mysqli_fetch_assoc($result, MYSQLI_NUM);
echo $row['total'];
Method 2: Use this code:
$sum=0;
$queryone="SELECT `ID` FROM seriestwo";
$result = mysqli_query($link,$queryone);
$row = mysqli_fetch_array($result, MYSQLI_NUM);
while($row = $result->fetch_assoc()){
$sum = $sum + 1;
}
echo $sum;
Which Method to Use
The first method is the one you should be using right now, in this case. You can use second when you want to add extra things, like print every ID
You may be overthinking this.
It's as simple as the following and using an alias while using only 3 lines of code:
$query = $link->query("SELECT SUM(`ID`) as `total` FROM seriestwo");
$row = $query->fetch_assoc();
echo $row['total'];

PHP encode a partial set of MySQL data into JSON

I know how to encode all the data from an SQL query into JSON using PHP, but don't know How to encode a partial set.
In Android (the client), I send an HTTP request which goes something like this:
public interface DataAPI {
#GET("/top500")
public void getResult(#Query("start") int start, #Query("count") int count,
Callback<Top500> response);
}
As you can see, I am using start and count in Android code.
I have around 500 records in my table and I have successfully encoded all the data into JSON, using below PHP Script:
<?php
$con = mysqli_connect(HOST,USER,PASS,DB);
$sql = "select * from Persons";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array(
'id'=>$row[0],
'name'=>$row[1]
));
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
?>
JSON Result:
{"result": [{ ... }]}
But I need to encode mysql data 20 by 20 like this:
{"count": 20, "start": 0, "total": 500, "result": [{ ...}]}
What's missing is how to use the start and count parameters to get a partial set in order to get slices of the data.
You need to use LIMIT and OFFSET in your query. Applying some nasty logic in PHP is a bad solution. This is an operation that MySQL should do instead because you don't want to fetch all the rows if you don't need all of them.
If you run a query like this:
SELECT *
FROM Persons
ORDER BY Id
LIMIT 10 OFFSET 20
you will get a subset of the matching rows starting from the 20th and long 10 rows. You can then loop over the full results set.
Better to explicitly order by a field to ensure consistency across different pages.
You're final code (using PDO rather than mysqli):
$pdo = new PDO('mysql:dbname=db;host=127.0.0.1', $user, $password);
$count = $_GET['count'];
$start = $_GET['start'];
$stmt = $pdo->prepare('SELECT * FROM Persons ORDER BY Id LIMIT ? OFFSET ?');
$stmt->execute(array($count, $start));
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
// your logic that was inside the while
}
Use below code.
$con = mysqli_connect(HOST,USER,PASS,DB);
$count = "select count(*) as total from Person"; //query to get row count of your table
$count_res = mysqli_query($con,$count);
$count_row = mysqli_fetch_array($count_res);
$total = $count_row['total']; // get total no of records
$start = YOUR_START_VALUE; // from which offset you want to get record
$end = YOUR_VALUE // how many record want to fetch
$sql = "select * from Persons limit $start, $end";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array(
'id'=>$row[0],
'name'=>$row[1]
));
}
echo json_encode(array("count"=> $end, "start"=> $start, "total"=> $total,"result"=>$result));
mysqli_close($con);
?>
How about something like:
$start = 7;
$size = 3;
$count = 0;
while($row = mysqli_fetch_array($res)){
if($count>=$start && $count <$start+$size) {
array_push($result,array('id'=>$row[0],'name'=>$row[1]));
}
$count++;
}
The code should be self explanatory, but if you have any questions, feel free to comment.
Note: This is more of a PHP pseudo code, as I don't have an environment and haven't coded in PHP in a while.
I can think of 2 ways to solve this problem.
The first is using just MySQL:
SELECT SQL_CALC_FOUND_ROWS * FROM Persons LIMIT 0,20;
SELECT FOUND_ROWS();
With the first query you retrieve the batch of rows you want. With the second you get the total row count in the result set.
The second option is to use array_slice:
$total = count($result);
$batch = array_slice($result, 0, 20);
echo json_encode(array("total" => $total, "start" => 0, "count" => count($batch), "result"=>$batch));

strange mysql behaviour on timestamp

Please have a look at this mysql query. What it should do is pretty simple - list dates, created from timestamps not older than 10 days.
It works, but not perfectly ...
If I have only 1 timestamp matching, I have 0 results.
If I have 2 timestamps matching, I have 1 results.
if I have 3 timestamps matching, I have 2 results
... and so on...
So the newest timestamp in the table is always ignored by the query, WHY ?!
$timestamp_now = date('U');
$timestamp_10_day_back = $timestamp_now - 864000;
mysql_select_db("$db_visitors");
$sql = "SELECT DATE(FROM_UNIXTIME(visitors_timestamp))
FROM visitors
WHERE visitors_timestamp > $timestamp_10_day_back
ORDER BY visitors_timestamp DESC";
$sql = mysql_query($sql);
$row = mysql_fetch_array($sql);
while($row = mysql_fetch_array($sql)) {
echo $row[0] . "<br>";
}
Just remove
$row = mysql_fetch_array($sql);
...which is swallowing your first result
First row is being ignored because of the row $row = mysql_fetch_array($sql); then you call it again in your while loop . just remove this row .
try the code following
$n=count($row);
if($n>0){
for($i=0;$i<$n;$i++){
echo $row[i];}}
or
print_r($row);

Checking to see if a MySQL row is populated

I have a page that writes to a MySQL table. The table has a set amount of rows (24).
I have an $id variable that's set by a rand() function. I basically want to pull the row at that $id, so if $id was 3, I want to pull the third row. Then, I want to check if there is a price set at that row (indicating that the row is being used). If there is no price, I want to keep $id at the value it has been set at and proceed with the query. If there is a price, I want to re-randomize the $id variable, and check again if that row is used up. When it finds an empty row, proceed with the query.
My solution semi-works, but it seems to have a <10% chance of overwriting a used row, for some reason. I want it to never overwrite a used row.
Here's my code:
mysql_select_db("delives0_booklet", $con);
$query = "SELECT * FROM booklet WHERE id = '$id'";
$res = mysql_query($query,$con);
$newId = $id;
while($row = mysql_fetch_array($res))
{
if($row['price'] != 0)
{
do{
$newId = rand(1, 24);
}while($newId == $id);
}
}
$id = $newId;
mysql_query("UPDATE booklet SET price = '$price', advertiser = '$advertiser', image = '$image', monthsRemaining = '$monthsRemaining', availability = 1 WHERE id = '$id'");
Edit
I had the idea to do this. I loop through the table and I put the 'id' of each unfilled spot into an array. Then I pick randomly from that array. However, there seems to be a bug that I can't find, since the array keeps showing as having nothing in it, even after the loop is run, and $i is the correct figure.
mysql_select_db("delives0_booklet", $con);
$query = "SELECT * FROM booklet";
$res = mysql_query($query,$con);
$i = 0;
$isEmpty = array();
while($row = mysql_fetch_array($res))
{
if($row['price'] == 0)
{
$isEmpty[i] = $row['id'];
$i = $i + 1;
}
}
echo $i . " unfilled spots.";
$n = 0;
while($n<$i)
{
echo $isEmpty[$n];
$n = $n + 1;
}
if($i > 0)
{
$id = $isEmpty[rand(0, $i)];
}
if($i == 0)
{
echo 'All spots have been filled.';
}
I think it is a top level logic problem. Because you populate with random ids, you can get duplicate ids, and so when you update "WHERE id = '$id'" you may be picking up rows already populated.
I don't know your goal, but perhaps using an auto-increment id, and dropping rows that you want to get rid of, is the way to go. A rolling set of rows (24 at a time) but with ever increasing ids, would prevent mistaking one for the other.
If I understand the problem correct, this should work:
SELECT *
FROM booklet
WHERE price = 0 OR price IS NULL
ORDER BY RAND()

How to display five rows?

How can I use PHP to show five rows from a MySQL database, then create a new line and show another five, etc?
Use the LIMIT clause if you want to limit the amount of results returned from the query.
If you want to print an <hr/> after every fifth record you can check it via the modulus operator:
$counter = 1;
while ($row = mysql_fetch_assoc($rst)) {
// print $row stuff
if ($counter % 5 == 0)
print "<hr />";
$counter++;
}
Basically, we have a variable used to count how many records we've printed. Once that counter can be divided by five, and leave no remainder, we print our horizontal-rule.
Something like this may be helpful:
$result = mysql_query($query);
if($result) {
while($row = mysql_fetch_assoc($result)) {
if(++$i%5==0 && $i>0) {
/* do the extra thing... new line some styles */
}
}
}
Err.. you mean something like:
SELECT * FROM `tablename` WHERE ... LIMIT 5
$total = 20;//get total number here;
$limit = 5;
for($i = 0;$i< $total/$limit;$i++)
{
$sql = $result = $rows = "";
$start = $limit * $i;
$sql = "select * from m_table order by id desc limit $start,$limit";
$result = mysql_query($query);
while($rows = mysql_fetch_assoc($result))
{
//print the result here;
}
}
You can fetch 5 rows every time from mysql without fetching all the rows at once.

Categories