This question already has answers here:
How can I loop through a MySQL result set more than once using the mysql_* functions?
(7 answers)
Closed 9 months ago.
I want to use a query result multiple times.
$result=mysql_query("Select field from tables;");
while($result_details = mysql_fetch_array($result))
{ echo $result_details[0]; //Returns 10 Rows..
}
but if I use mysql_fetch_array($result) again its not returning rows..
I don't want to execute the same query multiple times Please let me know how to use the results of a query multiple times.
First fetch all records using a while loop:
$result=mysql_query("Select field from tables;");
while($result_details = mysql_fetch_array($result))
{
$var[]=$result_details;
}
Then display all using a foreach loop and a single variable $var anywhere in the same page where you used query or put query in a functions.php file and include and use anywhere:
foreach ($var as $value) {
$value['field'];
}
If you do not want to make multiple queries then simply unwind the pointer to the desired position.After you execute your code.You should call function to seek to initial (0) position:
$result=mysql_query("Select field from tables;");
while($result_details = mysql_fetch_array($result))
{ echo $result_details[0]; //Returns 10 Rows..
}
mysqli_data_seek($result ,0);
You need to "rewind" result pointer using: http://php.net/manual/en/function.mysql-data-seek.php
Related
I was messing around with how to do queries from MySQL and show them on PHP and I stumbled upon something:
This is the table I'm doing the query to:
$query = mysqli_query($conexion, "SELECT * FROM notas");
while($nota = mysqli_fetch_assoc($query)){
var_dump($nota);
echo $nota["Descripcion"];
}
Whenever I use a while() to display all the results of the query, it works. This table have 2 rows and both of them are showing.
Result of the var_dump($notas):
But whenever I use a foreach(), it just returns me the last result of the query.
$query = mysqli_query($conexion, "SELECT * FROM notas");
foreach(mysqli_fetch_assoc($query) as $valor){
var_dump($valor);
}
Result of the var_dump($valor):
Is there any reason why? I'm doing something wrong in the foreach() loop? I really can't tell. I would just say "fudge it", accept it and only use while loops to display queries, but, you know, want to know if I was doing something wrong or not understanding something.
The second version is looping through the columns, not the rows. It's equivalent to:
$row = mysqli_fetch_assoc($query);
foreach ($row as $valor) {
var_dump($valor);
}
You can see here that it's just fetching one row, which is an associative array, then looping through the elements of that array.
foreach (<expression> as <variable>) doesn't re-evaluate the expression every time through the loop. It executes it once, saves that array, then loops through the array elements.
The mysqli_result object is iterable, so you can do:
foreach($query as $valor) {
var_dump($valor);
}
You can also call mysqli_fetch_all($query), which will return a 2-dimensional array of all the results, and then loop through that. But if the query returns many results, this will use lots of memory.
I have found some PHP code that connects to a MySQL database and gets the column CityName for each row of the table Cities. I'm curious why while() loop is used and not for() or foreach. So here are my questions regarding how while() works in case of looping through arrays:
First, isn't $row variable an 2D array which it's rows contains the list of cities from the SQL query and it's columns contain the columns of each row of the query?
If this is the case, couldn't for() or foreach() be used to loop through the $row array?
Second, how does while() know when the array ends using only $row = $stmt->fetch_assoc() in the while()'s first line in order to end the loop?
Third, how does while() move to the next row of the $row array without using next() at the end of the loop?
And last but not least, how does echo $row['CityName']; output the city name of each row of the $row array without specifying the row of the array to use but only it's column CityName?
Thanks for any answers.
$query="SELECT CityName FROM Cities";
if($stmt = $connection->query("$query"))
{
while ($row = $stmt->fetch_assoc())
{
echo $row['CityName'];
}
}
else
{
echo $connection->error;
}
You could loop through $row, because it is an array (a simple array, not a 2d array); but you're not looping through an array called $row with the while, you're iterating over the resultset returned by $stmt->fetch_assoc() - which isn't an array- and assigning the value of a single returned row to $row in that statement (note the = for assignment) from the resultset.
while itself doesn't magically move any pointer; it's the call to $stmt->fetch_assoc() that not only returns a single row result, but moves the resultset pointer to the next result (and determines when it has reached the end of the resultset)
while($this_is_true){
// do this
}
# if the condition is not true for this while stmt, it will not execute (not even once)
do{
// stuff here
} while($thisIsTrue);
# even if the condition isn't true, a do-while executes at least once (the first time)
The point is that they are using a while() because it's a lazy way to say "only do it if it's true", so they don't have to check if it's true before they loop through it. WIth a for loop, you need to know the number of results you are looping through. For a do, you need to know that there are results before you attempt to use the results (echo). So, you use a while() to check if it's valid and then execute it, with just that piece of code.
Personally, I like to do...
if($query->num_rows > 0){
$query->bind_result($bindvar);
while($query->fetch()){
// do stuff
}
$query->close();
} else {
// no results found
}
You can use foreach instead of while. At least if stmt is a mysqli_result and you PHP version is not terribly outdated (newer than 5.4). In that case your loop would be:
foreach($stmt as $row)
{
echo $row['CityName'];
}
But this does not mean that $stmt is a 2D array. It's an object that implements the Traversable interface. That means that the foreach loop will implicitly invoke the required methods.
This question already has answers here:
CodeIgniter - return only one row?
(11 answers)
Closed 9 years ago.
Having trouble with Codeigniter. I am trying to fetch the value of a product from mysql. The mysql table contain a field called cost_price. I am trying to fetch the result of a single product using the product ID. Here is the code im using,
$query = $this->db->query('SELECT * FROM items WHERE id="$id"');
$row = $query->result();
echo $row['cost_price'];
But nothing is happening ! What is the problem with my code?
I tried some wrong code to check whether the database is responding or not, but it seems that the database is working fine. Can't understand why my query can't find any result !
Try something like this:
$row = $this->db->get_where('items', array('id' => $id))->row();
Or, if you just need the price:
$price = $this->db->select('cost_price')
->get_where('items', array('id' => $id))
->row()
->cost_price;
EDIT
Your method was ok up to a point, look:
$query = $this->db->query('SELECT * FROM items WHERE id="$id"');
$res = $query->result(); // this returns an object of all results
$row = $res[0]; // get the first row
echo $row['cost_price']; // we have an object, not an array, so we need:
echo $row->cost_price;
Alternatively, if you want an array, you can use result_array() instead of result().
My way, row(), returns only the first row. It's also an object, and if you need an array, you can use row_array().
I suggest you read more about all that here.
This question already has answers here:
Get sum of MySQL column in PHP
(9 answers)
Closed 9 years ago.
how do I get the output from this:
$VisitorsProfile = $mysql->query("SELECT SUM(views) FROM visitors_profile WHERE publisher = '123456'");
I tryed this but nothing prints me out!
<?php echo $VisitorsProfile['sum'] ?>
Any suggestions?
you need to name the column, I know it sounds weird but it should be
$VisitorsProfile = $mysql->query("SELECT SUM(views) as totals FROM visitors_profile WHERE publisher = '123456'");
and as indicated as below you need the mysql_fetch_assoc function on the query so you can reference it by name.
Then you can reference it by
<?php echo $VisitorsProfile['totals'] ?>
you just need to reference it "as" something. whatever you put in after the word as is what you can refer to it by, i wouldn't use something like "sum" as that is a mysql function and can cause problems.
PHP allows you to get the information by column name or by column index. The recommended way is to do it by column name, because this will allow you to change your query's column order without affecting your PHP code.
So to get it you need to add a column alias to your query:
$rs = mysql_query("SELECT SUM(value) AS total FROM visitors_profile WHERE publisher = '123456'");
if ($row = mysql_fetch_assoc($rs)) {
echo $row['total'];
}
On the first line you are actually running the query. Check the column alias: "total".
On the second line you are asking for an array or specifically a "map" from the result set. In other words, by calling mysql_fetch_assoc you are asking for an array whose elements are available by name. That array represents a row from your result set.
On the third line you are printing the actual sum.
Check the "if" in the $row assignment. This will help you validate there is a result row before trying to print it. I recommend you to do the same on the line where you call mysql_query.
EDIT:
Sorry, I think you are using objects, so it should look like this:
$rs = $mysql->query("SELECT SUM(value) AS total FROM visitors_profile WHERE publisher = '123456'");
if ($row = $mysql->fetch_assoc($rs)) {
echo $row['total'];
}
I am using the sqlsrv driver for IIS so I can connect to a MS SQL server in PHP.
I've managed to convert a lot of my original mysql_ code and all going well, until I tried to SELECT some DateTime fields from the database. They were coming back as Date objects in PHP rather than strings, I found the fix which is adding this to the connection array:
'ReturnDatesAsStrings'=>1
Since doing that though my code is broken when trying to populate my recordset:
function row_read($recordset) {
if (!$recordset) {
die('<br><br>Invalid query :<br><br><bold>' . $this->sql . '</bold><br><br>' . sqlsrv_error());
}
$rs = sqlsrv_fetch_array($recordset);
return $rs;
}
The error is: sqlsrv_fetch_array(): 16 is not a valid ss_sqlsrv_stmt resource
There is such little amount of help on that error in Google so this is my only shot! I just don't get it.
row_read is called from within a While: while ($row = $db->row_read($rs)) {
Any ideas?
Just to add more code and logic - I do a simple SELECT of all my orders, then as it loops through them, I do another 2 SELECT's on the orders table then the customer table. It's falling down when I try these extra 2 'gets':
$this->db->sql = "SELECT * FROM TicketOrders";
$rs = $this->db->query($this->db->sql);
$this->htmlList->path("skin/search.bookings");
if ($this->db->row_count != 0) {
while ($row = $this->db->row_read($rs)) {
// Load the order row
$this->TicketOrders->get($this->db, $row['Id']);
// Load the customer row
$this->Customers->get($this->db, $row['CustomerId']);
Did you pass this resource variable by another function? If yes, you can try by executing the sqlsrv_query and executing sqlsrv_fetch_array in one function; don’t pass the ss_sqlsrv_stmt resource by another function. Hope that it will help.
Does your program involves a nested query function?
If so, the next question is: are you opening the same database in the inner query function?
Try these changes:
comment out the lines that open the database, including the { and } that enclose the function,
change the name of connection and array variables between the outer loop and the inner loop.
In other words, the outer loop may have:
$tring = sqlsrv_query($myConn, $dbx_str1);
while( $rs_row1 = sqlsrv_fetch_array($tring, SQLSRV_FETCH_ASSOC))
and the inner loop would have:
$tring2 = sqlsrv_query($myConn, $dbx_str2);
while( $rs_row2 = sqlsrv_fetch_array($tring2, SQLSRV_FETCH_ASSOC))
sqlsrv_fetch_array need a ss_sqlsrv_stmt resource. There must be something wrong with your SQL.