database abstraction functions...

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

verlaine101
Forum Newbie
Posts: 10
Joined: Mon Jul 16, 2007 4:21 am

Post by verlaine101 »

Begby wrote:What do you mean undetermined format?
Sorry if I'm not being clear, what I mean is I want this function to pull out arbitrary fields from any table and format them in any way the user choses.

for example you could have a list of users details from the "users" table.

Code: Select all

rowFormatted(users,"Name:$name Address: $address Email:$email<br/>");
or you could have a table row with details of cars from the "cars" table

Code: Select all

rowFormatted(cars,"<tr><td>$model</td><td>$engine_size</td><td>$colour</td><td>$price</td></tr>");
Hope that makes more sense.
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

@Begby: :?:
@verlaine101: You might want to try something like

Code: Select all

function rowFormated($table, $fields, $format)
{
	$retval = '';
	$query=mysql_query("SELECT $fields FROM $table");
	while ( false!==($row=mysql_fetch_array($query, MYSQL_NUM)) ) {
		array_unshift($row, $format);
		$retval .= call_user_func_array('sprintf', $row);
	}
	
	return $retval;
}

mysql_connect('...
mysql_select_db('...

echo rowFormated('table', 'name,address',"name:%s Address: %s<br />\n");
There are still issues with this code. But at least it doesn't use eval()
Begby
Forum Regular
Posts: 575
Joined: Wed Dec 13, 2006 10:28 am

Post by Begby »

volka wrote:@Begby: :?:
I thought that post was from him looking for examples of a database abstraction layer, I neglected to read the name. 8O
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

oh, php also knows vsprintf, which makes the code even simpler

Code: Select all

function rowFormated($table, $fields, $format)
{
  $retval = '';
  $query=mysql_query("SELECT $fields FROM $table");
  while ( false!==($row=mysql_fetch_array($query, MYSQL_NUM)) ) {
    $retval .= vsprintf($format, $row);
  }
	
  return $retval;
}

mysql_connect('...
mysql_select_db('...

echo rowFormated('table', 'name,address',"name:%s Address: %s<br />\n");
verlaine101
Forum Newbie
Posts: 10
Joined: Mon Jul 16, 2007 4:21 am

Post by verlaine101 »

This code outputs the whole row not just the chosen fields.
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

I have tested the code and it does not print the whole row.
verlaine101
Forum Newbie
Posts: 10
Joined: Mon Jul 16, 2007 4:21 am

Post by verlaine101 »

Oops sorry missed the changed sql query.

That works great I learned quite bit from this thread thanks to you all.
Post Reply