I have a mysql result (having many rows) that I will use later. For now, I only need to access (sum) the first 5 rows. The problem is that the rows were saved from the query using "AS", so now they can be accessed by using $row['name'] . How can I select the first 5 rows without using the "name" for each of them?
Is there any way for doing like so:
PHP:
for($i=0;$i<5;++$i)
echo $row[$i];
?
EDIT
Sorry, my question was wrong.
Actually: How can I use the same $result 2 times without loosing the values by fetching the array?
What do you use for working with DB? PDO? MySQLi? MySQL extension?
If you use MySQL extension (mysql_connect(), mysql_query() etc), you can use mysql_data_seek() to move the internal row pointer of the MySQL result:
$res = mysql_query($sql);
if ( mysql_num_rows($res) ) {
// process first 5 lines
for ( $n = 0; $n < 5; ++$n ) {
$row = mysql_fetch_assoc($res);
if ( $row === false ) {
break;
}
// do something with $row
// ...
}
// reset pointer
mysql_data_seek($res, 0);
// process all rows
while ( $row = mysql_fetch_assoc($res) ) {
// do something with $row
// ...
}
}
mysql_free_result($res);
Another option would be to fetch all results into an array and then work with that array. I can't think of any benefit of holding MySQL resource opened.
$result = array();
while( $row = mysql_fetch_array($queryResult) ) {
$result[$row['primaryKey']] = $row; // index the $result according to any fieldValue(say primay key) so that you can access a single records without looping)
echo $row['name'];
}
use $result as many times as you want
you can use mysql query as
select * from table_name_ravi limit 0,5
just use this
I think you mix up things. $row['name'] accesses the column of a row with the name name sou you should work on your fetch function your while( $row = mysql_fetch_assoc($result) ) {}
Related
I don't know why it's behaving like that in Php. In my first while() loop its showing data but second and third while() loop it's not return/showing any data. I'm using only one sql query to get same data 3 times.
Do you know why it's not showing data in second and third while loop in php ?
$query = mysql_query("SELECT * FROM contact_details ORDER BY family_name LIMIT 10");
while($a=mysql_fetch_array($query)){
echo $fname = $a['family_name'];
echo "<br/>";
}
while($b=mysql_fetch_array($query)){
echo $fname = $b['family_name'];
echo "<br/>";
}
while($c=mysql_fetch_array($query)){
echo $fname = $c['family_name'];
echo "<br/>";
}
If you need to use the same result multiple times, store it in a local array first. Once your first loop is completed, there is obviously 'no more data left' as otherwise the while wouldn't have stopped.
For example:
$query = mysql_query("SELECT * FROM contact_details ORDER BY family_name LIMIT 10");
$data = [];
while($row = mysql_fetch_array($query))
$data[] = $row;
foreach($data as $row)
// Do Stuff;
foreach($data as $row)
// Do Stuff;
foreach($data as $row)
// Do Stuff;
Mandatory disclaimer: the mysql_ family of functions is deprecated and will start breaking in future PHP versions. Consider switching to PDO or mysqli.
From PHP docs, mysql_fetch_array returns "Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows" , so second and third loop reuturns FLASE (no more data )
Because the array pointer has reached the end it is not possible to read it again.
you can use
mysql_data_seek ( resource $result , int $row_number );
mysql_data_seek ( $query , 0 );
i suggest that after every while loop try to reset the pointer to this query using this
mysql_data_seek($query, 0); // add this after every while loop.
//you need this to reset the pointer of the query.
try this out and check back if you still have problems.
this link has your same problem and is already answered PHP - Multiple while($row = mysql_fetch_array($variable)) { } ERRORS
I'm working on pagination, and for some reason I cannot use mysql_fetch_array to loop through a result more than once.
//both $page and $imagesPerPage != 0
$offset = $page * $imagesPerPage
while ($row = mysql_fetch_array($result)) {
$total_images++;
}
echo $total_images;
//echos correct amount
$row = null;
$images_to_offset = 0;
while ($row = mysql_fetch_array($result) && $images_to_offset < $offset) {
$images_to_offset++;
}
echo $images_to_offset;
//echos 0... which is wrong
Should I be using a different php function to get row data in a database?
Thanks!
This is the error
while ($row = mysql_fetch_array($result)) {
$total_images++;
}
once you fetched the array the array pointer set to the end.
use this
$total_images=mysql_num_rows($result);
and
$images_to_offset=mysql_num_rows($result);
OR
To reset the position of pointer Use mysql_data_seek(). it moves internal result pointer
If you wish to start fetching from the beginning after you've already fetched, you'll need you use mysql_data_seek().
Also, please note that the mysql line of functions have been deprecated, and the community is encouraging use instead of MySQLi or PDO_MySQL lines of functions.
You could point the pointer back to the first row with mysql_data_seek.
mysql_data_seek($result, 0);
Also see: http://ca2.php.net/manual/en/function.mysql-data-seek.php
You have to 'rewind' the array, by using the mysql_data_seek function:
$offset = $page * $imagesPerPage
while ($row = mysql_fetch_array($result)) {
$total_images++;
}
echo $total_images;
//echos correct amount
$row = null;
mysql_data_seek(); // <-- rewind to the beginning
$images_to_offset = 0;
while ($row = mysql_fetch_array($result) && $images_to_offset < $offset) {
$images_to_offset++;
}
echo $images_to_offset;
mysql_fetch_array not only returns an array that corresponds to the fetched row, it also moves the internal data pointer ahead.
There are more than one way of dealing with this, the most obvious is to "park" your result in an array itself and then work from there. Or query 2 times. Or use mysql_data_seek. In your case, maybe mysql_num_rows is more appropriate, since your code indicates you only want to know how many rows you have to iterate through, and thats what this function is there for.
Whatever decide, keep in mind that use of the mysql extension is discouraged. Instead, the MySQLi or PDO_MySQL extension should be used.
Try using mysql_num_rows() , that way you don't have to iterate the $result twice which is giving you error in the second loop as you have to reset the result pointer. So do it like this which only iterates once:
//both $page and $imagesPerPage != 0
$offset = $page * $imagesPerPage
$total_images = mysql_num_rows($result);
echo $total_images;
//echos correct amount
$row = null;
$images_to_offset = 0;
while ($row = mysql_fetch_array($result) && $images_to_offset < $offset) {
$images_to_offset++;
}
echo $images_to_offset;
As a side note, you should try to migrate to MySQLi or PDO_MySQL to access mysql as the interface you are using is now deprecated, see the red box in http://es.php.net/manual/en/function.mysql-num-rows.php
You can only loop through the results array once, after that they effectively 'disappear'. the way to loop over the results multiple times is to store them into a new array during the first loop, then loop over the new array as many times as you want...
I have a small problem and since I am very new to all this stuff, I was not successful on googling it, because I dont know the exact definitions for what I am looking for.
I have got a very simple database and I am getting all rows by this:
while($row = mysql_fetch_array($result)){
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
Now, my question is: how do I filter the 2nd result? I thought something like this could work, but it doesnt:
$name2= $row['name'][2];
Is it even possible? Or do I have to write another mysql query (something like SELECT .. WHERE id = "2") to get the name value in the second row?
What I am trying to is following:
-get all data from the database (with the "while loop"), but than individually display certain results on my page. For instance echo("name in second row") and echo("id of first row") and so on.
If you would rather work with a full set of results instead of looping through them only once, you can put the whole result set to an array:
$row = array();
while( $row[] = mysql_fetch_array( $result ) );
Now you can access individual records using the first index, for example the name field of the second row is in $row[ 2 ][ 'name' ].
$result = mysql_query("SELECT * FROM ... WHERE 1=1");
while($row = mysql_fetch_array($result)){
/*This will loop arround all the Table*/
if($row['id'] == 2){
/*You can filtere here*/
}
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
$counter = 0;
while($row = mysql_fetch_array($result)){
$counter++;
if($counter == 2){
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
}
This While loop will automatically fetch all the records from the database.If you want to get any other field then you will only need to use for this.
Depends on what you want to do. mysql_fetch_array() fetches the current row to which the resource pointer is pointing right now. This means that you don't have $row['name'][2]; at all. On each iteration of the while loop you have all the columns from your query in the $row array, you don't get all rows from the query in the array at once. If you need just this one row, then yes - add a WHERE clause to the query, don't retrieve the other rows if you don't need them. If you need all rows, but you wanna do something special when you get the second row, then you have to add a counter that checks which row you are currently working with. I.e.:
$count = 0;
while($row = mysql_fetch_array($result)){
if(++$count == 2)
{
//do stuff
}
}
Yes, ideally you have to write another sql query to filter your results. If you had :
SELECT * FROM Employes
then you can filter it with :
SELECT * FROM Employes WHERE Name="Paul";
if you want every names that start with a P, you can achieve this with :
SELECT * FROM Employes WHERE Name LIKE "P%";
The main reason to use a sql query to filter your data is that the database manager systems like MySQL/MSSQL/Oracle/etc are highly optimized and they're way faster than a server-side condition block in PHP.
If you want to be able to use 2 consecutive results in one loop, you can store the results of the first loop, and then loop through.
$initial = true;
$storedId = '';
while($row = mysql_fetch_array($result)) {
$storedId = $row['id'];
if($initial) {
$initial = false;
continue;
}
echo $storedId . $row['name'];
}
This only works for consecutive things though.Please excuse the syntax errors, i haven't programmed in PHP for a very long time...
If you always want the second row, no matter how many rows you have in the database you should modify your query thus:
SELECT * FROM theTable LIMIT 1, 1;
See: http://dev.mysql.com/doc/refman/5.5/en/select.html
I used the code from the answer and slightly modified it. Thought I would share.
$result = mysql_query( "SELECT name FROM category;", db_connect() );
$myrow = array();
while ($myrow[] = mysql_fetch_array( $result, MYSQLI_ASSOC )) {}
$num = mysql_num_rows($result);
Example usage
echo "You're viewing " . $myrow[$view_cat]['name'] . "from a total of " . $num;
I was wondering how I can handle a mysql request in php precisely as an object.
Ex:
//supposing...
$beginning=$_GET['start'];//value equal to 3
$ending=$_GET['end'];//value equal to 17
$conn=new mysqli("localhost","user","password","databasename");
$query=$conn->query("select name, favoriteFood, weight, from tablename");
1- Supposing that tablename has 23 rows, how to printing only 14 rows, beginning for example by 3rd row and ending in 17th row, as following?
Ex:
//supposing... It, I guess, should result in error but is a sketch of my ideia
for($i=$beginning,$colsCol=$query->fetch_array(MYSQLI_ASSOC); $i<$ending; $i++)
printf("%s %s %s<\br>",$colsCol['name'][$i],$colsCol['favoriteFood'][$i],$colsCol['weight'][$i]);
2 - And later, how to order the resulted rows with $query variable?
P.S.: I know that to get results ordered, I could user order by columname, but in this case I would like to order the resulted rows after query been done.
If you want to sort later, after the query's done, then you'd need to store the results in a PHP data structure and do the sorting there. Or re-run the query with new sorting options.
As for fetching only certain rows, it'd be far more efficient to retrieve only the rows you want. Otherwise (for large result sets) you're forcing a lot of data to be pulled off disk, sent over the wire, etc... only to get thrown away. Rather wasteful.
However, if you insist on doing things this way:
$row = 0; $data = array();
while($row = $query->fetch_array(MYSQLI_ASSOC)) {
$row++;
if (($row < 3) || ($row > 17)) {
continue;
}
$data[] = $row;
}
for 2D array you can use it.
function asort2d($records, $field, $reverse=false) {
// Sort an array of arrays with text keys, like a 2d array from a table query:
$hash = array();
foreach($records as $key => $record) {
$hash[$record[$field].$key] = $record;
}
($reverse)? krsort($hash) : ksort($hash);
$records = array();
foreach($hash as $record) {
$records []= $record;
}
return $records;
} // end function asort2d
Use SQL for SQL-tasks:
"how to printing only 14 rows, begging for example by 3rd row and ending in 17th row"
$stmt = $database->prepare('SELECT `name`, `favoriteFood`, `weight` FROM `tablename` LIMIT :from, :count');
$stmt->bindValue(':from', (int)$_GET['start'] - 1);
$stmt->bindValue(':count', (int)$_GET['end'] - (int)$_GET['start']);
I want to retrieve a set of records from a MySQL table as an array.
So far I was able to retrieve each row as an associative array. But I want all the rows in one array because I have to access that complete object in jQuery to display them.
This is what I have done so far.This is my .php script to retrieve data
//select query
$result = mysql_query("SELECT * FROM student",$con) or die (mysql_error());
$numRows = mysql_num_rows($result); //to iterate the for loop
//passing as an associative array
for ($count = 0; $count < $numRows; $count++){
$row = mysql_fetch_array($result, MYSQL_ASSOC);
echo json_encode($row);
}
This is what I currently get
{"StuId":"1","fName":"Saman","lName":"Kumara","age":"14","grade":"A"}
{"StuId":"2","fName":"Marry","lName":"Vass","age":"12","grade":"B"}
{"StuId":"3","fName":"Navjoth","lName":"Bogal","age":"32","grade":"A"}
{"StuId":"4","fName":"Jassu","lName":"Singh","age":"22","grade":"E"}
But I want this result set as follows.
[
{"TEST1":45,"TEST2":23,"TEST3":"DATA1"},
{"TEST1":46,"TEST2":24,"TEST3":"DATA2"},
{"TEST1":47,"TEST2":25,"TEST3":"DATA3"}
]
I seek help in doing this. Thanks in advance.
Put it all in one array, then json_encode it:
$json = array( );
$result = mysql_query("SELECT * FROM student",$con) or die (mysql_error());
while( $row = mysql_fetch_assoc( $result ) ) {
$json[] = $row;
}
echo json_encode( $json );
FYI: there's no need to count the number of results to loop. mysql_fetch_* will internally keep a pointer to the current record and increment that on each call. That makes it a perfect candidate to use in a simple while loop. Also, instead of mysql_fetch_array and passing MYSQL_ASSOC, you can simply use mysql_fetch_assoc instead, a method I much prefer. Makes the code easier to read too (in my opinion, anyway).