Reputation: 6635
I am storing a bunch of user ID's inside of a mySQL database along with other data relative to each uid, but now I would like to implement a check in the beginning of the program which basically goes like so, if the user already exists, get the specified fields for that specific user and assign them to variables, else return null.
$query = mySQL query;
if ($query){
do this...
}else{
do that...
};
I am assuming it would look something like that?
I am a little unsure of my syntax and don't know very much about mySQL which is why I am asking for some help, thanx in advance!
Upvotes: 0
Views: 86
Reputation: 384
$query = "SELECT `name`, `email` FROM `user` WHERE `id` = '$id' LIMIT 1";
$sql = mysql_query($query);
$count = mysql_num_rows($sql);
if ($count >= 1)
{
$name = mysql_result($sql,0,'name');
$email = mysql_result($sql,0,'email');
return /*whatever u need to return*/;
}
also u should never count anything in if()
especially in cycles.
Upvotes: 1
Reputation: 10857
Here's something to get you started, assuming you are connected to the database ..
$query = "SELECT name, email FROM user WHERE id = $id";
$result = mysql_query($query);
if ($arr = mysql_fetch_assoc($result))
{
// either return $arr or build something else with
// individual column values, something like this
// (would require you to define a User class)
$name = $arr['name'];
$email = $arr['email'];
return new User($name, $email);
}
else
{
return null;
}
Alright, as requested, make sure to do something like this with any variables (that you do not have 100% control over) before inserting them into your sql queries:
$id = mysql_real_escape_string($id);
However, I'll have to say that in my apps, user ids come from sources I trust - not from user input.
Upvotes: 1
Reputation: 798666
Not quite. Have the query pull all desired fields WHERE uid=:uid
, then check the number of rows returned via mysql_num_rows()
or the like. On 0 return null, otherwise extract the values from the row.
Upvotes: 1