note 13814 deleted from language.variables.scope by jimw

From: Date: Sat, 08 Dec 2001 21:44:16 +0000
Subject: note 13814 deleted from language.variables.scope by jimw
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-22225@lists.php.net to get a copy of this message
DB access and GLOBALS: You can create a generic db function (called db_req() in my case) to take a single SQL statement, and store the results of the query in a global two-dimensional associative array; e.g: $db_data["column_header"][row]. when done correctly, you can remove the need to make db calls from your programs, and so you just need to change the generic function if you change databases etc. Two things to note: i) you can't set arrays through the GLOBALS associative array. You must explicitly declare your globals in your generic function, and access them that way. ii) You've now created a duplicate of all the data retrieved by your query. It's perhaps a good idea to free the data from memory after you've read it into your global. EXAMPLE: This is the code I've used for MySQL (excluding the actual mysql access functions) # Declare global variables $db_rows = 0; $db_data[] = NULL; # db_req() function for querying database and reading results into $db_data array. function db_req($sql_query) { global $db_rows, $db_data; # Retrieve query data and store in global vars $db_rows = mysql_num_rows($query_ref); if ($db_rows != 0) { for ($i = 0; $i < $db_rows; $i++) { $fetched_data = mysql_fetch_array($query_ref, MYSQL_ASSOC); while (list ($key) = each ($fetched_data)) { $db_data[$key][$i] = $fetched_data[$key]; } } } return 1; } To access the data you can cycle through each row implicitly using a for loop (and $db_rows to limit your iterations), churning out the info you requested. N.B: You must know what your column headers are.

« previous php.notes (#22225) next »