waiwai933 Posted December 9, 2008 Share Posted December 9, 2008 Hi everyone! I need a little help with a new script of mine. How do I get it so that the script, once connected to the db & table, checks if a row exists. For example, if I'm allowing users to register, I don't want them to have the same username. So, I need to check if that username already exists, by connecting to the database and selecting the table. How do I get a variable that tells me if that username has been taken up, if let's say, each username is stored in a field called 'user'. Quote Link to comment https://forums.phpfreaks.com/topic/136145-checking-for-existing-row/ Share on other sites More sharing options...
corbin Posted December 9, 2008 Share Posted December 9, 2008 SELECT COUNT(username) as cnt FROM users WHERE user = '$username'; Then, if the first column of that != 0, you know that the username already exists. Quote Link to comment https://forums.phpfreaks.com/topic/136145-checking-for-existing-row/#findComment-710121 Share on other sites More sharing options...
waiwai933 Posted December 9, 2008 Author Share Posted December 9, 2008 I'm sorry, can you break that up? I'm pretty new to PHP. Quote Link to comment https://forums.phpfreaks.com/topic/136145-checking-for-existing-row/#findComment-710144 Share on other sites More sharing options...
corbin Posted December 9, 2008 Share Posted December 9, 2008 That's not PHP (for the most part); that's MySQL. What exactly do you not get about it? You would use it like: $username = $_POST['username']; $unames = mysql_real_escape_slashes($username); $q = mysql_query("SELECT COUNT(username) as cnt FROM users WHERE user = '{$unames}'"); if(mysql_result($q, 0, 0) == 1)) { //name exists. } Another, possibly better way, would be to do SELECT 1 FROM users WHERE user = ''; and then check the row count. Quote Link to comment https://forums.phpfreaks.com/topic/136145-checking-for-existing-row/#findComment-710283 Share on other sites More sharing options...
fenway Posted December 9, 2008 Share Posted December 9, 2008 There is an EXISTS query, too. Quote Link to comment https://forums.phpfreaks.com/topic/136145-checking-for-existing-row/#findComment-710572 Share on other sites More sharing options...
waiwai933 Posted December 10, 2008 Author Share Posted December 10, 2008 Actually Corbin, your rewriting it made it make sense. Thanks. Actually, I'm new to both PHP and MySQL. I have just one question. What does the second line, the one that says $unames = mysql_real_escape_slashes($username); What does that line do? I can't find that command on Google. Quote Link to comment https://forums.phpfreaks.com/topic/136145-checking-for-existing-row/#findComment-711021 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.