Capturing Both First and Last Rows in Query into PHP Variables - php

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 ...

Related

How to avoid last added 2 data in while loop

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'];
}
}

How to echo columns 1...n from mysql database except the first one in php?

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.

While loop with assignment operator

I can't seem to figure out how this loop works in PHP:
$people = array();
while($row = $result->fetch_assoc())
$people[] = $row;
It seems as though the loop would just keep going, infinitely. But, it doesn't How exactly does this work? Can someone explain it to me step-by-step? I'm guessing that the while loop could also be written like this:
while(($row = $result->fetch_assoc()) == true)
The fetch_assoc fetches one result row at a time and stores it in $row. Since this is in a loop, you are fetching until you run out of rows
In the loop you are essentially pushing the $row value into a $people array
Your code:
$people = array();
while($row = $result->fetch_assoc())
$people[] = $row;
Example how its works (MySQL):
$people = array();
$result = mysql_query($query);
$rows_count = mysql_num_rows($result);
for ($i = $rows_count - 1; $i >= 0; $i--) {
mysql_data_seek($result, $i);
$people[] = mysql_fetch_assoc($result);
}
How U see first option is more compact.
fetch_assoc will return false either upon an error or when the cursor for the fetch hits the end of all the rows and no more rows can be fetched, so it will return false.
Every time you fetch for the query, a cursor keeps track of the last returned row and will continue to keep track ultimately till you finish reading all rows.
Edit: Sorry I was thinking about PDO and not mysqli, however it should be about the same thing.

MSSQL returns multiple rows into array, explode into one array per row

I have an MSSQL query where it SELECTS all rows that meet a specific criteria. In PHP I want to fetch that array, but then I want to convert it into one array per row. So if my query returns 3 rows, I want to have 3 unique arrays that I can work with.
I'm not sure how to go about this. Any help would be greatly appreciated!
Thanks, Nathan
EDIT:
$query = "SELECT * FROM applicants WHERE applicants.user_id ='{$_SESSION['user_id']}'";
$query_select = mssql_query($query , $connection);
if (mssql_num_rows($query_select) == 2){
$message = '2 students created successfully';
}
$i = 0;
while($row = mssql_fetch_array($query_select)) {
$student.$i['child_fname'][$i] = $row['child_fname'];
$student.$i['child_lname'][$i] = $row['child_lname'];
$i++;
}
$query_array1 = $student0;
$query_array2 = $student1;
You will notice from the code above that I am expecting two rows to be returned. Now, I want to take those two rows and create two arrays from the results. I tried using the solution that was give below. Perhaps my syntax is incorrect or I didn't understand how to properly implement his solution. But any help would be greatly appreciated.
$query = mssql_query('SELECT * FROM mytable');
$result = array();
if (mssql_num_rows($query)) {
while ($row = mssql_fetch_assoc($query)) {
$result[] = $row;
}
}
mssql_free_result($query);
Now you can work with array like you want:
print_r($result[0]); //first row
print_r($result[1]); //second row
...
$i=0;
while( $row = mysql_fetch_array(query){
$field1['Namefield1'][$i] = $row['Namefield1'];
$field2['Namefield2'][$i] = $row['Namefield2'];
$field3['Namefield3'][$i] = $row['Namefield3'];
$i++;
}
or if you preffer an bidimensional array:
$i=0;
while( $row = mysql_fetch_array(query){
$result['Namefield1'][$i] = $row['Namefield1'];
$result['Namefield2'][$i] = $row['Namefield2'];
$result['Namefield3'][$i] = $row['Namefield3'];
$i++
}

How to fetch 2 times in MYSQL PDO without FETCHALL

I have this sample query:
$STH = $DBH->query("SELECT id FROM table");
I want to get the first row and then loop and display all rows. So I use the following to get the first row:
$STH->setFetchMode(PDO::FETCH_ASSOC);
$first_row = $STH->fetch();
$first_row = $first_row['id'];
I use while loop to display all rows again:
while ($list = $STH->fetch()) {
$id = $list['id'];
echo $id;
}
Now the while skips the first row and I want it to be displayed. Is there an equivalent to mysql_data_seek to reset the pointer again to the first row? I know fetchall can be used but it's bad on memory and wasteful. I could also run the query and limit to 1 but this is not recommended as I have a query that joins multiple tables and would be very slow. Is there any other solution?
Thanks
I take that back looks like you can use the cursor orientation contants to select the result... sample code coming... I havent tried this so you may need to play a bit. This is also based on the assumption that a PDO::FETCH_ORI_FIRST acts like a data_seek and leaves the cursor on the first position as opposed to returning it to whatever it was before.
$stmt = $pdo->prepare('SELECT id FROM table', array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$stmt->execute();
$first = $pdo->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_FIRST);
$first_row = $first['id'];
// other stuff
// first iteration we rewind to the first record;
$cursor = PDO::FETCH_ORI_FIRST;
while (false !== ($row = $stmt->fetch(PDO::FETCH_ASSOC, $cursor))) {
$id = $row['id'];
// successive iterations we hit the "next" record
$cursor = PDO::FETCH_ORI_NEXT;
echo $id;
}
I dont think you can rewind a statement... Assuming these blocks arent seprated by a bunch of intermediary logic id just do it in the loop.
$STH->setFetchMode(PDO::FETCH_COLUMN); // no need to pull an array
$count = 0;
while ($id = $STH->fetch()) {
if($count === 0) {
$first_row = $id;
}
echo $id;
$count++;
}
Could you just use a do...while loop instead?
$STH->setFetchMode(PDO::FETCH_ASSOC);
$list = $STH->fetch();
$first_id = $list['id'];
do {
$id = $list['id'];
echo $id;
} while ($list = $STH->fetch());
You can fetch all the result, and then just act on it as an array. So, for instance, you could shift the first result off the front, and then loop over any additional rows:
<?php
$sql = "YOUR QUERY";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
// get first row
$firstRow = array_shift($rows);
// loop over remaining rows
foreach ($rows as $row) {
// do something
}

Categories