If I do this in PHP, it works fine and loops as expected:
$rs = mysql_query($sql);
while ($row = mysql_fetch_assoc($rs)){
writeme("UserID: " . $row["UserID"]);
}
But I keep wanting to abstract this out into a function I have called ExecuteQuery:
function ExecuteQuery($sql){
$result = mysql_query($sql);
if ($result) {
if($result != 1){
return mysql_fetch_assoc($result); // return recordset
}
}else{
$message = 'Invalid query: ' . mysql_error() . "<br>";
$message .= 'Whole query: ' . $sql;
echo $message;
die();
}
}
This function works great in 2 out of 3 scenarios:
1- Works great for a query that returns 1 row, and I can access like this:
$rs = ExecuteQuery($sql);
$foo = $rs["UserID"];
2- Works great for a sql statement that returns no records, like an UPDATE or DELETE.
3- But when I try to get back a recordset that returns multiple records, and then loop through it, I get an infinite loop and my browser crashes. Like this:
$rs = ExecuteQuery($sql);
while ($row = $rs){
writeme("UserID: " . $row["UserID"]);
}
How can I modify my while loop so it advances to each new record in the recordset and stops after the last record? I'm sure it's a dumb little thing, but I'm not expert with PHP yet. I'd really like my ExecuteQuery function to be able to handle all 3 scenarios, it's very handy.
try foreach($rs as $row){ instead of while ($row = $rs){
mysql_fetch_assoc() only returns one row of the result. To get the next row, you need to call mysql_fetch_assoc() again. One thing you could do is have your ExecuteQuery function return an array of arrays:
$rows = array();
while ($row = mysql_fetch_assoc($result) !== false) {
$rows[] = $row;
}
return $rows;
Also, you should not use the mysql_* functions as they are deprecated. Try using PDO or mysqli_* instead.
Don't use while, use foreach:
$rs = ExecuteQuery($sql);
foreach ($rs as $row){
writeme("UserID: " . $row["UserID"]);
}
Related
I am trying to query a db for an entire column of data, but can't seem to get back more than the first row.
What I have so far is:
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
if($row = mysqli_fetch_array($medicationItemObj, MYSQLI_NUM)){
echo count($row);
}
It's not my intention to just get the number of rows, I just have that there to see how many it was returning and it kept spitting out 1.
When I run the sql at cmd line I get back the full result. 6 items from 6 individual rows. Is mysqli_fetch_array() not designed to do this?
Well, I had a hard time understanding your question but i guess you are looking for this.
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
if($row = mysqli_num_rows($medicationItemObj))
{
echo $row;
}
Or
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
$i = 0;
while ($row = mysqli_fetch_array($medicationItemObj))
{
$medicationItem[] = $row[0];
$i++;
}
echo "Number of Rows: " . $i;
If you just want the number of rows i would suggest using the first method.
http://php.net/manual/en/mysqli-result.num-rows.php
You can wrote your code like below
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
while ($row = mysqli_fetch_assoc($medicationItemObj))
{
echo $row['medication'];
}
I think this you want
You could give this a try:
$results = mysqli_fetch_all($medicationItemObj, MYSQLI_NUM);
First, I would use the object oriented version of this and always use prepared statements!
//prepare SELECT statement
$medicationItemSQL=$connection->prepare("SELECT medication FROM medication");
// execute statement
$medicationItemSQL->execute();
//bind results to a variable
$medicationItemSQL->bind_result($medication);
//fetch data
$medicationItemSQL->fetch();
//close statement
$medicationItemSQL->close();
You can use mysqli_fetch_assoc() as below.
while ($row = mysqli_fetch_assoc($medicationItemObj)) {
echo $row['medication'];
}
I want to create a function that returns all results from a mysqli query in an array.
function Get(){
// verification... verification...
$res = $this -> link -> query("SELECT " . $select . " FROM " . $from);
while ($res->fetch_assoc())
{
$row[] = $res->fetch_assoc();
}
return $row;
}
i = 0;
var_dump(Get());
the while returns only the 1,3,5,7,9 results
Can someone explain the result?
You do twice $ref->fetch_assoc();
while ($result = $res->fetch_assoc())
{
$row[] = $result;
}
You should change your code and run:
while ($result = $res->fetch_assoc())
{
$row[] = $result;
}
Explanation:
In your code in your loop you have while ($res->fetch_assoc()) what makes that 1st record is taken from your results and it's being checked if this record is in database (it there are no records fetch_assoc return false and loop isn't executed anymore. However you don't assign this result to any variable so this result simple disappear. Then inside your loop you use $row[] = $res->fetch_assoc(); so you take the second record from database. Now the loop is being executed again. This is how this works.
The $res->fetch_assoc() call returns a single row from the result set and increments the internal pointer of the result set by one. Since you are calling fetch_assoc several times per Get() call, your results are not what you expect. If you'd like to get a single row of results, call fetch_assoc once. If you'd like to return all the rows from the result set, do something like this:
function Get(){
// verification... verification...
$res = $this -> link -> query("SELECT " . $select . " FROM " . $from);
$rows = array();
while( $row = $res->fetch_assoc() ) {
$rows[] = $row;
}
return $rows;
}
var_dump(Get());
These are my two methods for querying a database.
This is my first method that saves all the results in an array. Then i use a foreach loop to loop through the array.
public function query($query) {
$rows = array();
if ($result = $this->mysqli->query($query)) {
if($result->num_rows > 1) {
while ($item = $result->fetch_assoc()) {
$rows[] = $item;
}
//jo else sepse nxjerr error kur ska asnje row i ben fetch kur ska row.
} else if($result->num_rows == 1) {
$rows = $result->fetch_assoc();
}
return $rows;
} else {
echo "error";
}
}
Then to output I use:
$run_query = $db->query($query);
foreach ((array)$runk_query as $data) {
....
This is my second method:
$query = $db->query("SELECT * FROM ...");
while($run_query = mysqli_fetch_array($query)) {
//OUTPUT data.
....
}
I notice that in many cases I need to output the results so I think using the first method is bad because I use once the while loop and then I use again a foreach loop so the work is done twice but the second way is not very OOP.
Can anyone suggest me the best method of this or if possible another better method?
You can likely replace you entire first function with a call to mysqli_fetch_all() instead of iterating through each record with fetch_assoc(). This way you don't have to build your array result by result.
You can then run through all the results with your second foreach as per usual.
See: http://www.php.net//manual/en/mysqli-result.fetch-all.php
Alternatively if you were using PDO you could use fetchAll()
See: http://www.php.net/manual/en/pdostatement.fetchall.php
$query = "SELECT * FROM table";
$result = mysql_query($query, $db);
$all = mysql_fetch_assoc($result);
echo mysql_num_rows($result) . ":" . count($all);
This returns
2063:7
I have not used count before, so I'm not 100% sure it's not counting the table columns. It's late and I might be going nuts.
Here's another example of what's happening:
$result = mysql_query($query, $db);
echo "Rows: " . mysql_num_rows($result) . " <BR />";
$player_array = mysql_fetch_assoc($result);
echo "<pre>";
print_r($player_array);
echo "</pre>";
Which outputs:
Rows: 9
Array
(
[playerID] => 10000030
)
TL;DR: I submit queries which return multiple rows, but fetch_array only gives me a small portion of those rows in the resulting array.
mysql_fetch_assoc returns only one row in once you have to use loop to retrieve all rows
while($row = mysql_fetch_assoc($result))
{
print_r($row);
}
Every call to mysql_fetch_assoc($result); gives you one row of the result set:
(from the documentation)
mysql_fetch_assoc — Fetch a result row as an associative array
Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead. mysql_fetch_assoc() is equivalent to calling mysql_fetch_array() with MYSQL_ASSOC for the optional second parameter. It only returns an associative array.
You have to use the function in a loop:
$all = array();
while(($row = mysql_fetch_assoc($result))) {
$all[] = $row;
}
The example in the document shows how it is done.
mysql_fetch_assoc doesn't work that way, you need to call it multiple times to get all rows. Like this:
while ($row = mysql_fetch_assoc($db_result))
{
print_r($row);
}
I want to make a simple function that I can call on to query my database. I pass the "where" part of the query to it and in the code below, my $q variable is correct. However, what should I then do to be able to use the data? I'm so confused at how to do something I'm sure is extremely easy. Any help is greatly appreciated!
function getListings($where_clause)
{
$q = "SELECT * FROM `listings` $where_clause";
$result = mysql_query($q,$dbh);
foreach (mysql_fetch_array($result) as $row) {
$listingdata[] = $row;
}
return $listingdata;
}
Your function should be like this:
function getListings($where_clause, $dbh)
{
$q = "SELECT * FROM `listings` $where_clause";
$result = mysql_query($q, $dbh);
$listingdata = array();
while($row = mysql_fetch_array($result))
$listingdata[] = $row;
return $listingdata;
}
Improvements over your function:
Adds MySQL link $dbh in function arguments. Passit, otherwise query will not work.
Use while loop instead of foreach. Read more here.
Initialize listingdata array so that when there is no rows returned, you still get an empty array instead of nothing.
Do you have a valid db connection? You'll need to create the connection (apparently named $dbh) within the function, pass it in as an argument, or load it into the function's scope as a global in order for $result = mysql_query($q,$dbh); to work.
You need to use while, not foreach, with mysql_fetch_array, or else only the first row will be fetched and you'll be iterating over the columns in that row.
$q = "SELECT * FROM `listings` $where_clause";
$result = mysql_query($q,$dbh);
while (($row = mysql_fetch_array($result)) != false)
{
$listingdata[] = $row;
}
Always add error handling in your code. That way you'll see what is going wrong.
$result = mysql_query($q,$dbh);
if (!$result) {
trigger_error('Invalid query: ' . mysql_error()." in ".$q);
}
Here is a function which will save you some time. First Argument tablename, then condition(where), fields and the order. A simple query will look like this : query_db('tablename');
function query_db($tbl_name,$condition = "`ID` > 0",$fields = "*",$order="`ID` DESC"){
$query="SELECT ".$fields." FROM `".$tbl_name."` WHERE ".$condition." ORDER BY".$order;
$query=$con->query($query);
$row_data=array();
while($rows = $query->fetch_array()){
$row_data[] = $rows;
}
return $row_data;
}