简体   繁体   中英

Apply condition on mysql_query in php

sorry for my really dumb question.(I'm so new in this!).

I have a query (mysql, the programming language is php):

mysql_query("INSERT INTO user (id, f_name, l_name, email, user_name, password, b_day, gender, country, p_number, address, active)
VALUES ('NULL', '$_POST[fname]', '$_POST[lname]', '$_POST[email]', '$_POST[username]', '$_POST[password]', '$_POST[bday]', '$gender', '$_POST[country]', '$_POST[phone]', 'address', '0')")


or die("The username already exist");

that i need to apply some condition on it , sth like...

if (mysql_query done inserting successfully){
// do 1-
// 2-
// 3-
// 4-
}

else {die("The username already exist");
//and do 
// 1-
// 2-
// 3-
// 4-

}

by the wayI set the username as unique in mysql database so will give an error if someone want to insert sth similar and i catch it as user already exist.

how can i do this?

If you hit a unique key constraint in MySQL, it will throw an error, causing PHP to throw an error, which then shows up in your logs, meaning you forgot to do something in your code. You should do a separate SELECT query to determine if the user already exists (validation) before attempting the INSERT statement.

Use of the mysql_* functions is discouraged. You should learn to use MySqli or PDO. However, I'll just answer your question.

$qry = mysql_query("...");
if ($qry)
{
    //do 1-2-3-4
}
else
{
    //did not insert
}

And you could do a query checking if the user already exists, before you insert anything.

You should sanitize and clean those $_POSTS.

If you want to find if the username exists, you need to do a select statement beforehand

SELECT * FROM user WHERE username = 'xxx'

Once you run that query, check if username exist by counting the number of rows return using mysql_num_rows (or mysqli_num_rows).

$result = mysql_query("SELECT * FROM user WHERE username = 'xxx'", $link);
$num_rows = mysql_num_rows($result);
if ($num_rows == 0) {
    mysql_query("INSERT INTO user (id,f_name,l_name,email,user_name,password,b_day,gender,country,p_number,address,active) VALUES ('NULL','$_POST[fname]','$_POST[lname]','$_POST[email]','$_POST[username]','$_POST[password]','$_POST[bday]','$gender','$_POST[country]','$_POST[phone]','address','0')")
} else {
    die("The username already exist");
}

Suggestion:

  • use mysqli instead of mysql
  • escape the input given to insert into DB using mysqli_real_escape_string (http://www.php.net/manual/en/mysqli.real-escape-string.php)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM