how to avoid last added 2 data in while loop
$counter = 0;
$data=mysql_query("select * from tbl_sub_product");
$cnt = sizeof(mysql_fetch_assoc($data));
while($row= mysql_fetch_assoc($data)) {
if(($counter==$cnt-1) || ($counter== $cnt-2)){
}
echo $id = $row['id'];
}
is this a correct way.?is there any other way.? please help me
Firstly, as #Twinfriends said you should avoid using mysql_ functions.
You need to actually increment your $counter. You can do this by $counter++ (which is basically shorthand for $counter = $counter + 1 or $counter += 1).
Also, as #jeroen pointed out, the way you're checking for the count would have
returned the first row of your results so it would be missing from your while loop.
Given you the column count rather than the row count.
With mysql_ functions you need to use mysql_num_rows() for this.
$counter = 0;
$data = mysql_query("select * from tbl_sub_product");
$cnt = mysql_num_rows($data);
$stop = $cnt - 2;
while ($row = mysql_fetch_assoc($data)) {
$counter++;
if ($counter >= $stop) {
break;
}
echo $id = $row['id'];
}
break; inside a loop with stop the loop there and then. If you have the situation where you want to skip an iteration but you don't want to stop the loop you can use continue; instead.
Hope this helps!
The solution would be simple. Adding an additional condition within your while loop is not required at all, consider the solution below and Moreover mysql_functions are deprecated so I will suggest you to go with mysqli_functions
$count = 1;
/* Here $db would be something like $db = mysqli_connect('YOUR_HOST', 'DB_USER', 'DB_PASSWORD', 'DB_NAME'); */
$data = mysqli_query($db, "select * from tbl_sub_product");
$rows_count = mysqli_num_rows($data);
while($count++ < $rows_count-2 && $row = mysqli_fetch_array($data)) {
echo $id = $row['id']
}
That's all you have to do.
You can do it like this
$counter = 0;
$data=
mysql_query("select*
from tbl_sub_p roduct");
$cnt =mysql_num_rows($data);
$run=$cnt-2;
while($row=
mysql_fetch_assoc($data)) {
$count++;
if($count!=$run)
{echo $id = $row['id'];
}
}
If you want to avoid last two entries added in database then simply modify your query to:
$data = mysql_query("SELECT * FROM tbl_sub_product ORDER BY id DESC LIMIT 2,18446744073709551615");//it will start selecting from 3rd record and leave first two records in database which are actually last inserted records
this is the answer for my question
$counter = 0;
$data=mysql_query("select* from tbl_sub_product");
$cnt =mysql_num_rows($data);
$run=$cnt-0;
$run1=$cnt-1;
while($row= mysql_fetch_assoc($data)) {
$count++;
if($count!=$run && $count!=$run1)
{
echo $id = $row['id'];
}
}
Related
I'm echoing out all the rows on a page for a query of mine.
I also need to capture the first row and last row into PHP variables to do a calculation.
db = new mysqli('server','username','password','database');
$resource = $db->query("SELECT . . . (my query, not wanting to modify this)");
I can get the last row into a variable like this.
$numResults = $resource->num_rows;
$counter = 0;
while ( $rows = $resource->fetch_assoc() ) {
if (++$counter == $numResults) {
$lastrow = $rows['column'];
}
I can get the first row in a php variable like this.
$first = mysqli_fetch_assoc($resource);
$firstrow = $first['column'];
But it seems it is only allowing me to do one or the other.
If I comment out the first block of code to get $lastrow, my second block to get $firstrow shows up.
If I comment out the second block of code to get $firstrow, my first block to get $lastrow shows up.
Anyone know of any tricks I can use so that I can get both $firstrow and $lastrow into variables on the same page using PHP?
There are a few ways to do it. Below are 2 of them.
1) Similar to your example - this is simple to understand as it uses a while loop and an if structure
$firstRow = $resource->fetch_assoc();
$lastRow = NULL;
while ( $rows = $resource->fetch_assoc() ) {
$lastRow = $rows;
}
if(!isset($lastRow)) $lastRow = $firstRow;
2) Using mysqli_data_seek - http://php.net/manual/en/mysqli-result.data-seek.php
// First Row
$resource->data_seek(0);
$firstRow = $resource->fetch_assoc();
// Last Row
$resource->data_seek($resource->num_rows - 1);
$lastRow = $resource->fetch_assoc();
If your above code is working then try following
$numResults = $resource->num_rows;
$counter = 0;
while ( $rows = $resource->fetch_assoc() ) {
if ($counter == 0) {
$firstrow = $rows['column'];
}
if (++$counter == $numResults) {
$lastrow = $rows['column'];
}
}
It is very simple ... Rows are like arrays !!!
As you got your number of rows in $numResults ...
For first row -- $rows[0]
For last row -- $rows[$numresults-1]
Totally try below ..
$numResults = $resource->num_rows;
$firstrow = $rows[0]; //first
$rows[$numresults-1]; //last
Hope this helps ...
I have a table with par_id and columns (par1-5) 1 up to 5, but I'm trying to have my php function below to echo any number of columns
//-------------------------------------- get about ----------------------------------------------
function getAbout($option){
$div = array();
$sql_st = "undefined";
if($option == "about")
$sql_st = "SELECT * FROM `about` where par_id='1'";
// connect to database
mysql_connect($_SESSION['dbSever'],$_SESSION['dbUser'],$_SESSION['dbPass']) or die(mysql_error());
mysql_select_db($_SESSION['tblName']) or die(mysql_error());
$result = mysql_query($sql_st) or die(mysql_error()."<br/>".$sql_st);
$num_rows = mysql_num_rows($result);
while ($row = mysql_fetch_array($result) ){
// not sure what to do here
}
// disconnect
mysql_close();
return $div;
}
From your question title I'm assuming you have an ID maybe in your first column and you want to keep that from being printed. You could try something like:
$numberOfColumns = mysql_num_fields($result);
while ($row = mysql_fetch_array($result) ){
for ($i = 1; $i < $numberOfColumns; $i++){
echo $row[$i];
}
}
The $i iterator in the for loop is initiated with value of 1 because PHP handles (like many languages) arrays as zero-based, which means that the first element is referenced by $row[0] (as in this example) - by starting the loop at one and going for as many elements there are in the array, you're effectively grabbing all elements except for the first one.
A really simple one would be to have a flag like so:
$skippedFirstRow = false;
while ($row = mysql_fetch_array($result)){
if(!$skippedFirstRow) {
//do whatever you want here
}
$skippedFirstRow = true;
}
However, keep in mind that this is just a quick hack for what you want and considering your code, but it is not an elegant solution.
I understand this could appear alarming but bear with me.
I need to echo every field in every row in a table.
This is only an example - I have removed the HTML wrapped around it to improve readability.
$a = 1;
while ($a <= $count_rows) {
$query = "SELECT col1, col2 etc.. FROM table WHERE `id`='$id'";
$result = mysqli_query($con, $query);
$i = 1;
while($i <= $count_fields) {
$row = mysqli_fetch_array($result, MYSQL_NUM);
echo "$row[$i]";
$i++;
}
$a++;
$id = $a;
}
This only outputs the first field of every row? Why?
If I echo $row[2] I get nothing!
If I echo $row[2] I get nothing!
because it's actually third item
and there is some strange code interfering with $i variable
Anyway, to get every column from every row ou need a code like this
$query = "SELECT * FROM table";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_row($result)) {
foreach ($row as $index => $value) {
echo "$index => $value, ";
}
echo "<br>\n";
}
This question already has answers here:
How to store values from foreach loop into an array?
(9 answers)
Closed 1 year ago.
I have this code:
include('config.php');
$result = mysql_query("SELECT * FROM system");
while($row = mysql_fetch_array( $result )) {
$name_system = $row['name'];
$value_system = $row['value'];
if($name_system=='website_register' AND $value_system==1)
{$register_system = 1;}
else
{$register_system = 0;}
if($name_system=='website_offline' AND $value_system==1)
{$offline_system = 1;}
else
{$offline_system = 0;}
}
My problem is the fact that the loop only displays the last record from "system" table.
My problem is the fact that the loop only it displays the last record from
No, the problem is the fact that the loop displays nothing. The display happens afterward, in code that's outside the loop and therefore gets executed only once, when the cursor has browsed the whole table and only the last row remains in $row to be printed.
Move the code that does the echo or print or whatever inside the loop, and it'll work.
This is sloppy, but it will show you what's happening as it goes through the loop:
include('config.php');
$result = mysql_query("SELECT * FROM system");
while ($row = mysql_fetch_array($result)) {
$name_system = $row['name'];
$value_system = $row['value'];
if($name_system=='website_register' AND $value_system==1)
{$register_system = 1;}
else
{$register_system = 0;}
if($name_system=='website_offline' AND $value_system==1)
{$offline_system = 1;}
else
{$offline_system = 0;}
print "$name_system, $value_system, $register_system, $offline_system<br />";
}
Your problem is you're overriding the last value each time on the same variable. Instead, add it as a new cell in an array. e.g. each place instead of doing
$register_system = 1;
Do
$register_system[] = 1;
At the end your can do print_r($register_system) to see all the value. You'll notice the keys of the array are 0,1,... You can consider using the $row['name'] as the key, like this:
$register_system[$row['name']] = 1
Assuming of-course these are distinct values.
the echo/print needs to be inside the loop.
Try to use break wherever it is necessary...
Use the logic of flag variable...
You might want to store your items into an array.
$result = mysql_query("SELECT * FROM system");
while($row = mysql_fetch_array( $result )) {
$name_system[] = $row['name'];
$value_system[] = $row['value'];
if($row['name']=='website_register' AND $row['value']==1)
{$register_system[] = 1;}
else
{$register_system[] = 0;}
if($row['name']=='website_offline' AND $row['value']==1)
{$offline_systemp[] = 1;}
else
{$offline_system[] = 0;}
}
That way you can print out each of the values by doing something like:
for ($i = 0; $i < count($name_system); $i++) {
echo 'Name system is: '.$name_system[$i];
}
<?php
//function to create a table
function makeTable($table, $columns){
$numFields = count($columns)-1;
$query = 'SELECT * FROM '.$table;
$result = mysql_query($query);
$arrayResult = mysql_fetch_array($result);
$num_rows = mysql_num_rows($result);
for ($x = 1; $x <= $num_rows; $x++){ //1st for loop
echo '<tr>';
for ($i = 0; $i <= $numFields; $i++){ //2nd for loop
echo '<td>'.$arrayResult[$columns[$i]].'</td>';
}
echo '</tr>';
}
}
?>
$columns is an array entered by the user eg: $columns = array ('Column1', 'Column2', 'Column3);. These are the names of the columns which are in a given $table.
My idea was to create a function that displays the data from the MySQL table with the info from the $columns array. The problem is in the second for loop. The value of $i is reset every time the first loop is done, so I get the same result over and over again (the number of rows in the table).
My question is this: How do I keep the $i in the second loop from resetting?
Thank you in advance.
The reason you get the same result over and over is not because $i, but $arrayResult.
The right way is like this:
//function to create a table
function makeTable($table, $columns){
$numFields = count($columns)-1;
$query = 'SELECT * FROM '.$table;
$result = mysql_query($query);
while ($arrayResult = mysql_fetch_array($result)){
echo '<tr>';
for ($i = 0; $i <= $numFields; $i++){ //2nd for loop
echo '<td>'.$arrayResult[$columns[$i]].'</td>';
}
echo '</tr>';
}
}
In your code you simple fetch always the first row and regardless of the subsequent cycles you only deal with that first row.
Just place
$arrayResult = mysql_fetch_array($result);
within the first loop just before echo '<tr>';
Anyway, for is not the best choice for iterating the records of a table, consider using while.
Why Dont you use while loop? If you use while you even don't need mysql_num_rows($result). Try this
function makeTable($table, $columns){
$numFields = count($columns)-1;
$query = 'SELECT * FROM '.$table;
$result = mysql_query($query);
while($arrayResult = mysql_fetch_array($result)){
echo '<tr>';
for ($i = 0; $i <= $numFields; $i++){ //2nd for loop
echo '<td>'.$arrayResult[$columns[$i]].'</td>';
}
echo '</tr>';
}
}
I m sure, you will get your ans
Your code won't work ever. Because you didn't read manual entry for mysql_fetch_array()
There is no use for the for loops these days. You need some manual to see how to deal with loops in PHP. foreach and while you will need more often than for.
The idea of creating such a function is wrong. combining SQL and HTML in one function is a sign of VERY BAD design. What you really need is a function to get SQL data into array and a template.
a function
function sqlArr($sql){
$ret = array();
$res = mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
if ($res) {
while($row = mysql_fetch_array($res)){
$ret[] = $row;
}
}
return $ret;
}
a code
$data = sqlArr("SELECT * FROM table");
include 'template.php';
a template
<table border='1'>
<? foreach ($data as $row): ?>
<tr>
<? foreach ($row as $col): ?>
<td><?=$col?></td>
<? endforeach ?>
</tr>
<? endforeach ?>
</table>
However, you can put this latter template code into function, if you're gonna use it often.
and call it like
<? drawTable($data) ?>