While looping sql query - php

I am trying to update all of the rows in a table in my database with a different value. I am trying to while loop the query to do this. Here's what I have...
<?php
$rand = rand(100,150000);
$start = 1;
$start += $start;
$start2 = $start +1;
echo $start;
while($start =< 686) {
echo "UPDATE table_video SET total_view = $rand WHERE id BETWEEN $start AND $start2;";
};
?>
I am sure most of you should be able to look at my code and understand what I am trying to accomplish. I would like the assistance. Thank You very much!

Use the mySQL RAND() function, min and max your range for the random values. I belive on this case are (100,150000)
UPDATE table_video
SET total_view = ROUND( (RAND() * (max-min)) +min )
WHERE id BETWEEN 1 AND 686;

Related

I am calling the sql statement with a php loop and I want to change it to be called only once

I am a novice developer running a server.
Recently, I am running a server using php and mysql.
However, the server keeps hitting and checking, and mysql is eating all the cpu.
I think it is a problem to put the sql query in the loop statement because of poor skill.
I looked around, but it couldn't be solved, but I saw a post that told me to solve it with a join statement rather than repeatedly calling the sql statement.
If you think about it, it is definitely a problem by repeatedly calling the sql statement, so I think it will improve if it can be processed as a single query.
But I don't know how to change it right now...
I am using a code similar to the one below, not the code that is actually used. Please help me on how to change this.
It's a little embarrassing to use this code...
I want to print the sum.
I have 24 hours worth of data.
This code takes the number of records in 1 minute and adds up the value divided by 100.
$sum = 0;
for ($i = 0; $i < 1440; $i++){
$time1 = date("Y/m/d H:i",(strtotime($basetime) - 72000 + ($i * 60))).":00";
$time2 = date("Y/m/d H:i",(strtotime($basetime) - 60 + ($i * 60))).":59";
$sql = "select count(*) as cnt from mytable where start_time between '$time1' and '$time2'";
$query_result = mysqli_query($sql);
$sum += 100 / $query_result['cnt']);
}
echo $sum;
$sql = "select count(*) as cnt from mining where start_time between '$time1' and '$time2'";
$query_result = sql_fetch($sql);
$sum = 0;
for ($i = 0; $i < 1440; $i++){
$time1 = date("Y/m/d H:i",(strtotime($basetime) - 72000 + ($i * 60))).":00";
$time2 = date("Y/m/d H:i",(strtotime($basetime) - 60 + ($i * 60))).":59";
$sum += $query_result['cnt']);
}

How to dynamically add and get total of time from database?

I'm trying to get the total time duration of all time variables from the database. But I don't seem to get the right total or result. This is my code...
$len = count($mids);
foreach($mids as $key => $val)
{
$result=mysql_query("SELECT * FROM tbltempmovies WHERE mid='".$val."'");
while($row=mysql_fetch_array($result))
{
$dur += strtotime($row['duration']);
}
}
$duration = date('g:i:s', $dur);
PS: I know I'm not using mysqli or PDO. I'll fix that once I'm done with this.
try this
$duration = date('g:i:s', strtotime($dur));

How to make php generate random numbers untill the specific number is reached

I want a random integer to be generated in the range from 1 to 3 until 2 will be generated.
Please review the code below - What am I doing wrong?
Thank you!
<?php
$min = 1;
$max = 3;
$number = rand($min,$max);
while($number !== 2) {
echo ($number);
}
?>
your rand() is not in the while loop, so the rand() will execute one time.
If the $number is not 2, the while loop will execute without stoping.
If the $number is 2, the while loop will not executed.
while(($number = rand($min, $max)) != 2){echo $number;}

How to limit MySQL query result to specific results?

I have a news table in MySQL Database I query the table and show the title of the news in one PHP pages but now the table getting bigger so I want to divide the results into pages I mean to show each 50 news title in one page (pagenation).
I use this query to bring the news :
SELECT news.*, categories.category, users.username
FROM news INNER JOIN
users on news.user_id = users.id INNER JOIN
categories on categories.id = news.category_id
order by news.timestamp DESC
limit $min,$max
and this is part of the PHP page (How I calculate the max and min)
$news_per_page = 50;
if(!empty($_GET['p_n']))
{
$p_n = $_GET['p_n'];
$max = $news_per_page*$p_n;
$min = ($max - $news_per_page);
}
else
{
$p_n = 1;
$max = 50;
$min = 0;
}
$news = all_news($max,$min);
The sql giving me wrong result when i pass the limits I do not know why. Is it wrong to specify the max and min of sql query by this way?? Should I correct something in this code?
The LIMIT clause, as explained in the docs, takes arguments offset and count. So if you want to get, for example, results from 201 to 250, you would use LIMIT 200, 50. Start by renaming your variables $min and $max to $offset and $count, and from there everything will fall into place.
Pseudocode:
offset = (requestedPageNumber - 1) * rowsPerPage;
count = rowsPerPage;
PHP Code:
(assuming page number is 0-based)
$rowsPerPage = 50;
$page = empty($_GET['p_n']) ? 0 : $_GET['p_n'];
$offset = $rowsPerPage * (int) $page;
$news = all_news($offset, $rowsPerPage);
If you've got problems handling pagination properly, I suggest you use some code that is working, for example a pagination class that takes three parameters:
The current page.
The total count.
The number of items per page.
And then that class will generate the LIMIT clause for you. Example:
$pageNumber = 1;
$totalCount = 17;
$perPage = 5;
$pagination = new LimitPagination($pageNumber, $totalCount, $perPage);
echo $pagination, "\n";
This would output
LIMIT 0, 5
because you'er on the first page. Such a class then could also filter out those problems you have here, for example setting to a negative page - just automatically. And also it can provide a lot of extra data, like the next and previous page, the current page, the number of total pages, if it is the first or the last page and what not:
$pagination->setPage(-2);
echo $pagination, "\n";
echo "Current: ", $pagination->getPage(),
"; Total: ", $pagination->getTotalPages(),
"; Previous: ", $pagination->getPreviousPage(),
"; Next: ", $pagination->getNextPage(),
"\n";
Output:
LIMIT 0, 5
Current: 1; Total: 4; Previous: 1; Next: 2
This is then easy to integrate with different code, including yours:
$pagination = new LimitPagination($_GET['p_n'], $totalCount, 50);
$limit = sprintf("%d, %d", $pagination->getOffset(), $pagination->getCount());
This should easily do it. Class is here as Gist: https://gist.github.com/4469154
You need to set start (this you can achieve by using current page and per page property) and the second information is how many results you want (again per page property).
LIMIT . ($p_n - 1) * $news_per_page .', ' . $news_per_page
So, in your script it will be:
if(!empty($_GET['p_n']))
{
// You need to protect your variables for SQL injection. For numbers (int) or integer() function it is enough.
$p_n = (int) $_GET['p_n'];
$max = (int) $news_per_page;
$min = (int) ($p_n - 1) * $news_per_page;
}
else
{
$p_n = 1;
$max = 50;
$min = 0;
}
The correct code is:
$news_per_page = 50;
if(!empty($_GET['p_n']))
{
$p_n = intval($_GET['p_n']);
$min = ($p_n-1) * $news_per_page;
$max = $news_per_page;
}
else
{
$p_n = 1;
$max = 50;
$min = 0;
}
$news = all_news($max,$min);
While $_GET['p_n'] is page_number you dont' need to make any multiplies

how to create pagination in php with random records but with maintaing previous state

I have create a pagination in php and MySQL which works fine but shows same records every time I refresh the page.
the problem I am facing is how to show new records every time I refresh the page and even maintain the flow.for example if I am on first page its show random records every time.. and when I click in second page and come back to first page..it shows totally different records.
How to solve this.
$selectQ = "select * from primaryinfo order by rand(3)";
$result = mysql_query($selectQ);
$total_results = mysql_num_rows($result);
$total_pages = ceil($total_results / $per_page);
$start;
$end;
if (isset($_POST['pagecc']))
{
$show_page = $_POST['pagecc'];
if ($show_page > 0 && $show_page <= $total_pages)
{
$start = ($show_page - 1) * $per_page;
$end = $start + $per_page;
} else
{
$start = 0;
$end = $per_page;
}
}
else
{
$start = 0;
$end = $per_page;
}
if($end > $total_results)
$end = $total_results;
///$totlaRecords = mysql_num_rows($result) or die(mysql_error());
for($i=$start;$i<$end;$i++){
//displaying here...
}
this is how I did pagination...hope this could help..
thank in advance.
Seed RAND(N):
If a constant integer argument N is specified, it is used as the seed value, which produces a repeatable sequence of column values. In the following example, note that the sequences of values produced by RAND(3) is the same both places where it occurs.
SELECT ... ORDER BY RAND(CONSTANT_INT_VALUE);
Demo
CONSTANT_INT_VALUE should be a constant integer value maintened across requests.
Of the top of my head, you could use the decimal representation of the client IP address for instance.
Try using this.. Form what i understand.
consider no of records on a single page must be 'x'. So,
mysql_query("select * from primaryinfo LIMIT 0,x");
For second page
mysql_query("select * from primaryinfo LIMIT x,2x");
So this would show the next records and when you return to first page they would not repeat.
Try in your sql add ORDER BY RAND()

Categories