472,805 Members | 933 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,805 software developers and data experts.

PHP/MYSQL data query

Greetings,

I'd like to figure out some syntax for retrieving the data from a table
when I don't know all the of field names. What I do know are, the name
of the table, the names of the primary key fields, and the names of the
fields I want to use in the "where" clause of the SELECT statement. All
of the examples I've seen in my books only show how to do this by
hard-coding the names of each of the fields, i.e.,

$userid=$query_data["userid"];
$userphone=$query_data["phonenum"];
etc.

What I've tried thus far, is to: first, retrieve the name of a field,
store that in a variable, and then, use that variable in the [""]
argument, but I can't get it to work. I also tried using an index,
unsuccessfully. I am able to get the field names successfully and
display them, so I know that part is working.

At the risk of testing patience but perhaps saving time, here's a code
snippet (trouble line is commented in caps, line 10).

Suggestions/examples appreciated.

//connect to the database
1. $linkid = db_connect();

//retrieve the field names of the specified table:
//the value of $userviewtable was passed from a previous line
2. $result=mysql_list_fields("mydatabasename",$uservi ewtable, $linkid);

//define a generic data query to get data from a selected record
3. $query = "select * from $userviewtable where userid='$userid' and
functional_area='$userviewarea';";

//execute the data query and store the result in a variable
4. $result2 = mysql_query($query);

//fetch the resulting data array from the variable
5. $query_data = mysql_fetch_array($result2);
6. mysql_close($linkid);

//at this point $result holds the field names,
//and $query_data holds the data from the selected record

//loop through the field names and use them as
//the arguments for getting the data values
7. echo "Data for selected record on table $userviewtable<br>";
8. for ($i=0; $i<mysql_num_fields($result); $i++) {
//this line seems to be working
9. $fieldname = mysql_field_name($result, $i);
//THIS IS THE TROUBLE LINE
10. $data_value = $query_data[$fieldname];
//note that I also tried these variations:
//["$fieldname"]; [".$fieldname."]; and [$i];

//result shows field names but no data
11. echo $fieldname: $data_value;
}
//end of snippet

Jul 17 '05 #1
3 4346

Yeah - and its not as difficult as you might think...

Hint: http://ca.php.net/mysql_fetch_array

Need more?

if you want to get all fields/cells from a record, you don't need to
know their names - instead, SELECT * . For example:-

SELECT * FROM TABLE WHERE condition

(condition being whatever your condition is - for example WHERE ID=35
LIMIT 1)

A brief example:

<?
// Select all data from TABLE myTable where fieldName=whatever
$query="SELECT * FROM myTable WHERE fieldName='whatever'";

// Execute our query
$result=mysql_query($query);

// Write the result of our search into $ourRecords - note the
// MYSQL_ASSOC which returns an associate array (meaning the
// keys of your array will have the field names, and not numbers)
$ourRecords=mysql_fetch_array($result, MYSQL_ASSOC);

?>

The above will make $ourRecords a multi-dimensional array... If you
performed a SELECT * (ie select all fields/cells) and your table has the
following fields, ID,FIRSTNAME,LASTNAME,EMPLOYEE_NUMBER and your MySQL
query returned four records, then you would have

$ourRecords[0][ID]
$ourRecords[0][FIRSTNAME]
$ourRecords[0][LASTNAME]
$ourRecords[0][NUMBER]
$ourRecords[1][ID]
$ourRecords[1][FIRSTNAME]
$ourRecords[1][LASTNAME]
$ourRecords[1][NUMBER]
$ourRecords[2][ID]
$ourRecords[2][FIRSTNAME]
$ourRecords[2][LASTNAME]
$ourRecords[2][NUMBER]
$ourRecords[3][ID]
$ourRecords[3][FIRSTNAME]
$ourRecords[3][LASTNAME]
$ourRecords[3][NUMBER]

I hope the above helps - drop me a byte if any of it is unclear... Note
there are things you can do to make improvements (like
mysql_affected_rows() to count how many records were returned - also,
have MySQL make a sort for you (ORDER BY fieldName) and save PHP the
burden - and reduce the time limit it takes to find your data by putting
LIMIT 5 at the end of your query to limit the result to return maximum
five records...)

randelld
Jul 17 '05 #2
'bonehead wrote:
Greetings,

I'd like to figure out some syntax for retrieving the data from a table
when I don't know all the of field names. What I do know are, the name
of the table, the names of the primary key fields, and the names of the
fields I want to use in the "where" clause of the SELECT statement. All
of the examples I've seen in my books only show how to do this by
hard-coding the names of each of the fields, i.e.,

$userid=$query_data["userid"];
$userphone=$query_data["phonenum"];
etc.

What I've tried thus far, is to: first, retrieve the name of a field,
store that in a variable, and then, use that variable in the [""]
argument, but I can't get it to work. I also tried using an index,
unsuccessfully. I am able to get the field names successfully and
display them, so I know that part is working.

At the risk of testing patience but perhaps saving time, here's a code
snippet (trouble line is commented in caps, line 10).

Suggestions/examples appreciated.

//connect to the database
1. $linkid = db_connect();

//retrieve the field names of the specified table:
//the value of $userviewtable was passed from a previous line
2. $result=mysql_list_fields("mydatabasename",$uservi ewtable, $linkid);

//define a generic data query to get data from a selected record
3. $query = "select * from $userviewtable where userid='$userid' and
functional_area='$userviewarea';";

//execute the data query and store the result in a variable
4. $result2 = mysql_query($query);

//fetch the resulting data array from the variable
5. $query_data = mysql_fetch_array($result2);
6. mysql_close($linkid);

//at this point $result holds the field names,
//and $query_data holds the data from the selected record

//loop through the field names and use them as
//the arguments for getting the data values
7. echo "Data for selected record on table $userviewtable<br>";
8. for ($i=0; $i<mysql_num_fields($result); $i++) {
//this line seems to be working
9. $fieldname = mysql_field_name($result, $i);
//THIS IS THE TROUBLE LINE
10. $data_value = $query_data[$fieldname];
//note that I also tried these variations:
//["$fieldname"]; [".$fieldname."]; and [$i];

//result shows field names but no data
11. echo $fieldname: $data_value;
}
//end of snippet


Sorry, I wrongly had not read the full post...

You're almost there... $query_data should be a multi-dimension array,
true? Why not take the first record, and then take the keys from that
record and it should contain the name of all the fields/cells in a
single row of your database. Thus, untested code follows:

<?
$singleRecord=$query_data[0];
$fieldNames=array_keys($singleRecord);
foreach($fieldNames as $fieldNumber=>$fieldName)
{
print("<br>Cell/Column number $fieldNumber is called $fieldName");
}
?>

I hope that helps - and I hope second time around, that I have
understood your question... sorry for the first post...

randelld
Jul 17 '05 #3
Reply via newsgroup wrote:
<?
$singleRecord=$query_data[0];
$fieldNames=array_keys($singleRecord);
foreach($fieldNames as $fieldNumber=>$fieldName)
{
print("<br>Cell/Column number $fieldNumber is called $fieldName");
}
?>
Ahhaaahhh! I did not know about the array_keys function...somehow I
*knew* I would find out something I did not know! And guess what, there
it is, right there in the index of my book. Thanks for the tip.

Now the sticky part is still hanging out there:

Assuming that the following lines have executed correctly:

//connect to db, define and execute query, fetch data array:
$linkid = db_connect();
$query = "select * from $userviewtable where userid='$userid';";
$result = mysql_query($query);
$query_data = mysql_fetch_array($result);
mysql_close($linkid);

and, assuming that I *know* that one of the fields is named "userid", I
would retrieve the data from a particular field as follows:

$my_data=$query_data["userid"];

HOWEVER, if I do *not* know the names of the fields, and wanted to
substitute $fieldName from your example above, I presume I would still
retain the square bracket and double quotes, as follows:
$singleRecord=$query_data[0];
$fieldNames=array_keys($singleRecord);
foreach($fieldNames as $fieldNumber=>$fieldName)
{
print("<br>Cell/Column number $fieldNumber is called $fieldName"); //MY NEW LINES HERE
$my_data=$query_data["$fieldName"];
echo $my_data; }


I'll test this in the morning when I'm soburrrr....thanx again....hic

Jul 17 '05 #4

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

Similar topics

0
by: Lenz Grimmer | last post by:
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi, MySQL 4.0.14, a new version of the popular Open Source/Free Software Database, has been released. It is now available in source and binary...
0
by: Philip Stoev | last post by:
Hi all, Please tell me if any of this makes sense. Any pointers to relevant projects/articles will be much appreciated. Philip Stoev http://www.stoev.org/pivot/manifest.htm ...
0
by: Mike Chirico | last post by:
Interesting Things to Know about MySQL Mike Chirico (mchirico@users.sourceforge.net) Copyright (GPU Free Documentation License) 2004 Last Updated: Mon Jun 7 10:37:28 EDT 2004 The latest...
1
by: jlee | last post by:
I'm pretty much a newbie on mysql, and I need some help. I am running mysql Ver 12.22 Distrib 4.0.24, for portbld-freebsd5.4 (i386) on a server hosting an active website. The site's developer...
1
by: Good Man | last post by:
Hi there I've noticed some very weird things happening with my current MySQL setup on my XP Laptop, a development machine. For a while, I have been trying to get the MySQL cache to work....
1
by: Ike | last post by:
Recently, I began using a different MySQL verver (i.e. different machine as well as different version#, going from 4.12a to 4.1.9 max). The following query used to work: select firstname,...
3
by: Me Alone | last post by:
Hello: I am trying to edit some C code I found in "The definitive guide to using, programming, and administering MySQL" by Paul DuBois. This C client program connects and then segfaults when...
13
by: Ciaran | last post by:
Hi All, Is it faster to have mySql look up as much data as possible in one complex query or to have php do all the complex processing and submit lots of simple queries to the mysql database? ...
6
Atli
by: Atli | last post by:
This is an easy to digest 12 step guide on basics of using MySQL. It's a great refresher for those who need it and it work's great for first time MySQL users. Anyone should be able to get...
221
Atli
by: Atli | last post by:
You may be wondering why you would want to put your files “into” the database, rather than just onto the file-system. Well, most of the time, you wouldn’t. In situations where your PHP application...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 2 August 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: erikbower65 | last post by:
Using CodiumAI's pr-agent is simple and powerful. Follow these steps: 1. Install CodiumAI CLI: Ensure Node.js is installed, then run 'npm install -g codiumai' in the terminal. 2. Connect to...
0
by: erikbower65 | last post by:
Here's a concise step-by-step guide for manually installing IntelliJ IDEA: 1. Download: Visit the official JetBrains website and download the IntelliJ IDEA Community or Ultimate edition based on...
0
by: kcodez | last post by:
As a H5 game development enthusiast, I recently wrote a very interesting little game - Toy Claw ((http://claw.kjeek.com/))。Here I will summarize and share the development experience here, and hope it...
0
by: Taofi | last post by:
I try to insert a new record but the error message says the number of query names and destination fields are not the same This are my field names ID, Budgeted, Actual, Status and Differences ...
14
DJRhino1175
by: DJRhino1175 | last post by:
When I run this code I get an error, its Run-time error# 424 Object required...This is my first attempt at doing something like this. I test the entire code and it worked until I added this - If...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
0
by: lllomh | last post by:
How does React native implement an English player?
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...

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.