I would like to optimize the script a little and save cpu some work, so I have to create for loop. In this loop I will work with some data from database and below is my current code:
$result = $this->Model->function();
for ($i = 0; $i < $result->num_rows(); $i++)
{
echo $result->row_array($i)['row'];
}
What do I need here is to check if the next row exists. This one would be on the top of all code in for loop in if statement, but there is some problem. If I type $result->num_rows()+1 in for loop and echo the last row (which doesn't exist) out, the value of it isn't null, but it's same as row before.
How do I check if current row is null?
Or rather than have the boolean checked every time, plus you don't call the num_rows method a second time:
$result = $this->Model->function();
$y = $result->num_rows();
for ($i = 0; $i < $y-1; $i++)
{
echo $result->row_array($i)['row'];
}
echo 'last row';
echo $result->row_array($y-1)['row'];
You can do this for example:
$result = $this->Model->function();
$y = $result->num_rows();
$y--;
for ($i = 0; $i < $result->num_rows(); $i++)
{
if ($i == $y)(
echo 'last row';
)
echo $result->row_array($i)['row'];
}
Related
I want to update my MySQL table. When I type the ID as a number works, but when using a variable instead, it does not work.
What I am trying to do is order elements of an html table by column.
I have e.g. 4 Columns:
$colname = array("Column1", "Column2", "Column3", "Column4");
I get the IDs of the elements already sorted from the URL variable:
$strTaskIds = $_GET["taskIds"];
// for example: $strTaskIds = "3;1;32_4;5_6;36_34;7"
Now I split the string into a 2D-Array and update the MySQL table:
$arrTaskIds = explode("_", $strTaskIds);
for($i = 0; $i < count($arrTaskIds); $i++) {
$arrIdsPerCol = explode(";", $arrTaskIds[$i]);
for($j = 0; $j < count($arrIdsPerCol); $j++) {
$sql = "UPDATE tasks SET col='$colname[$i]', rank=$j WHERE id=$arrIdsPerCol[$j]";
}
if($conW->query($sql) === TRUE) {
$error = 0;
} else {
$error = 1;
}
}
When I write a number E.G 7 instead of the variable $arrIdsPerCol[$j] it works.
Writing (int)$arrIdsPerCol[$j] does not work either.
The reason i gave you no error message is that there was none. It just looked like the MySQL table is not updating.
After starring at my code for quite a long time a found the problem.
I placed the query() code in the outer loop. But i needed it in the inner loop.
Problem solved:
$arrTaskIds = explode("_", $strTaskIds);
$error = 0;
for($i = 0; $i < count($arrTaskIds); $i++) {
$arrIdsPerCol = explode(";", $arrTaskIds[$i]);
for($j = 0; $j < count($arrIdsPerCol); $j++) {
$sql = "UPDATE tasks SET col='$colname[$i]', rank=$j WHERE id=$arrIdsPerCol[$j]";
if($conW->query($sql) === TRUE) {
} else {
$error = 1;
}
}
}
I want to create a loop in php which start again from 1 after reaching a specific number assigned in variable.
Loop has to run 10 time
But after reaching 5 as i++ i want this loop to start again from 1 something as given below.
1,2,3,4,5,1,2,3,4,5
Please help!!
You might want to use the modulo operator, %. This will cause numbers to "cycle" like what you want.
for ($i = 0; $i < 10; $i++) {
echo ($i % 5) + 1;
}
The above will print out the numbers 1 through 5 twice.
Try -
$count = 0;
for ($i = 1 ; $i <= 10; $i++) {
$count++;
echo $count;
if ($count == 5) {
$count = 0;
echo "</br>";
}
}
Try this:
$i=1;
while($i<=10)
{
echo $i;
$i++;
if($i>5)
{
$i=1;
echo "</br>";
}
}
You can try this:-
$count = 10;
for ($i = 0; $i < $count; $i++)
{
if($i != ($count-1)){$coma = ',';}else{$coma = '';}
$value = ($i % 5)+1;
$output = $value.$coma;
echo $output;
}
Output:- 1,2,3,4,5,1,2,3,4,5
<?php
$loop=1;
for($i=1;$i<=10;$i++)
{
echo $loop;
if($i==5)
{
$loop=0;
echo "</br>";
}
$loop++;
}
?>
Output:
12345
12345
This can be achieved without using loop also please find the below 2 functions helpful
First:
function createDateRangeArray($strDateFrom,$strDateTo)
{
// takes two dates formatted as YYYY-MM-DD and creates an
// inclusive array of the dates between the from and to dates.
// could test validity of dates here but I'm already doing
// that in the main script
$aryRange=array();
$iDateFrom=mktime(1,0,0,substr($strDateFrom,5,2), substr($strDateFrom,8,2),substr($strDateFrom,0,4));
$iDateTo=mktime(1,0,0,substr($strDateTo,5,2), substr($strDateTo,8,2),substr($strDateTo,0,4));
if ($iDateTo>=$iDateFrom)
{
array_push($aryRange,date('Y-m-d',$iDateFrom)); // first entry
while ($iDateFrom<$iDateTo)
{
$iDateFrom+=86400; // add 24 hours
array_push($aryRange,date('Y-m-d',$iDateFrom));
}
}
return $aryRange;
}
Second:
$st_date = '2012-07-20';
$ed_date = '2012-07-27';
$dates = range(strtotime($st_date), strtotime($ed_date),86400);
$range_of_dates = array_map("toDate", $dates);
print_r($range_of_dates);
function toDate($x){return date('Y-m-d', $x);}
These 2 functions will be returning you the dates between the 2 dates you will pass and then you can loop on the output array to perform operations
I have written the following code to count the number of string occurrences in a given file.
PHP
<?php
$p = fopen("g.txt", "r");
$q = fread($p, filesize("g.txt"));
$t = explode(" ", $q);
$m = explode(" ", $q);
$i = 0;
$j = 0;
$r = 0;
$count = 0;
$c = count($t);
$d = array();
echo "count of".
"<br/>";
for ($i = 0; $i < $c; $i++) {
for ($j = $i; $j < $c; $j++) {
if ($t[$i] == $t[$j]) {
$count = $count + 1;
}
}
for ($r = $i + 1; $r < $c; $r++) {
if ($t[$i] == $t[$r])
unset($t[$r]);
}
echo $t[$i].
"=".$count.
"<br/>";
$count = 0;
}
?>
I am getting a notice of undefined offset on line numbers 17 and 24, though my output is coming out to be correct. Can you please help me in rectifying the above problem?
The problem is that you are deleting items from the array $t. You saved the count in $c, but the actual count will change by your last inner loop.
Even if you replace $c by count($t) everywhere, it will go wrong, because the last loop should be in reverse order, otherwise you skip items. For instance if you have the list 'a', 'b', 'c'. then when you delete 'b' and increment $r, you will not check 'c' at all.
So, if I fix those things, your code becomes as below. Although I didn't really check it for other issues. Frankly, I don't really get what is should do. ;-)
<?php
$p=fopen("g.txt","r");
$q=fread($p,filesize("g.txt"));
$t=explode(" ",$q);
$m=explode(" ",$q);
$i=0;
$j=0;
$r=0;
$count=0;
$d=array();
echo "count of"."<br/>";
for($i=0; $i<count($t); $i++)
{
for($j=$i; $j<count($t); $j++)
{
if($t[$i]==$t[$j])
{
$count=$count+1;
}
}
for($r=count($t) - 1; $r > $i; $r--)
{
if($t[$i]==$t[$r])
unset($t[$r]);
}
echo $t[$i]."=".$count."<br/>";
$count=0;
}
?>
In conclusion, you should do more tests. If the outcome of this script was okay, then it was by accident.
Need to receive data of fields from $i raw of mysqli object.
$res = $mysqli->query("SELECT mood,count(mood) as number FROM em_mood GROUP by mood ORDER by mood ASC");
$obj = $res->fetch_object();
for ($i = 1; $i <= 10; $i++){
if ($i==$obj->mood[$i]) $mood_result .= "<div class='chart'>".$obj->mood[$i].$obj->number[$i]."</div>";
else $mood_result .= "<div class='chart'>empty</div>";
}
Explanation:
$obj->mood is equal from 1 to 10.
if $obj->mood is missing "2" for example, I need to exchange it with empty div.
In other words, what is the syntax of getting field [mood] value in lets say second raw? something like $obj[2][mood]?
Update:
Looks like it works like this:
for ($i = 1; $i <= 10; $i++){
$res = $mysqli->query("SELECT mood,count(mood) as number FROM em_mood WHERE date>=CURDATE()-INTERVAL 30 DAY and mood=".$i);
$obj = $res->fetch_object();
echo $obj->mood." - ".$obj->number."<br>";
}
Is there any way to make this more simple? To don`t make 10 mysqli queries?
$raw = [];
$sql = "SELECT mood,count(mood) as number FROM em_mood GROUP by mood";
$res = $mysqli->query($sql);
while ($obj = $res->fetch_object())
{
$raw[$obj->mood] = $obj->number;
}
now you will have your "raw" data all right
for ($i = 1; $i <= 10; $i++){
if (isset($raw[$i])) {
$mood_result .= "<div class='chart'>$i - $raw[$i]</div>";
} else {
$mood_result .= "<div class='chart'>empty</div>";
}
}
I have a HTML Form where i can add rows dynamically, every time a row is added the number in my input field goes up each time
each row there are 4 input fields and each one has the number on the end of the name
on my submit page i have this PHP for loop:
for($x=1;$x<=$_POST["number"];$x++)
{
}
but its only getting one posted value
i have tried changing to:
for($x=0;$x<=$_POST["number"];$x++)
{
}
but this does the same thing
for ($x = 0; $x < count($_POST['number']); $x++)
{
echo "Number: $_POST['number'][$x]";
}
// OR:
foreach ($_POST['number'] as $number)
{
echo "Number: $number";
}
You have to add the count() function and use < instead of <= or else you will get an:
index out of range error.
Try this:
for ($x = 0; $size = count($_POST['number']); $x < size; $x++)
{
echo "Number: $_POST['number'][$x]";
}
Bad practice:
for ($x = 0; $x < count($_POST['number']); $x++)
{
echo "Number: $_POST['number'][$x]";
}
Why? The array size is fetched on every iteration and this will make your code run slower.