I want to check for the username in the users
table.
If it's found, then I want to get the id
.
Otherwise, I want to insert the username as a new record, then get the id
.
Here's my code:
<?PHP
$sql = "SELECT id FROM users where username = '$username'";
$query = mysql_query($sql) or die(mysql_error());
$result = mysql_num_rows($query);
if($result){
$row = mysql_fetch_array($query);
$userid = $row["id"];
}else{
$sql = "insert into users set username = '$username'";
$query = mysql_query($sql) or die(mysql_error());
$userid = mysql_insert_id();
}
?>
How can I optimize or combine these MySQL queries?
Can I select and insert in the same query?
and would it be better and faster?