1

I need to prevent duplicate student number in my SQL database. I don't know where to insert the php code to do that.

/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/

// array for JSON response
$response = array();

// check for required fields
if (isset($_POST['name']) && isset($_POST['studnum']) && isset($_POST['password'])) {

$name = $_POST['name'];
$studnum = $_POST['studnum'];
$password = $_POST['password'];

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// mysql inserting a new row
$result = mysql_query("INSERT INTO products(name, studnum, password)     VALUES('$name','$studname', '$password')");

// check if row inserted or not
if ($result) {
    // successfully inserted into database
    $response["success"] = 1;
    $response["message"] = "Product successfully created.";

    // echoing JSON response
    echo json_encode($response);
} else {
    // failed to insert row
    $response["success"] = 0;
    $response["message"] = "Oops! An error occurred.";

    // echoing JSON response
    echo json_encode($response);
}


} 
else
{
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";

// echoing JSON response
echo json_encode($response);
}
?>
1
  • please ignore the comments in the code since i only edit it thanks a lot Commented Aug 19, 2013 at 10:48

2 Answers 2

2

add unique to some of the columns which you think can make unique record, then

$result = mysql_query("INSERT INTO products(name, studnum, password)     VALUES('$name','$studname', '$password') ON DUPLICATE KEY UPDATE studnum=VALUES(studnum)");

It will update the record and prevent you from showing duplicate error.

Sign up to request clarification or add additional context in comments.

1 Comment

You’re right : Its important to avoid MySQL error. In most cases, Php will ignore it but with ajax, the MySQL error could be an issue when using a callback function.
0

Run the following SQL statement in your db

alter table products add unique index(studnum);

This will tell mySQL that the studnum field should be unique and will cause it to give an error message if a duplicate is created.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.