I need a simple code to check if a record exists in a db table. I found this code which does what I want though db_result no longer exists in D7.
$exists = db_result(db_query('SELECT 1 FROM {artistfield} WHERE uid = %d', $user->uid));
How would I write this statement in D7?

Comments

Web Assistant’s picture

Just getting used to D7 myself, does something like the below work?

$result = db_query("SELECT 1 FROM {artistfield} WHERE uid = :uid", array(':uid' => $user->uid))->fetchObject();
jordojuice’s picture

Yeah I don't think there's an equivalent of db_result(). That's the closest I've found, so note that you will get an object, which means you need to check it with $result->1 or similar instead of just $result.

Web Assistant’s picture

How about something like this...

<?php
$result = db_query("SELECT 1 FROM {artistfield} WHERE uid = :uid", array(':uid' => $user->uid))->fetchField();
?>

Got that from here..

http://api.drupal.org/api/drupal/includes--database.pgsql.inc/function/d...

jordojuice’s picture

Oooooh now I think I remember seeing that before too. Thanks.

Firehawk777’s picture

That was just what I was looking for! All works great now!
Thanks guys!!!

only4kaustav’s picture

If you are working in a migration project from d6 to d7 and if there are multiple occurrence of db_result in your custom module you can simply write the below function in any of your custom module without changing the same.

function db_result($res){
	return $res->fetchField();
}