473,770 Members | 2,217 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Query returning array

I'm missing something very obvious, but it is getting late and I've
stared at it too long.

TIA for responses
I am writing a basic function (listed at the bottom of this post) that
returns data from a query into an array.

The intent is that the following code:
$foo = dbSelectData("S ELECT foo, bar FROM table", $link);
would return an array with the keys: 'foo' and 'bar'.

But what I get is instead a multidimensiona l array.
Doing a var_dump on $foo turns out to be
array(2) {
["foo"]=>
string(5) "Stuff"
["bar"]=>
string(10) "More Stuff"
}
I'm wondering where I went wrong in writing the function below.
function dbSelectData($q uery, $connection, $rtype=MYSQL_AS SOC){

$result = mysql_query($qu ery, $connection);
if(!$result){
dbThrowError("E rror in function dbSelectData. Query Was <em>
$query</em>.");
return FALSE;
}
else{
$numrows = mysql_num_rows( $result);

if($numrows == 0){
return FALSE;
}
else{
while($rows = mysql_fetch_arr ay($result, $rtype)){
$output[] = $rows;
}
mysql_free_resu lt($result);
return $output;
}
}
}
Thanks in advance.

--
Karl Groves

Apr 20 '07 #1
13 2555
Karl Groves wrote:
I'm missing something very obvious, but it is getting late and I've
stared at it too long.

TIA for responses
I am writing a basic function (listed at the bottom of this post) that
returns data from a query into an array.

The intent is that the following code:
$foo = dbSelectData("S ELECT foo, bar FROM table", $link);
would return an array with the keys: 'foo' and 'bar'.

But what I get is instead a multidimensiona l array.
Doing a var_dump on $foo turns out to be
array(2) {
["foo"]=>
string(5) "Stuff"
["bar"]=>
string(10) "More Stuff"
}
I'm wondering where I went wrong in writing the function below.
function dbSelectData($q uery, $connection, $rtype=MYSQL_AS SOC){

$result = mysql_query($qu ery, $connection);
if(!$result){
dbThrowError("E rror in function dbSelectData. Query Was <em>
$query</em>.");
return FALSE;
}
else{
$numrows = mysql_num_rows( $result);

if($numrows == 0){
return FALSE;
}
else{
while($rows = mysql_fetch_arr ay($result, $rtype)){
$output[] = $rows;
}
mysql_free_resu lt($result);
return $output;
}
}
}
Thanks in advance.
That's weird, your code seems to be working on my box.
The only thing that i can think of right now that would return that
result is when you return $rows instead of $output.... or when you
assign your $rows to $output, you forgot the bracket (ie. $output[] =
$rows) .... but that is not the case with you posted code

Hendri Kurniawan

Hendri Kurniawan
Apr 20 '07 #2

"Karl Groves" <ka**@NOSPAMkar lcore.comwrote in message
news:Xn******** *************** ******@199.45.4 9.11...
| I'm missing something very obvious, but it is getting late and I've
| stared at it too long.

it is obvious to me only because i have programmed it already...here' s a
static method of my db class:

public static function execute($sql, $decode = false, $returnNewId =
false)
{
self::$lastStat ement = $sql;
$array = array();
$key = 0;
if (!($records = mysql_query($sq l))){ return false; }
$fieldCount = @mysql_num_fiel ds($records);
while ($row = @mysql_fetch_ar ray($records, MYSQL_NUM))
{
for ($i = 0; $i < $fieldCount; $i++)
{
$value = $row[$i];
if ($decode){ $value = self::decode($v alue); }
$array[$key][strtoupper(@mys ql_field_name($ records, $i))] = $value;
}
$key++;
}
if ($returnNewId)
{
$array = array();
$array[0]['ID'] = mysql_insert_id ();
}
@mysql_free_res ult($records);
return $array;
}

notice, and here's what your code is missing, the use of $key. that way you
create a multi-dimentional array of fields AT $key rather than what you're
getting now. here's example of useage:

$sql = "
SELECT Foo ,
Bar
FROM raspberries
";
$records = db::execute($sq l);
foreach ($records as $record)
{
echo '<pre>Foo == ' . $record['FOO'] . '</pre>';
echo '<pre>Bar == ' . $record['BAR'] . '</pre>';
}

hth,

me
Apr 20 '07 #3
| it is obvious to me only because i have programmed it already...here' s a
| static method of my db class:

oops...not so obvious. i mis-read how you were setting $output. it looks
like it should work fine.

are you expecting the query to return only a single row (by the nature of
the query), yet are confused as to why you are still getting an array? your
function always returns an array regardless of row count. you could just use
the $numrows and if one, return the single row...all others would still be
arrays of label/value pairs as it should be.

i don't know...it's late. :)
Apr 20 '07 #4
Karl Groves wrote:
But what I get is instead a multidimensiona l array.
Doing a var_dump on $foo turns out to be
array(2) {
["foo"]=>
string(5) "Stuff"
["bar"]=>
string(10) "More Stuff"
}
Umm... that isn't a multidimensiona l array. Translation follows:

array(2) { // Start of array with 2 elements
["foo"]= // Element with key "foo" is ...
string(5) "Stuff" // ... a 5 character string "Stuff"
["bar"]= // Element with key "bar" is ...
string(10) "More Stuff" // ... a 10 character string "More Stuff"
} // End of array.

A multidimensiona l array would look more like this:

array(1) {
[0]=>
array(2) {
["foo"]=>
string(5) "Stuff"
["bar"]=>
string(10) "More Stuff"
}
}

--
Toby A Inkster BSc (Hons) ARCS
http://tobyinkster.co.uk/
Geek of ~ HTML/SQL/Perl/PHP/Python*/Apache/Linux

* = I'm getting there!
Apr 20 '07 #5
Toby A Inkster wrote:
Karl Groves wrote:
>But what I get is instead a multidimensiona l array.
Doing a var_dump on $foo turns out to be
array(2) {
["foo"]=>
string(5) "Stuff"
["bar"]=>
string(10) "More Stuff"
}

Umm... that isn't a multidimensiona l array. Translation follows:
He was saying... that he expected multi-dimensional array, but get
something else instead.

Hendri Kurniawan
Apr 20 '07 #6
Hendri Kurniawan wrote:
He was saying... that he expected multi-dimensional array, but get
something else instead.
He may have *meant* that, but it's certainly not what he *said*:

| The intent is that the following code: [...]
| would return an array with the keys: 'foo' and 'bar'.
|
| But what I get is instead a multidimensiona l array.

--
Toby A Inkster BSc (Hons) ARCS
http://tobyinkster.co.uk/
Geek of ~ HTML/SQL/Perl/PHP/Python*/Apache/Linux

* = I'm getting there!
Apr 20 '07 #7
Toby A Inkster <us**********@t obyinkster.co.u kwrote in news:nfdmf4-
hc*****@ophelia .g5n.co.uk:
Karl Groves wrote:
>But what I get is instead a multidimensiona l array.
Doing a var_dump on $foo turns out to be
array(2) {
["foo"]=>
string(5) "Stuff"
["bar"]=>
string(10) "More Stuff"
}

Umm... that isn't a multidimensiona l array. Translation follows:

array(2) { // Start of array with 2 elements
["foo"]= // Element with key "foo" is ...
string(5) "Stuff" // ... a 5 character string "Stuff"
["bar"]= // Element with key "bar" is ...
string(10) "More Stuff" // ... a 10 character string "More Stuff"
} // End of array.

A multidimensiona l array would look more like this:

array(1) {
[0]=>
array(2) {
["foo"]=>
string(5) "Stuff"
["bar"]=>
string(10) "More Stuff"
}
}
Very very sorry that my original post is unclear.

Yes, I am getting a multidimensiona l array. My var_dump looks exactly
like your second example. (and I wish it looked like the first, lol)

--
Karl Groves

Apr 20 '07 #8
Karl Groves wrote:
I'm missing something very obvious, but it is getting late and I've
stared at it too long.

TIA for responses
I am writing a basic function (listed at the bottom of this post) that
returns data from a query into an array.

The intent is that the following code:
$foo = dbSelectData("S ELECT foo, bar FROM table", $link);
would return an array with the keys: 'foo' and 'bar'.

But what I get is instead a multidimensiona l array.
Doing a var_dump on $foo turns out to be
array(2) {
["foo"]=>
string(5) "Stuff"
["bar"]=>
string(10) "More Stuff"
}
I'm wondering where I went wrong in writing the function below.
function dbSelectData($q uery, $connection, $rtype=MYSQL_AS SOC){

$result = mysql_query($qu ery, $connection);
if(!$result){
dbThrowError("E rror in function dbSelectData. Query Was <em>
$query</em>.");
return FALSE;
}
else{
$numrows = mysql_num_rows( $result);

if($numrows == 0){
return FALSE;
}
else{
while($rows = mysql_fetch_arr ay($result, $rtype)){
$output[] = $rows;
}
mysql_free_resu lt($result);
return $output;
}
}
}
Thanks in advance.
Hi, Karl,

I'm confused. This should work.

while($rows = mysql_fetch_arr ay($result, $rtype)){

$rows will be a single dimensional array with indexes ['foo'] and ['bar'].

$output[] = $rows;
}
And $output will be an array of the above array with indexes zero to
(number_of_rows _returned - 1).

Are you sure this is the exact code? If so, can you show us where you
call it and dump the results? Maybe the problem is back there.

--
=============== ===
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attgl obal.net
=============== ===
Apr 20 '07 #9
Jerry Stuckle <js*******@attg lobal.netwrote in
news:Vp******** *************** *******@comcast .com:
Karl Groves wrote:
>I'm missing something very obvious, but it is getting late and I've
stared at it too long.

TIA for responses
I am writing a basic function (listed at the bottom of this post)
that returns data from a query into an array.

The intent is that the following code:
$foo = dbSelectData("S ELECT foo, bar FROM table", $link);
would return an array with the keys: 'foo' and 'bar'.

But what I get is instead a multidimensiona l array.
Doing a var_dump on $foo turns out to be
array(2) {
["foo"]=>
string(5) "Stuff"
["bar"]=>
string(10) "More Stuff"
}
I'm wondering where I went wrong in writing the function below.
function dbSelectData($q uery, $connection, $rtype=MYSQL_AS SOC){

$result = mysql_query($qu ery, $connection);
if(!$result){
dbThrowError("E rror in function dbSelectData. Query Was
<em>
$query</em>.");
return FALSE;
}
else{
$numrows = mysql_num_rows( $result);

if($numrows == 0){
return FALSE;
}
else{
while($rows = mysql_fetch_arr ay($result, $rtype)){
$output[] = $rows;
}
mysql_free_resu lt($result);
return $output;
}
}
}
Thanks in advance.

Hi, Karl,

I'm confused. This should work.

while($rows = mysql_fetch_arr ay($result, $rtype)){

$rows will be a single dimensional array with indexes ['foo'] and
['bar'].

$output[] = $rows;
}
And $output will be an array of the above array with indexes zero to
(number_of_rows _returned - 1).

Are you sure this is the exact code? If so, can you show us where you
call it and dump the results? Maybe the problem is back there.
I apologize to everyone for the confusion in my original post.
My var_dump example was wrong.
I'm getting a multidimensiona l array and want a single dimension.

I recognize that my use of $output[] = $rows; seems to be the reason why
I get the multidimensiona l array. I guess my real issue is figuring out
how to get ALL returned rows of the single dimensional array. Everything
else I've tried gives me one row.
--
Karl Groves

Apr 20 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
10296
by: Fraser Ross | last post by:
I need to know the syntax for writing a reference of an array. I haven't seen it done often. I have a class with a member array and I want a member function to return an reference to it. Returning a pointer to the first element might do but I want to do what I've said. Fraser.
41
3829
by: Materialised | last post by:
I am writing a simple function to initialise 3 variables to pesudo random numbers. I have a function which is as follows int randomise( int x, int y, intz) { srand((unsigned)time(NULL)); x = rand(); y = rand();
3
2700
by: Faustino Dina | last post by:
Hi, The following code is from an article published in Informit.com at http://www.informit.com/guides/content.asp?g=dotnet&seqNum=142. The problem is the author says it is not a good idea to return an array as a property because it will return a copy of the array instead a reference to it. How can I force the property to return a reference to the array? Is it only a feature of arrays? I hope normal class objects (including collections)...
5
19600
by: Stacey Levine | last post by:
I have a webservice that I wanted to return an ArrayList..Well the service compiles and runs when I have the output defined as ArrayList, but the WSDL defines the output as an Object so I was having a problem in the calling program. I searched online and found suggestions that I return an Array instead so I modified my code (below) to return an Array instead of an ArrayList. Now I get the message when I try to run just my webservice...
17
3263
by: I.M. !Knuth | last post by:
Hi. I'm more-or-less a C newbie. I thought I had pointers under control until I started goofing around with this: ================================================================================ /* A function that returns a pointer-of-arrays to the calling function. */ #include <stdio.h> int *pfunc(void);
2
4108
by: Rowan | last post by:
For some reason when I do a fetchall on a PDO query the array returned has duplicated keys. see below. SELECT name_first, name_last, personal_street, personal_phone_home, personal_phone_cell FROM contacts WHERE id = 8; $result = $stmnt->fetchAll(); <====krumo array dump===> 0 (Array, 12 elements)
5
5392
by: KDawg44 | last post by:
Hi, Is there a way to get a multidimensional associative array with the entire result set? I would like to get a an array like this: resultsArray How can I accomplish this? Can I do something like this? var $userArray = array(array());
2
5600
by: paulmitchell507 | last post by:
I think I am attempting a simple procedure but I just can't figure out the correct syntax. My asp (classic) page runs a SELECT query to obtain dates and ID's from 2 tables uSQL = "SELECT cal_date, holiday_ID from Calendar, holiday_tbl WHERE (((calendar.cal_Date) Between . And .)) And Email_sent=0 AND Staff_ID=" & Staff_ID This works fine.
5
2681
by: ctj951 | last post by:
I have a very specific question about a language issue that I was hoping to get an answer to. If you allocate a structure that contains an array as a local variable inside a function and return that structure, is this valid? As shown in the code below I am allocating the structure in the function and then returning the structure. I know if the structure contained only simple types (int, float) this will work without problems as you...
0
9619
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9454
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10260
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10102
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10038
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7460
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6712
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5354
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
2850
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.