riceje7 Posted August 20, 2009 Share Posted August 20, 2009 i'm just learning mysql and i am migrating from a flat file database on a project i'm working on and i can't figure out how to, in php with mysql, check to see if a user name already exists and if it doesnt then insert the post data any help would be greatly appreciated. here is my code... not sure how much it will help though :-\ <?php $username = $_POST['user']; $password = $_POST['password']; $password2 = $_POST['password2']; $email = $_POST['email']; $zip = $_POST['zip']; $image = $_FILES['image']; $imageNAME = $_FILES['image']['name']; if($password != $password2) { echo "Passwords do not match."; die; } $connect = mysql_connect('localhost','dbname','dbpass') or trigger_error("SQL", E_USER_ERROR); $db = mysql_select_db('user_data',$connect) or trigger_error("SQL", E_USER_ERROR); $sql = "SELECT username FROM user_data WHERE username LIKE $username"; $search = mysql_query($sql, $connect); if ($search == null) { $sql = "INSERT INTO `user_data`.`user_data` (`username`, `password`, `email`, `zipcode`, `picture_name`) VALUES ('$username', '$password', '$email', '$zip', '$imageNAME');"; $insert = mysql_query($sql, $connect); } else { echo "Username Exists Already."; die; } ?> Link to comment https://forums.phpfreaks.com/topic/171079-checking-for-existing-data-in-mysql-database/ Share on other sites More sharing options...
trq Posted August 20, 2009 Share Posted August 20, 2009 Firstly, mysql_query will never return null. As it states in the manual it returns a result resource on success or false on failure. However, this still wont help you as you need to see if you have results returned from your select statement. For this, you need to use mysql_num_rows. eg; if ($search = mysql_query($sql, $connect)) { if (!mysql_num_rows($search)) { $sql = "INSERT INTO `user_data`.`user_data` (`username`, `password`, `email`, `zipcode`, `picture_name`) VALUES ('$username', '$password', '$email', '$zip', '$imageNAME');"; $insert = mysql_query($sql, $connect); } else { echo "Username Exists Already."; die; } } Link to comment https://forums.phpfreaks.com/topic/171079-checking-for-existing-data-in-mysql-database/#findComment-902251 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.