Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Similar to mysql_fetch_assoc(), this function returns an associative array
- given a mysql resource, but prepends the table name (or table alias, if
- used in the query) to the column name, effectively namespacing the column
- names and allowing SELECTS for column names that would otherwise have collided
- when building a row's associative array.
- */
- function mysql_fetch_assoc_with_table_names($resource) {
- // get a numerically indexed row, which includes all fields, even if their names collide
- $row = mysql_fetch_row($resource);
- if( ! $row)
- return $row;
- $result = array();
- $size = count($row);
- for($i = 0; $i < $size; $i++) {
- // now fetch the field information
- $info = mysql_fetch_field($resource, $i);
- $table = $info->table;
- $name = $info->name;
- // and make an associative array, where the key is $table.$name
- $result["$table.$name"] = $row[$i]; // e.g. $result["user.name"] = "Joe Schmoe";
- }
- return $result;
- }
- $resource = mysql_query("SELECT * FROM user JOIN question USING (user_id)");
- while($row = mysql_fetch_assoc_with_table_names($resource)) {
- echo $row['question.title'] . ' Asked by ' . $row['user.name'] . "n";
- }
- select * from tabx tx, taby ty where ... ;
- SELECT tabx.*, taby.* FROM tabx, taby WHERE ...
- <?php
- $pdo = new PDO($dsn, $user, $pass, array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION));
- function aliasFields($pdo, $table, $delim='__') {
- $fields = array();
- // gotta sanitise the table name - can't do it with prepared statement
- $table = preg_replace('/[^A-z0-9_]/', "", $table);
- foreach ($pdo->query("EXPLAIN `".$table."`") as $row) {
- $fields[] = $table.'.'.$row['Field'].' as '.$table.$delim.$row['Field'];
- }
- return $fields;
- }
- $fieldAliases = array_merge(aliasFields($pdo, 'artist'), aliasFields($pdo, 'event'));
- $query = 'SELECT '.implode(', ', $fieldAliases).' FROM artist, event';
- echo $query;
- // ABOVE PROGRAM'S OUTPUT (assuming database exists)
- SELECT artist__artist_id, artist__event_id, artist__artist_name, event__event_id, event__event_name FROM artist, event
- <?php
- $pdo = new PDO($dsn, $user, $pass, array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION));
- $query = 'SELECT artist.*, eventartist.* FROM artist, eventartist LIMIT 1';
- $stmt = $pdo->prepare($query);
- $stmt->execute();
- while ($row = $stmt->fetch()) {
- foreach ($row as $key=>$value) {
- if (is_int($key)) {
- $meta = $stmt->getColumnMeta($key);
- echo $meta['table'].".".$meta['name']."<br />";
- }
- }
- }
Add Comment
Please, Sign In to add comment