Date comparison inside a "for loop" in php - php

I have a set of rows with five fields. My requirement is if "Internal_Deadline" field is greater than "Client_Deadline" in any of the rows, then it has to display a alert saying "Internal Deadline should not be greater than Client Deadline". Now it's checking only with the first row. I need to check with all the rows. Thanks
<?php
for( $i = 1; $i <= 100; $i++ )
{
$task = $_POST['task'.$i];
$Description = $_POST['Description'.$i];
$Internal_Deadline = $_POST['Internal_Deadline'.$i];
$Client_Deadline = $_POST['Client_Deadline'.$i];
$Actual_Deadline = $_POST['Actual_Deadline'.$i];
if(strtotime($Internal_Deadline) > strtotime($Client_Deadline)){
?>
<script>alert('Internal Deadline should not be greater than Client Deadline');</script>
<?php
}
else{
$result_task=mysql_query("select * from project_plan where p_id='$p_id' and task_no='$i'", $dbconnect1);
$row_task=mysql_fetch_array($result_task);
$id=$row_task['id'];
if(mysql_num_rows($result_task)!=0){
$update_result=mysql_query("update project_plan set Task='$task',Description='$Description',Internal_Deadline='$Internal_Deadline',Client_Deadline='$Client_Deadline',Actual_Deadline='$Actual_Deadline' where id='$id'", $dbconnect1);
}
else{
if($task!=""){
$que = mysql_query("insert INTO project_plan(task_no,Task,Description,Internal_Deadline,Client_Deadline,Actual_Deadline,Created_Date,p_id) VALUES ('".$i."','".$task."','".$Description."','".$Internal_Deadline."','".$Client_Deadline."','".$Actual_Deadline."','".$current_date."','".$p_id."')", $dbconnect1);
}
}
}
}

First of all the length of your for loop is not correct.
You need to run this loop exact same times to the post data count.
secondly i have tried locally with your given data(in your comment). it seems that is not met the condition:
if(strtotime($Internal_Deadline) > strtotime($Client_Deadline)){
try like this:
it will skip unnecessary loops. if you have task1,task2,task3 set in post data then it will run for 3 times not 100 times as your implementation.
$i=1;
while(isset($_POST['task'.$i]))
{
$task = $_POST['task'.$i];
$Description = $_POST['Description'.$i];
$Internal_Deadline = $_POST['Internal_Deadline'.$i];
$Client_Deadline = $_POST['Client_Deadline'.$i];
$Actual_Deadline = $_POST['Actual_Deadline'.$i];
if(strtotime($Internal_Deadline) > strtotime($Client_Deadline)){
?>
<script>alert('Internal Deadline should not be greater than Client Deadline');</script>
<?php
}
else{
$result_task=mysql_query("select * from project_plan where p_id='$p_id' and task_no='$i'", $dbconnect1);
$row_task=mysql_fetch_array($result_task);
$id=$row_task['id'];
if(mysql_num_rows($result_task)!=0){
$update_result=mysql_query("update project_plan set Task='$task',Description='$Description',Internal_Deadline='$Internal_Deadline',Client_Deadline='$Client_Deadline',Actual_Deadline='$Actual_Deadline' where id='$id'", $dbconnect1);
}
else{
if($task!=""){
$que = mysql_query("insert INTO project_plan(task_no,Task,Description,Internal_Deadline,Client_Deadline,Actual_Deadline,Created_Date,p_id) VALUES ('".$i."','".$task."','".$Description."','".$Internal_Deadline."','".$Client_Deadline."','".$Actual_Deadline."','".$current_date."','".$p_id."')", $dbconnect1);
}
}
}
$i =$i +1;
}

Related

If rowCount empty, try again

I am running a query from a table whose data gets refreshed (deleted and re-inserted) every 30 seconds.
I want my query (which outputs row count) to detect that the row count is null (or zero) and re-run the query. Maximum retries: 5.
And after 5th retries, if it's still zero, I want the row count to print "0".
I know it's a loop but I don't know how to loop it from within the if for row.
<?php
$con=mysqli_connect("HOST","USERNAME","PASS","TABLENAME");
$sql="SELECT id FROM candyshop WHERE candy <= 5 AND sugartype ='hard'";
$number = 0; //init count for loop
if ($result=mysqli_query($con,$sql))
{
$rowcount=mysqli_num_rows($result);
printf($rowcount); //print number of rows
mysqli_free_result($result);
$number = $number+1; //increment number for loop
}
mysqli_close($con);
?>
Use a do while loop and only leave the loop if the rowcount is higher than 0 or 5 retries have been reached.
<?php
$sql = "SELECT id FROM candyshop WHERE candy <= 5 AND sugartype ='hard'";
$count = 0;
$retry = 5;
do {
// Count the rows
if ($result = mysqli_query($con, $sql)) {
$count = mysqli_num_rows($result);
}
// Wait for 10ms
if ($count === 0) {
usleep(10000)
}
} while ($count === 0 && --$retry > 0);
mysqli_close($con);
This is however very bad practice, I would recommend looking for another approach. Why would you clear and then refill the table?
Still new to StackOverflow but can you try this?
<?php
$con=mysqli_connect("HOST","USERNAME","PASS","TABLENAME");
$sql="SELECT id FROM candyshop WHERE candy <= 5 AND sugartype ='hard'";
$number = 0; //init count for loop
if ($result=mysqli_query($con,$sql)) {
$rowcount=mysqli_num_rows($result);
printf($rowcount); //print number of rows
mysqli_free_result($result);
$number = $number+1; //increment number for loop
if ($number = 5) {
printf(0);
break 2;
}
}
mysqli_close($con);
?>
$i = 0;
do {
$result = mysqli_query($con, $sql);
$count = mysqli_num_rows($result);
} while ($count == 0 && $i++ < 5)
As i understood you are trying to write a Web Based Game. Actually your method is probably going to make database a little busy. You don't have to loop queries. If you are going to do it, we are talking about milliseconds here. Let's say your queries are generally giving results in 0.05 seconds that means for 5 query you are just going to have the data of 0.25 seconds.
You can write your game or whatever easily with COMET Programming. But if you decided to go with loop queries , there is only one thing you will do and it's for loop.
$rowcount=0;
do {
if ($result=mysqli_query($con,$sql)) {
$rowcount=mysqli_num_rows($result);
printf($rowcount); //print number of rows
mysqli_free_result($result);
}
} while(++$number<5 && $rowcount!=0);
that is basicaly the answer to your request, though it needs some more explanation to be useful.

PHP Recursion -- Increment query variables

I have a database where each row contains a unique userid number, and a referralid number that links them to the person that referred them to the site. I am trying to create a recursive function that will search the database as long as it continues to find users, and perform several calculations as it goes. Below is what I have so far - I am getting stuck on trying to create incrementing query variables - PLEASE HELP!
function findrepsloop($refidnum, $num){
echo "FINDREPSLOOP STARTED<br><br>";
if(strlen($refidnum) > 0){
echo "FIRST STRLEN IF LOOP PASSED: $refidnum<br><br>";
$totalreps++;
$query{$num} = "SELECT * FROM user WHERE (refidnum = '$refidnum' && active = 'YES') ";
$result{$num} = mysql_query($query{$num});
$line{$num} = mysql_fetch_array($result{$num}, MYSQL_NUM);
$total{$num} = mysql_num_rows($result{$num});
echo "QUERY $num found $total{$num} rows in the database. LINE 0: '$line{$num}[0]<br><br>";
$totaltemp = 0;
if($total{$num} > 2){ $totaltemp = $total{$num} / 3; $totaltemp = floor($totaltemp); }else{}
$numberofthrees = $numberofthrees + $totaltemp;
while(strlen($line{$num}[0]) > 0){
$refidnum = $line{$num}[0];
$num++;
findrepsloop($refidnum, $num);
$line{$num} = mysql_fetch_array($result{$num}, MYSQL_NUM);
}
}else{
}
}

Two elements but only one inserted into database (even in a loop)

for ($i = 0; $i < count($cart); $i++) {
$proid = $cart[$i]["proid"]; //1
$prodName = $cart[$i]["prod_name"]; //2
$price = $cart[$i]["unit_price"]; //3
$taken = $cart[$i]["taken"]; //4
if ($cart[$i]['taken'] > 0) {
$sql = "INSERT INTO `tblchitiethoadon`(`Ma_HD`, `Ma_SP`, `Ten_SP`, `SoLuong`, `Gia`)";
$sql.=" VALUES ({$mahd},{$proid},'{$prodName}',{$taken},{$price})";
$result = mysql_query($sql);
/* $mahd i got it before */
}
}
I got 3 elements in array $cart,2 of them got cart[$i]['taken'] > 0 (i also echo $cart with $cart[$i]['taken'] > 0 condition for sure ) but in the database i just got the first and only one element.
Typo/Syntax Error
$sql.=" VALUES ({$mahd},{$proid},'{$prodName}',{$taken},{$price})";
----------------------------------------------------------------------------------------------------------^(semicolon missing)
correct:
$sql.=" VALUES ({$mahd},{$proid},'{$prodName}',{$taken},{$price});";
-----------------------------------------------------------------------------------------------------------^
Reason:
Since you are using for loop to form the query.your query will look like
insert into table1(a,b,c) values(1,1,1)insert into table1(a,b,c) values(2,3,4)
which is wrong syntactically.
see here
you can echo your $sql and run it in phpmyadmin
Better Approach:
The better approach to your code(it will reduce the unwanted overhead,form the string inside the loop and execute it outside the loop):
$sql1 = "INSERT INTO `tblchitiethoadon`
(`Ma_HD`, `Ma_SP`, `Ten_SP`, `SoLuong`, `Gia`) VALUES";
for ($i = 0; $i < count($cart); $i++) {
$proid = $cart[$i]["proid"]; //1
$prodName = $cart[$i]["prod_name"]; //2
$price = $cart[$i]["unit_price"]; //3
$taken = $cart[$i]["taken"]; //4
if ($cart[$i]['taken'] > 0) {
$sql11.=" ({$mahd},{$proid},'{$prodName}',{$taken},{$price}),";
}
}
$sql=$sql1.$sql11;
$sql=trim($sql,",");//to remove the extra semicolon at the end of the string.
$result = mysql_query($sql);
Please Dont use mysql_* as these are depracated and you are prone to sql injections.
Loop will execute count($cart) times and the insertion action will occure if ($cart[$i]['taken'] > 0) is true.Make sure the condition is true for each time.
Try these this coding:
$sql = "INSERT INTO tblchitiethoadon (Ma_HD, Ma_SP, Ten_SP, SoLuong, Gia) VALUES ('$mahd','$proid','$prodName','$taken','$price')";
$result = mysql_query($sql);

adding further conditions to mysql loop

<?php
$query = $_GET['query'];
// gets value sent over search form
$min_length = 6;
// you can set minimum length of the query if you want
if(strlen($query) >= $min_length){ // if query length is more or equal minimum length then
$query = htmlspecialchars($query);
// changes characters used in html to their equivalents, for example: < to >
$query = mysql_real_escape_string($query);
// makes sure nobody uses SQL injection
$raw_results = mysql_query("SELECT * FROM cwnational WHERE (`postcode` = '$query') OR (`structure` LIKE '%".$query."%')") or die(mysql_error());
if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following
while($results = mysql_fetch_array($raw_results)){
echo "<p><h3>".$results['postcode']."</h3>".$results['structure']."</p>";
}
while($results = mysql_fetch_array($raw_results)){
if($results['structure'] = "National") {
echo "print national_table";
} else {
echo "print local_table";
}
}
else{ // if there is no matching rows do following
echo "No results";
}
}
else{ // if query length is less than minimum
echo "Minimum length is ".$min_length;
}
?>
</body>
I'm totally stumped now..
When I successfully match a $query, I want to use the 2nd part of the array which should be a column called structure and use that as a switch to either print table_local or table_national from the db.
re-wrote it after getting to grips with the correct approach,
if (empty($searchTerm)) {
echo "<h1>Empty search term</h1>";
$sqlQuery = false;
} elseif (strlen($searchTerm) < $minQueryLength) {
echo "<h1>Search term must be at least ".$minQueryLength." characters long.";
$sqlQuery = false;
} else {
if (strlen($firstPart) + strlen($secondPart) == 7) {
$sqlQuery = $mysqli->query("SELECT `postcode`, `structure` FROM `cwnational` WHERE `postcode` LIKE '".$firstPart." ".$secondPart."'");
} else {
$sqlQuery = $mysqli->query("SELECT `postcode`, `structure` FROM `cwnational` WHERE REPLACE(`postcode`, ' ', '') LIKE '".$searchTerm."%'");
}
}
if (is_object($sqlQuery) && $sqlQuery->num_rows >= 1) {
$resultArr = array();
while($row = $sqlQuery->fetch_assoc()) {
$resultArr[$row['postcode']] = array();
$priceQuery = $mysqli->query("SELECT `base_rate`, `commit_mbps` FROM `pricing` WHERE `structure` = '".$row['structure']."'");
if ($priceQuery->num_rows >= 1) {
while ($price = $priceQuery->fetch_assoc()) {
$resultArr[$row['postcode']][$price['commit_mbps']] = ((float)$price['base_rate'] + $transit[$price['commit_mbps']] ) + ( ( $transit[$price['commit_mbps']] + (float)$price['base_rate'] ) * ((float)$apiUser['margin']/100) ) ;
}
}
}
You're reading the result set twice. This will work for the first loop, but won't execute the second because you've already reached the end. If you need to read the results twice, use this:
mysql_data_seek ($raw_results , 0 )
immediately before the second loop to set the pointer to the beginning again.
Of course, you should be using mysqli...
what's going wrong now? I see you need to add an equals sign here:
if($results['structure'] == "National") {
note: double equals for php conditional
It also looks like you have an "else" coming out of a "while", that won't work. And you did this "while" loop twice, I'd combine them into a single "While":
while($results = mysql_fetch_array($raw_results)){

Pagenav. By clicking next get next lets say "20" records (php/mysql)

I've already created a query to mysql that will give 20 results from mysql table etc. "cat"
heres the calling:
if(isset($_GET['cat']))
{
$query = "SELECT game_title,game_desc,....
FROM games WHERE cat_id='".validate_input($_GET['cat'])."' LIMIT 20";
}
...
by this I manage to get the results I wanted. What I am asking here is how can I create a "button" that will load the next "20" records from table "cat" (something like Buttons).
<?
$cn=mysql_connect("localhost","root","root") or die(mysql_error());
mysql_select_db("db56") or die(mysql_error());
$sql="select count(*) from emp";
$result=mysql_query($sql);
$r=mysql_fetch_row($result);
$record=$r[0];
$pagesize=20;
$totalpages=$record/$pagesize;
$currpage=$_GET["pg"];
if(!isset($currpage))
$start=0;
else {
$currpage--;
$start= $currpage * $pagesize;
}
$end=$start+$pagesize;
$sql="select * from emp limit $start,$pagesize";
$result=mysql_query($sql);
if($result){
print "<table border='1'>";
print "<tr><th>No</th><th>Name</th><th>Date</th></tr>";
while($r=mysql_fetch_row($result))
{
print "<tr><td>$r[0]</td><td>$r[1]</td><td>$r[2]</td></tr>";
}
print "</table>";
}
for($i=1;$i<=$totalpages;$i++){
print "<a href='listemp.php?pg=$i'> $i </a>";
}
?>
If you keep track of what page you're on, in the URL or a hidden field or session variable, you can use that to work out the limit. For example, page 2 should show limit 20 from row 20 (20 times the page offset).
You can pass two SQL parameters to LIMIT (put a comma between them) If you do, the first tells SQL how many records to skip (ie the offset of the first record) and the 2nd parameter is the one you're already using (how many records to return).
So just put a variable in your "next" link that says what page to display. You can pass the offset in this link, but it's pretty common to pass the "page number" instead, and multiply by the number of records per page before sticking it in the sql.
next page
With a bit more work, you can make a "previous page" link, and make the correct links non-clickable when you're at the first/last page.
Pass along a parameter that tells the script that you want another chunk of the results and not just the first batch.
So for the link it could be like this:
example.com/results.php?cat=1&page=2
Where page= will tell the script what page you want to return.
Then you want to turn that LIMIT number you have so that you can work out some simple maths
$results_cnt = 20; //--rows you want per page of results
Now in your script you'll check to see if the page variable has been set. If not, default the start row to return from the first. But as you want to return different pages/sets of results, a little math is needed in order to start at the proper row.
if(isset($_GET["page"]) //--see if the variable is even there
{
$page_num = (int)$_GET["page"]; //--forcing it to always be an integer
$start_row = $results_cnt * ($page_num - 1);
/* --
what happens:
($results_cnt currently at 20)
on page one (page=1), start at row 0
math: 20 * (1 - 1) = 0
on page two (page=2), start at row 20
math: 20 * (2 - 1) = 20
on page three (page=3), start at row 40
math: 20 * (3 - 1) = 40
etc.
*/
}
else
$start_row = 0;
Now, having set the correct starting row, adjust the SQL query to use the variables like so:
if(isset($_GET['cat']))
{
$query = "SELECT game_title,game_desc,....
FROM games
WHERE cat_id='".validate_input($_GET['cat'])."'
LIMIT $start_row, $results_cnt";
}
OK I got it fixed I guess...
in index.php:
<?php
$games = array();
$count = 1;
$total = 0;
if(isset($_GET['cat']))
{
$query = "SELECT game_title,game_desc,.... FROM games WHERE cat_id='".validate_input($_GET['cat'])."' LIMIT 20";
$total = mysql_num_rows(mysql_query("SELECT 1 FROM games WHERE cat_id='".validate_input($_GET['cat'])."'"));
}
$query_result = #mysql_query ($query) OR error(mysql_error(), __LINE__, __FILE__, 0, '', '');
while ($info = #mysql_fetch_array($query_result))
{
/* -- here goes the infos.. */
$games[$info['game_title']]['game_title'] = $info['game_title'];
etc..
if(isset($_GET['cat']))
{
/* -- for template engine */
$page->SetLoop ('PAGES', pagenav($total,$_GET['page'],20,$config['site_url'].'?cat='.$_GET['cat'],1,$lang));
}
--end php
and in funct.php
--start php
function pagenav($total,$page,$perpage,$url,$posts=0)
{
$page_arr = array();
$arr_count = 0;
if($posts)
{
$symb='&';
}
else
{
$symb='?';
}
$total_pages = ceil($total/$perpage);
$llimit = 1;
$rlimit = $total_pages;
$window = 5;
$html = '';
if ($page<1 || !$page)
{
$page=1;
}
if(($page - floor($window/5)) <= 0)
{
$llimit = 1;
if($window > $total_pages)
{
$rlimit = $total_pages;
}
else
{
$rlimit = $window;
}
}
else
{
if(($page + floor($window/2)) > $total_pages)
{
if ($total_pages - $window < 0)
{
$llimit = 1;
}
else
{
$llimit = $total_pages - $window + 1;
}
$rlimit = $total_pages;
}
else
{
$llimit = $page - floor($window/2);
$rlimit = $page + floor($window/2);
}
}
if ($page>1)
{
$page_arr[$arr_count]['title'] = 'Prev';
$page_arr[$arr_count]['link'] = $url.$symb.'page='.($page-1);
$page_arr[$arr_count]['current'] = 0;
$arr_count++;
}
for ($x=$llimit;$x <= $rlimit;$x++)
{
if ($x <> $page)
{
$page_arr[$arr_count]['title'] = $x;
$page_arr[$arr_count]['link'] = $url.$symb.'page='.($x);
$page_arr[$arr_count]['current'] = 0;
}
else
{
$page_arr[$arr_count]['title'] = $x;
$page_arr[$arr_count]['link'] = $url.$symb.'page='.($x);
$page_arr[$arr_count]['current'] = 1;
}
$arr_count++;
}
if($page < $total_pages)
{
$page_arr[$arr_count]['title'] = 'Next';
$page_arr[$arr_count]['link'] = $url.$symb.'page='.($page+1);
$page_arr[$arr_count]['current'] = 0;
$arr_count++;
}
return $page_arr;
}
?>
and call it by
{LOOP: PAGES}{PAGES.title} {/LOOP: PAGES}
in an .html file..
it works perfectly but when I press the number 2 or next to get the next 20 records it jumps back to the first 20...
on the browser it reads http://siteurl/?cat=1&page=2
I can't figure out why.

Categories