What is my last row_number in mysql query? - php

I have a query like this:
$sql = "SELECT * FROM doctors WHERE city ='$city' LIMIT 10 ";
$result = $db->query($sql);
And I show the result like this :
while($row = $result->fetch_object()){
echo $row->city;
}
The Problem :
Mysql , will search through my database to find 10 rows which their city field is similar to $city.
so far it is OK;
But I want to know what is the exact row_number of the last result , which mysql selected and I echoed it ?
( I mean , consider with that query , Mysql selected 10 rows in my database
where row number are:
FIRST = 1
Second = 5
Third = 6
Forth = 7
Fifth = 40
Sixth = 41
Seventh = 42
Eitghth = 100
Ninth = 110
AND **last one = 111**
OK?
I want to know where is place of this "last one"????
)

MySQL databases do not have "row numbers". Rows in the database do not have an inherent order and thereby no "row number". If you select 10 rows from the database, then the last row's "number" is 10. If each row has a field with a primary id, then use that field as its "absolute row number".

You could let the loop run and track values. When the loop ends, you will have the last value. Like so:
while($row = $result->fetch_object()){
echo $row->city;
$last_city = $row->city;
}
/* use $last_city; */
To get the row number in the Original Table of the last resultant (here, tenth) row, you could save the data from the tenth row and then, do the following:
1. Read whole table
2. Loop through the records, checking them against the saved data
3. Break loop as soon as data found.
Like So:
while($row = $result->fetch_object()){
echo $row->city;
$last_row = $row;
}
Now, rerun the query without filters:
$sql = "SELECT * FROM doctors";
$result = $db->query($sql);
$rowNumber = 0;
while($row = $result->fetch_object()) {
if($row == $last_row) break;
$rowNumber++;
}
/* use $rowNumber */
Hope this helps.

What you can do is $last = $row->id; (or whatever field you want) inside your while loop - it will keep getting reassigned with the end result being that it contains the value of the last row.

You could do something like this:
$rowIndex = 0;
$rowCount = mysqli_num_rows($result);
You'd be starting a counter at zero and detecting the total number of records retrieved.
Then, as you step through the records, you could increment your counter.
while ( $row = $result->fetch_object() ) {
$rowIndex++;
[other code]
}
Inside the While Loop, you could check to see whether the rowIndex is equal to the rowCount, as in...
if ($rowIndex == $rowCount) {
[your code]
}
I know this is a year+ late, but I completely why Andy was asking his question. I frequently need to know this information. For instance, let's say you're using PHP to echo results in a nice HTML format. Obviously, you wouldn't need to know the record result index in the case of simply starting and ending a div, because you could start the div before the loop, and close it at the end. However, knowing where you are in the result set might affect some styling decisions (e.g., adding particular classes to the first and/or last rows).
I had one case in which I used a GROUP BY query and inserted each set of records into its own tabbed card. A user could click the tabs to display each set. I wanted to know when I was building the last tab, so that I could designate it as being selected (i.e., the one with the focus). The tab was already built by the time the loop ended, so I needed to know while inside of the loop (which was more efficient than using JavaScript to change the tab's properties after the fact).

Related

how to identify unsaved value from database using php mysql

I have to identify unsaved value from mysql table using php and mysql, for example i using table named as numtab and i have already stored some numbers 1, 3, 4, 7, 23, 12, 45 in numb column.
now i have generated one new number randomly(for example 23) and i have to check this number with already stored numbers,
if 23 is exist in the table mean i have to generate another one new number and have to check once again with stored values, this process have to continue till finding unsaved number.
if generated value is not exist in table mean can stop the process and can store this number in table.
here below the format i am currently using
$numb=23;
$qryb="select * from numtab where numb='$numb'";
$results=mysql_query($qryb)or die("ERROR!!");
if(mysql_num_rows($results) == 1)
{
$numb=rand(1,100);
mysql_query("insert query");
}
the problem is above the code is validation once only, its not verifying second time. i think if using for or while loop mean can solve this problem, but i dont know how to do looping, so help me to solve this problem.
You can use in clause like this :
$qryb="select * from numtab where numb in('$numb')";
$results=mysql_query($qryb)or die("ERROR!!");
$count = mysql_num_rows($results);
if ($count > 0) {
echo "number exist in db";
} else {
echo "number does not exist in db";
}
You could make a while() loop to check if the numbers exist in your database. You could also retrieve all numbers from the database, store them in an array and check if the generated number exists within that array.
The first option would be something like this:
do {
$numb=rand(1,100);
$qryb="select * from numtab where numb='$numb'";
$results = mysql_query($qryb) or die("ERROR!!");
} while(mysql_num_rows($results) >= 1)
mysql_query("insert query");
The second option would be something like this:
$query = mysql_query("SELECT DISTINCT(numb) as numb FROM numtab");
// set array
$array = array();
// look through query
while($row = mysql_fetch_assoc($query)){
// add each row returned into an array
$array[] = $row['numb'];
}
do
{
$numb = rand(1,100);
}
while(!in_array ( $numb , $array) ;
mysql_query("insert query");

Grouping a SQL result set in PHP

Say I have a query the following query run:
Edit
Added order clause because the real sql statement has one.
SELECT description, amount, id FROM table ORDER BY id
In this instance, the ID is not unique to the dataset. It would return something like this.
Description Amount ID
----------- ------ --
1 Hats 45 1
2 Pants 16 1
3 Shoes 3 1
4 Dogs 5 2
5 Cats 6 2
6 Waffles 99 3
What I need to do is enclose each section of IDs in it's own div (So rows 1,2,3 in one div, 4,5 in another div and 6 in it's own div).
There are tons of solutions to this but I just can't think of one that isn't overly complicated.
I want to be able to keep the SQL how it is and somehow sort the data set in PHP so that I can loop through each section of the dataset while looping through the dataset as a whole.
Some kind of array would work but the structure of it is stumping me.
How can I get this to work? PHP solutions would be idea but theoretical will help too.
See if something like this works for you.
// execute query: Select description, amount, id from table
$results = array();
while ($row = $query_result->fetch_array()) {
if (!isset($results[$row['id']])) $results[$row['id']] = array();
$results[$row['id']][] = $row; // push $row to results for this id
}
// later on
foreach($results as $id => $data) {
// output div based on $id
foreach($data as $datum) {
// output individual data item that belongs to $id
}
}
A simple serial solution might look something like this:
$curId = ''; // track working id
$firstDiv = true; // track if inside first div
// open first div
echo '<div>';
// foreach $row
{
// when id changes, transition to new div, except when in first div
if ($row->$id != $curId) {
if ($firstDiv) {
$firstDiv = false;
} else {
// start new div
echo '</div>';
echo '<div>';
}
$curId = $row->$id; // track new current id
}
// display contents of current row
}
// close last div
echo '</div>';
Just store the id in temp variable, if the next one is different close the div and open new div
Assuming associative arrays for the db results:
$final = array();
foreach($results as $result)
{
$final[$result['id']][] = $result;
}
This leaves you with an associative array $final that groups the entries by ID

php query does not retrieve any data?

well, i wanna pull out some data from a mysql view, but the wuery dos not seem to retrieve anything ( even though the view has data in it).
here is the code i've been "playing" with ( i'm using adodb for php)
$get_teachers=$db->Execute("select * from lecturer ");
//$array=array();
//fill array with teacher for each lesson
for($j=0;$j<$get_teachers->fetchrow();++$j){
/*$row2 = $get_lessons->fetchrow();
$row3=$row2[0];
$teach=array(array());
//array_push($teach, $row3);
$teach[$j]=mysql_fetch_array( $get_teachers, TYPE );
//echo $row3;*/
$row = $get_teachers->fetchrow();
//$name=$row[0]+" "+$row[0]+"/n";
//array_push($teach, $row1);
echo $row[0]; echo " ";echo $row[1]." ";
//$db->debug = true;
}
if i try something like "select name,surname from users", the query partially works . By partially i mean , while there are 2 users in the database, the loop only prints the last user.
the original query i wanted to execute was this
$get_teachers=$db->Execute("select surname,name from users,assigned_to,lessons
where users.UID=assigned_to.UID and lessons.LID=assigned_to.LID and
lessons.term='".$_GET['term']."'");
but because it didnt seem to do anything i tried with a view ( when you execute this in the phpmyadmin it works fine(by replacing the GET part with a number from 1 to 7 )
the tables in case you wonder are: users,assigned_to and lessons. ( assigned_to is a table connecting each user to a lesson he teaches by containing UID=userid and LID=lessonid ). What i wanted to do here is get the name+surname of the users who teach a lesson. Imagine a list tha displays each lesson+who teaches it based on the term that lesson is available.
Looking at http://adodb.sourceforge.net/ I can see an example on the first page on how to use the library:
$rs = $DB->Execute("select * from table where key=123");
while ($array = $rs->FetchRow()) {
print_r($array);
}
So, you should use:
while ($row = $get_teachers->fetchrow()) {
instead of:
for ($j = 0; $j < $get_teachers->fetchrow(); ++$j) {
The idea with FetchRow() is that it returns the next row in the sequence. It does not return the number of the last row, so you shouldn't use it as a condition in a for loop. You should call it every time you need the next row in the sequence, and, when there are no more rows, it will return false.
Also, take a look at the documentation for FetchRow().
for($j=0;$j<$get_teachers->fetchrow();++$j){
... a few lines later ...
$row = $get_teachers->fetchrow();
See how you call fetchrow() twice before actually printing anything? You remove two rows from the result set for every 1 you actually use.
while ($row = $get_teachers->fetchrow()) {
instead and don't call fetchrow() again within the loop.
Because you're fetching twice first in the loop
for($j=0;$j<$get_teachers->fetchrow();++$j){
... some code ...
// And here you fetch again
$row = $get_teachers->fetchrow();
You should use it like this
while ($row = $get_teachers->fetchrow()) {

Database data in PHP array

I have a table in phpmyadmin that stores an 'id' (auto inc), 'title' and a 'date'.
I have a webpage where I display the 10 latest items (I simply order by ID).
On that page I print the title and the date. My wish is to also display the number of the posted item, so the first posted item is 1, the second is 2, etc. I cannot simply print the ID from the database because if I delete a row, the numbers aren't straight anymore.
My idea was to put all the data in an array but I have no clue what the best way to do this is and how I could print that item number. So for example when I want to display the 54th item I can easily print $items[54][id] or something and it will show me the number 54 and to display the title I print $items[54][title].
I don't know if there are simpler methods, plus arrays always start at 0, but my items must start at 1.
Besides this page that shows the 10 latest items, there is another page where it gets the title of the item out of the URL. How will I be able to search the title in the array and display the data the same way but only for that requested title?
Thanks in advance!
"SELECT COUNT(id) as cnt FROM mytable";
you can select the count of all database entries.
and then assign it to your iterator
$i = $row['cnt']; // this will hold the ammount of records e.g. 21
// other query
while($row = mysql_fetch_assoc($result)) {
echo $i;
$i--; // this will decrement on every iteration 21, 20 , 19, and so on.
}
First off. I would add a timestamp field to the database and order by that instead as it feels overall more reliable and gives you additional details which may prove handy later.
To create the multidimensional array I would do something like:
$result = mysql_query(...);
$items = array();
while($item = mysql_fetch_assoc($result)) {
$items[] = $item;
}
Now $items[12] for example would give you item number 13 (since it's 0-indexed).
Lastly, to select only the item with a specific title I would use a query which included a WHERE clause, like
"SELECT ... FROM ... WHERE title = '".$title."'"
It's very important to sanitize this variable before using it in the query though.
You can read more about MySQL on a lot of places. A quick googling gave me this: http://www.tutorialspoint.com/mysql/index.htm
You should learn PHP before starting to program in PHP ;) Read and work through the PHP manual and some tutorials!
As to your question it is a simple loop you want to do. One way of doing it as an example.
Fetch the 10 last items from the database in any way you like, following some code, partly pseudo-code.
$markup = '';
for ($i=1; $i<=count($items); $i++)
{
$markup .= 'Item ' . $i . ': ' . $items['date'] . ' - ' . $items['title'];
$markup .= 'read more';
$markup .= PHP_EOL;
}
echo $markup;
I don't know how you print out your data exactly, but I assume there is a loop in there. Simply set a counter that increments by one at every row and print its value.
As for the title search, you'll have to run another query with a WHERE title = '$title' condition, but beware of SQL injection.

PHP, MySQL Per row output

Been all over the place and spent 8 hours working loops and math...still cant get it...
I am writing a CP for a customer. The input form will allow them to add a package deal to their web page. Each package deal is stored in mysql in the following format
id header item1 item2 item3...item12 price savings
The output is a table with 'header' being the name of the package and each item being 1 of the items in the package stored in a row within the table, then the price and amount saved (all of this is input via a form and INSERT statement by the customer, that part works) stored rows as well.
Here is my PHP:
include 'dbconnect.php';
$query = "SELECT * FROM md ";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
//Print 4 tables with header, items, price, savings
//Go to next row (on main page) and print 4 more items
//Do this until all tables have been printed
}
mysql_free_result($result);
mysql_close($conn);
Right now the main page is simpley a header div, main div, content wrap and footer div.
Ideal HTML output of a 'package' table, not perfect and a little confusing
$header
$item1
$item2
ect...
$price$savings
I basically want the PHP to print this 4 times per row on the main page and then move to the next row and print 4 times and continue until there are no more items in the array. So it could be row 1 4 tables, row 2 4 tables, row 3 3 tables.
Long, confusing and frustrating. I about to just do 1 item per row..please help
Jake
You say "tables", but do you mean cells?
The basic flow would be:
$res = mysql_query(...) or die(mysql_error());
if (mysql_numrows($res) == 0) {
... say there's nothing to show ...
} else {
... print table header ...
while($row = mysql_fetch_assoc($res)) {
... print row ...
}
... print table footer
}
if i get your question right you need to use a loop, something like a for
while ($row = mysql_fetch_array($result)) {
for($i=1; $i<=3; $i++){
//print table (change $i values to change number of loops)
}
}
if i didnt get it right, please post an example of how the table should look like.
$items_per_line=4;
$counter=$items_per_line;
while ($row = mysql_fetch_array($result)) {
if($counter <1){
$counter=$items_per_line;
// goto next pages
}
// print header etc.
$counter--;
}

Categories