I’m trying to implement a simple mysql insert that takes the user’s first name ($first_name) and the user’s last name ($last_name) and inserts them into my users table (url) column. This is very much like Quora and Facebook…www.facebook.com/Michael.Jackson.32 for example.
My while loop is below and I wish I knew the error but when I execute the code, my server just keeps going and eventually timeouts.
Any help is much appreciated.
//Store Vanity URL
$user_id_sql = $db->prepare("SELECT id FROM users WHERE first_name = :first_name AND last_name = :last_name");
$user_id_sql->execute(array(':first_name' => $first_name , ':last_name' => $last_name));
$user_search_results = $user_id_sql->rowCount();
if($user_search_results == "0") {
$vanity = $first_name.'.'.$last_name;
$insert_vanity_url = $db->prepare("INSERT INTO users (url) VALUES (:vanity) WHERE uid = :uid");
$insert_vanity_url->execute(array(':vanity'=>$vanity , ':uid'=>$uid));
}
else {
$var1 = "bad";
$i = "1";
while($var1 == "bad") {
$user_id_sql_two = $db->prepare("SELECT id FROM users WHERE first_name = :first_name AND last_name = :last_name");
$user_id_sql_two->execute(array(':first_name' => $first_name , ':last_name' => $last_name));
$user_search_results_two = $user_id_sql_two->rowCount();
if($user_search_results_two == "0") {
$vanity = $first_name.'.'.$last_name.$i;]
$insert_vanity_url = $db->prepare("INSERT INTO users (url) VALUES (:vanity) WHERE uid = :uid");
$insert_vanity_url->execute(array(':vanity'=>$vanity, ':uid'=>$uid));
$var1 = "good";
}
$i++;
}
}
Ok, I found the problem (well the specific problem):
This query:
does exactly what you think it does, gets all the users with that first and last name. The first time it is used, if no user like that exists, you add the user and the vanity and go on your way.
However, if such a user does exists, as determined by
rowCount(), you go into that loop.That loop contains the same query, checking to see if there are any users with that first and last name. But the only reason you are in this block is because there are users that match the query.
The general logic here is:
What you should probably do is generate the basic vanity, then check for its existence in the table, then you can check your fallback ones, generating a new vanity each loop until it doesn’t exist (this is actually not that good a way of doing it, but better would require more significant changes).
There is actually a lot more to improve with your code, but this is not Code Review, so I will hold my tongue.