Fetch Fields (of one row) from a MySQL Table

I was sick and tired of writing small queries where I had to retrieve one or few or even all records of one row against an id. E.g. when I had a userid and I had to fetch firstname, lastname and/or email against that id, I had to write a query each time and then repeat that mysql_query() & mysql_fetch_assoc() over and over again.

I then decided to write a function that helped me alot and reduced my coding time by huge amount. Here’s the function.

function getFieldsFromTable($fields, $table, $where_val, $where_field = "id"){
	$q = "SELECT $fields FROM $table WHERE $where_field = '$where_val'" ;
	if($row = mysql_fetch_assoc(mysql_query($q))){
		if(strpos($fields,",") || $fields == "*"){ // has more than one fields
			return $row ;
		}else{
			return $row[key($row)] ;
		}
	}
}

And here’s a list of ways I used it in.

$email = getFieldsFromTable(“email”, “users_table”, 8 ) ;
When I knew that id is the field name I’ve to search against.

list($firstname, $lastname) = getFieldsFromTable(“firstname,lastname”, “users_table”, 8, “id”) ;
Here I knew that “WHERE id=8” is the clause I’m using it against, but still I mentioned “id”. The function returns an array which I’m receiving using list().

$arr_userfields = getFieldsFromTable(“*”, “users_table”, “me@mydomain.com”, “email”) ;
This will return an array of all the fields against “WHERE email = ‘me@mydomain.com'”.

$counter = getFieldsFromTable(“count(*) as counter”, “users_table”, “Gohar”, “firstname”) ;
This will return the count of all the records “WHERE firstname =
‘Gohar'”.

Another PHP function, in the conjunction of which I used this function of mine, and got excellent results, is

extract(getFieldsFromTable(“firstname,lastname”, “users_table”, 8), EXTR_PREFIX_ALL, “user”) ;
This is a very powerful function of PHP that creates variables of all the elements of an array using their indexes and as an option (e.g. EXTR_PREFIX_ALL), concats the variable names with a string that you mention, here “users”… and returns variables (e.g. $user_firstname & $user_lastname).

This function can further be modified to accept multiple tables and multiple fields for WHERE CLAUSE.

Powered by ScribeFire.

One thought on “Fetch Fields (of one row) from a MySQL Table

Leave a comment