mysql_fetch_assoc() returning unexpected value - php

I am working on a project where I use mysql_fetch_assoc to return an associative array.
However, I am puzzled as to why it would return TRUE
I have looked at the PHP manual page, and the only boolean value it should be returning is FALSE, and then only on a fail.
Although I am using a custom set of abstraction classes, it is basically doing this:
$result = mysql_query("SELECT * FROM table WHERE filename = 'test1.jpg'");
var_dump(mysql_fetch_assoc($result)); // bool(true)
Does anyone know why it would be returning TRUE instead of an array?
Update
Well, after trying a few things, I've determined its my library, as running the above code returns an associative array. I don't know why exactly it was returning TRUE, but for now, I am going to stop making things more complicated than they have to be (a problem of mine) and just use mysqli (thanks for the tip, Michael) instead of my own ActiveRecord classes, which apparently don't work.
Thanks!

I ran into the same thing. It was a stupid coding error on my part.
I started out with:
$result = mysql_query($someSql);
while($row = mysql_fetch_assoc($result)) {
// do stuff
}
which worked fine. Then I changed it to:
$result = mysql_query($someSql);
while($row = mysql_fetch_assoc($result) && $someCondition) {
// do stuff
}
This is interpreted as $row = (mysql_fetch_assoc($result) && $someCondition), which means $row becomes true while there are rows left and the second condition is true.
What I meant to write was:
$result = mysql_query($someSql);
while(($row = mysql_fetch_assoc($result)) && $someCondition) {
// do stuff
}

Start using mysqli_query mysqli_fetch_assoc, . The old version is soon to be outdated - the new one is better anyways.

Have you tried:
print_r (mysql_fetch_assoc($result));
It may give what you are looking for.
Oh, and silly me, var_dump () returns nothing, it directly outputs its findings like print_r ().

Related

Unreachable Statement in PHP

require_once 'C:/wamp/www/FirstWebsite/CommonFunctions.php';
function SelectRowByIncrementFunc(){
$dbhose = DB_Connect();
$SelectRowByIncrementQuery = "SELECT * FROM trialtable2 ORDER BY ID ASC LIMIT 1";
$result = mysqli_query($dbhose, $SelectRowByIncrementQuery);
$SelectedRow = mysqli_fetch_assoc($result);
return $SelectRowByIncrementQuery;
return $SelectedRow; //HERE is the error <-------------------------------
return $result;
}
$row = $SelectedRow;
echo $row;
if ($row['Id'] === max(mysqli_fetch_assoc($Id))){
$row['Id']=$row['Id'] === min(mysqli_fetch_assoc($Id));#TODO check === operator
}
else if($row['Id']=== min(mysqli_fetch_assoc($Id))){
$row['Id']=max(mysqli_fetch_assoc($Id));#TODO check === operator //This logic is important. DONT use = 1!
Ok, I am trying to write a program for the server end of my website using PHP. Using Netbeans as my IDE of choice I have encountered an error while attempting to write a function which will store a single row in an associative array.
The issue arises when I try to return the variable $SelectedRow. It causes an 'Unreachable Statment' warning. This results in the program falling flat on its face.
I can get this code to work without being contained in a function. However, I don't really feel that that is the way to go about solving my issues while I learn to write programs.
Side Notes:
This is the first question I have posted on SO, so constructive criticism and tips are much appreciated. I am happy to post any specifications that would help an answer or anything else of the sort.
I do not believe this is a so-called 'replica' question because I have failed to find another SO question addressing the same issue in PHP as of yet.
If anybody has any suggestions about my code, in general, I'd be stoked to hear, as I have only just started this whole CS thing.
You can only return one time. Everything after the first return is unreachable.
It's not entirely clear to me what you want to return from that function, but you can only return one value.
The return command cancels the rest of the function, as once you use it, it has served its purpose.
The key to this is to put all of your information in to an array and return it at the end of the function, that way you can access all of the information.
So try changing your code to this:
require_once 'C:/wamp/www/FirstWebsite/CommonFunctions.php';
function SelectRowByIncrementFunc(){
$dbhose = DB_Connect();
$SelectRowByIncrementQuery = "SELECT * FROM trialtable2 ORDER BY ID ASC LIMIT 1";
$result = mysqli_query($dbhose, $SelectRowByIncrementQuery);
$SelectedRow = mysqli_fetch_assoc($result);
$returnArray = array();
$returnArray["SelectRowByIncrementQuery"] = $SelectRowByIncrementQuery;
$returnArray["SelectedRow"] = $SelectedRow;
$returnArray["result"] = $result;
return $returnArray;
}
And then you can access the information like so:
$selectedArray = SelectRowByIncrementFunc();
$row = $selectedArray["SelectedRow"]
And so forth...

PHP while loop. Why does this work?

I'm creating my first php site using tutorial for reference. I can't get my head around why the following works:
while ($row = mysql_fetch_array($result)){
echo $row[1]. " ".row[2]."<br/>";
}
Specifically, how does the loop increment to the next row?
UPDATE:
Thanks to all who bothered to provide an answer, including those who implored me to RTM. My problem was not understanding how while loops work, rather simply I couldn't see how the loop increments.
THE ANSWER:
From the PHP docs,
mysql_fetch_array: Returns an array that corresponds to the fetched row and moves the internal data pointer ahead
I see now, all is well.
You can rewrite that code to this equivalent:
$row = mysql_fetch_array($result); // fetch and advance
while ($row !== false) { // compare result against false
echo $row[1]. " ".row[2]."<br/>";
$row = mysql_fetch_array($result); // fetch and advance
}
An assignment yields a value which can then be used in a condition, though it's a good practice to put parentheses around the assignment:
// fetch and advance, compare fetched result against false
while (($row = mysql_fetch_array($result)) !== false) {
echo $row[1]. " ".row[2]."<br/>";
}
mysql_fetch_array() will take a $result and save into $row in form an array. Using while loop, your program will loop the data in the array from the beginning until the end.
By the way, your codes should be like
while ($row = mysql_fetch_array($result)){
echo $row['someData1']. " ".row['someData2']."<br/>";
}
If you want to iterate through the index, then the code looks like following but it will print the word Array as you will print the result in "that" specific index.
$indexCounter = 0;
while ($row = mysql_fetch_array($result)){
echo $row[$indexCounter]."<br/>";
}
Hope this helps! Thank you.
The mysql_fetch_array take the first element of $result then is $result have elements this work... is like take cards from a deck
Take a read though the PHP While documentation. It might also be useful to learn what mysql_fetch_array() does and how it works. After you're done reading about that, don't use the mysql_* functions again because they're deprecated. Instead, use mysqli_* or PDO.

How do I optimize these two lines?

So, I have these two lines of PHP.
$total_row_count = mysql_fetch_assoc(mysql_query(sprintf('SELECT COUNT(*) as count FROM %s',$table_name),$db));
$total_row_count = $total_row_count['count'];`
Is there any way to change the first declaration of $total_row_count so the 2nd line isn't necessary?
Something to this effect (I know this isn't functional code).
$total_row_count = mysql_fetch_assoc(mysql_query(sprintf('SELECT COUNT(*) as count FROM %s',$table_name),$db))['count'];
Thanks so much!
You second snippet is perfectly functional since PHP 5.4. It's called direct array dereferencing.
However, you should never ever do mysql_fetch_assoc(mysql_query(...)). The mysql_query call may fail and return false, which propagates ugly errors into mysql_fetch_assoc. You need error handling!
$result = mysql_query(...);
if (!$result) {
die(mysql_error());
// or
return false;
// or
throw new Exception(mysql_error());
// or whatever other error handling strategy you have
}
$row = mysql_fetch_assoc($result);
$count = $row['count'];
If this is too much code for you to repeat often, wrap it in a function.
function getCount() {
$result = mysql_query(...);
...
return $row['count'];
}

Last row always returns false?

This works well, except that the last row always returns false. I've use this multiple times within my site and no matter what query I run, the last row always returns false instead of the data in the last row.
So if I have a query that should return 2 rows, it returns 1 row and false. I'm not really sure why.
function query2array($query, $sql_con) {
$result = mysql_query($query,$sql_con);
if(!$result) {
return false;
}
else if (mysql_num_rows($result) > 0) {
//set entire result to array
while($arr_data[] = mysql_fetch_array($result));
var_dump($arr_data);
if(count($arr_data) > 0) {
return $arr_data;
}
}
return false;
}
I'm new to PHP and I've read the documentation on mysql_fetch_array and just can't seem to figure out what's going wrong here. (I also know that I should be using mysqli, but I picked up on a site developed by someone else)
Try this:
while($row = mysql_fetch_array($result))$arr_data[] = $row;
The reason of such behaviour is you appending mysql_fetch_array() result to array without checking if it successfully retrieved.
As of manual:
Returns an array of strings that corresponds to the fetched row, or
FALSE if there are no more rows.
NOTICE: MySQL (mysql*_ functions) extension is deprecated. I suggest to use MySQLi (mysqli*_ functions) or PDO instead.

Drupal - db_fetch_array returns NULL for every row

I'm using Drupal's db_fetch_array to fetch rows from my db_query. However, every row returned is equal to NULL. Typing the query into PHP myadmin works, so I have no idea whats going on. db_num_rows returns the number of rows as well. Here is the code:
if(count($rebuild_ids))
{
$ids=implode(",",$rebuild_ids);
$type_stmt = "SELECT * from {" . ItemType::$type_table_name . "} where id IN ($ids)";
$new_items=db_query($type_stmt);
if(!$new_items || db_num_rows($new_items) == 0)
{
return;
}
while($row = db_fetch_array($new_items));
{
if ($row!=NULL)
{
echo "I work!"
$game_items[] = $row['id'];
ItemInstance::$nid_to_item_type_code[$row['nid']] = $row['id'];
}
}
}
However, it never gets into the third if statement (i.e. never echos "I work!") Any ideas?
Friendly advice: Drupal has a coding standards http://drupal.org/coding-standards -- it helps to keep them. This error would have been a lot more obvious that way....
Also putting variables in a query is a huge no-no see http://drupal.org/writing-secure-code
$row is not NULL by definition, otherwise it wouldn´t even reach the third if statement.
There is no need to check if $row contains information, the while loop already takes care of that, but if you want to check anyway, use something like empty($row) or count($row) > 0; don´t compare an array with NULL.
The checking is completely unnecessary though...
K figured it out. It was the semicolon after the while loop!

Categories