Arthi Arthi - 4 years ago 136
PHP Question

duplicate entry on database using php

how to check for duplicate entry on a form using php?my front end is c#windows application

I am adding a new user to database using c# and php file.

I have created the following:

my project in c# (form1):

c# coding:

private void btncreate_Click(object sender, EventArgs e)
{
var request = (HttpWebRequest)WebRequest.Create("http://***.**.***.***/response.php");
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/x-www-form-urlencoded";
using (var stream = request.GetRequestStream())
{
var buffer = Encoding.UTF8.GetBytes("userid= " + txtUserid.Text + " & password=" + txtConformpassword.Text + " & first_name=" + txtFirstname.Text + " & last_name=" + txtLastName.Text + "& role= " + cmbRole.Text + "& active=" + cmbActive.Text + "");
stream.Write(buffer, 0, buffer.Length);
}
var response = (HttpWebResponse)request.GetResponse();
string result = String.Empty;
using (var reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
txtMessage.Text = result;
}


my PHP file :response.php

<?php
$uid = $_POST['userid'];
$pass = $_POST['password'];
$fname = $_POST['first_name'];
$lname = $_POST['last_name'];
$rol = $_POST['role'];
$act = $_POST['active'];

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql= "INSERT INTO aster(userid,password,first_name,last_name,role,active)
VALUES('$uid', '$pass', '$fname','$lname','$rol','$act');";

if ($conn->query($sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>


it add data successfully but when i enter the same userid in textbox and click create button i need to get an error message in txtmessage as userid already exists.

i search through googling but i did not got any thing about duplicate entry please refer me some coding

Answer Source

You could extend your response.php to do a select statement before the insert. If you are able to select a record with the given ID, then yield a response (essentially an error code) which your C# application will then interpret and display to the user.

As a side note, since the ID field appears to be numeric, you can simply omit it from your form and let the DB increment it automatically. This would also mean that the user will not have to guess which ID values are available.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download