duplicate entry on database using php - c#

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

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.

you just want that the ID which you have entered should not be inserted at the next time . for that you just need to do one thing. make your id as a primary key in your database table creation , after doing this you will be not able to insert that id again or duplicate entries are not allowed in a primary key.
lemme know if it is useful.

It may not help as much, but I think my explanation will point you to the right direction.
What I would do is:
I would use SQL query to check if record exist and if exist then print "Record Exists" Else "Record does not exist". Below the code I post, 'Justin Yen' on PHP posting a quote, make sure you assign that to the field of inputting the username. In your case it's $uid.
On PHP, assign the result of sql query to a variable.
Create a string variable "Record Exists" and "Record does not exist".
compare the string variable you create on step 3 to the result on step 2.
I don't know any PHP coding, but you can try to find a way to compare string. But here's an example of checking record exist in SQL:
Declare #Username varchar(MAX) = 'Justin Yen'
IF EXISTS(select Username from EmployeTable where Username = #Username)
begin print 'Record Exists' end
else
begin print 'Record does not exist' end
Now all you have to do is if variable match then prompt "Cannot create record because Record created." Else use the add record codes you have in php.

You can simply try to add the contraints(UNIQUE/PRIMARY) to the column 'userid'.
ALTER TABLE aster ADD CONSTRAINT MyUniqueKey UNIQUE KEY(userid)

Related

Trying to insert SQL row from C#, throws exception: 'System.Data.SqlClient.SqlException'

I'm very much a novice with C# to SQL interaction so apologies if the problem here is obvious or a duplicate. I'm trying to insert a new row into the table 'Clientes', the first part of this code connects to the database, then checks the table for duplicates, I know those parts work. I included it just in case maybe the problem maybe comes from my connection string or something.
Once it gets to the Try Catch, it throws up the "Error" message I put in there, so I know the failure is happening while inserting.
Usually I can work things like this out based on info from the error message but this is only giving me
[Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll]
in the output tab, nothing in the error list and no further details that I can find, and I've been unable to deduce the problem based on similar SO posts.
if ( textBox_tel.Text.All(c => char.IsDigit(c))) //checks no letters in phone number
{
string connectionstring;
SqlConnection con;
connectionstring = #"Data Source = DRAGONSLAYER;Initial Catalog=bancodb;User id=bancodb_admin;Password=admin";
con = new SqlConnection(connectionstring);
con.Open(); //now connected to the DB
string querysignupsubmitcheck = "Select * from Clientes Where Login = '" + textBox_usr.Text + "'";
SqlDataAdapter sda_signupsubmitcheck = new SqlDataAdapter(querysignupsubmitcheck, con);
DataTable dtbl_signupsubmitcheck = new DataTable();
sda_signupsubmitcheck.Fill(dtbl_signupsubmitcheck);
con.Close();
if (dtbl_signupsubmitcheck.Rows.Count < 1) //checks the new client row isn't a duplicate
{
try
{
string querysignupsubmit = "Insert into Clientes (Nombre, Telefono, Login, Password) Values (" +
textBox_name.Text + ", " +
textBox_tel.Text + ", " +
textBox_usr.Text + ", " +
textBox_pword2.Text + ")";
SqlCommand sc_signupsubmitc = new SqlCommand(querysignupsubmit, con);
sc_signupsubmitc.ExecuteNonQuery();
this.Close();
objform_login.Show();
}
catch { label_alert.Text = "ERROR DE BASE DE DATOS"; }
}
else
{
label_alert.Text = "usuario ya existe";
}
}
else
{
label_alert.Text = "Telefono acepta solo numeros";
}
based on something suggested on another question here, I changed the code inside the try-catch statement to this, but it still throws the same exception:
using (con)
{
string querysignupsubmit = "INSERT INTO Clientes (Nombre, Telefono, Login, Password) VALUES (#val1, #val2, #val3, #val4)";
using (SqlCommand sc_signupsubmit = new SqlCommand())
{
sc_signupsubmit.Connection = con;
sc_signupsubmit.CommandText = querysignupsubmit;
sc_signupsubmit.Parameters.AddWithValue("#val1", textBox_name.Text);
sc_signupsubmit.Parameters.AddWithValue("#val1", textBox_tel.Text);
sc_signupsubmit.Parameters.AddWithValue("#val1", textBox_usr.Text);
sc_signupsubmit.Parameters.AddWithValue("#val1", textBox_pword2.Text);
con.Open();
sc_signupsubmit.ExecuteNonQuery();
con.Close();
this.Close();
objform_login.Show();
}
}
Any help or suggestions are appreciated, this is the code for the table I'm trying to insert into:
CREATE TABLE [dbo].[Clientes] (
[ClienteID] INT IDENTITY (1, 1) NOT NULL,
[Nombre] VARCHAR (255) NOT NULL,
[Telefono] VARCHAR (20) NOT NULL,
[Login] VARCHAR (255) DEFAULT ('default_login') NOT NULL,
[Password] VARCHAR (128) NOT NULL,
CONSTRAINT [PK_Clientes] PRIMARY KEY CLUSTERED ([ClienteID] ASC)
);
EDIT:
Here is the full output and error list tabs, the exit message is from me closing it
EDIT2: I am dumb and declared Val1 multiple times, dumb dumb. Thanks for all the help y'all.
I added a breakpoint (right click inside a pair of brackets if you're using VSC) to my Catch statement as #Jamiec suggested. Then, while poking around with the debugging tabs, I found on the Watch tab to the left of the output I can keep track of a value in realtime. So I added the ex exception to the Watch and this message came up:
{"The variable name '#val1' has already been declared. Variable names must be unique within a query batch or stored procedure.\r\nMust declare the scalar variable "#val2"."}
I had accidentally declared val1 like four times in a row in my SqlCommand and somehow failed to notice it on multiple read-throughs.

insert into database value showing blank

I am currently making a Register Page, I coded the layout with html, and I get value from the html input(<input)
and insert into database. It did sucessfully inputed into the database but when I "select * from dbo.user" the value are showing blank
<?php
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("mydbname")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT id as userid, fullname, userstatus
FROM sometable
WHERE userstatus = 1";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
// then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
echo $row["userid"];
echo $row["fullname"];
echo $row["userstatus"];
}
mysql_free_result($result);
?>
SOURCE: http://au2.php.net/manual/en/function.mysql-fetch-assoc.php

no result on select query using Npgsql and c#

I tried to search a lot for tutorials on Npgsql and c#. but I couldn't resolve the below problem.
When I run the program, my programs stop and breaks at execute query. and when I try debug and check the return value from the execute reader is empty.
below is the sample code:
string user=textBox1.Text;
NpgsqlConnection dataconnect = new NpgsqlConnection(
"Server=127.0.0.1;Port=5432;User Id=dbuser;Password=dbpass;Database=dbname;");
string query = "Select USERNAME from helperdata.credentials where USERNAME = "
+ textBox1.Text + " and PASSWORD = " + textBox2.Text;
dataconnect.Open();
NpgsqlCommand command = new NpgsqlCommand(query, dataconnect);
NpgsqlDataReader reader = command.ExecuteReader();
if(reader.Read())
{
MessageBox.Show("Login Successful");
}
else
{
MessageBox.Show("Login failed");
}
reader.Close();
dataconnect.Close();
When I try to run the below query in Pgsql it returns the data.
Select "USERNAME" from helperdata.credentials where "USERNAME" = 'admin'
I am new to Npgsql.
I would also like if someone could provide me some good tutorial sites which provides detail explanation of Npgsql and C#.
Thanks in advance.
I have identified two problems in your code. The first the usage of uppercase letters on PostgreSQL identifiers. PostgreSQL allows identifiers with other than simple lowercase letter, but only if you quote them.
In fact, you can use, for instance:
CREATE TABLE helperdata.credentials (... USERNAME varchar, ...);
But PostgreSQL will convert it to:
CREATE TABLE helperdata.credentials (... username varchar, ...);
So, to make it really left with uppercase, you have to quote it as following:
CREATE TABLE helperdata.credentials (... "USERNAME" varchar, ...);
And that seems to be the way you have created your table, and the problem with that is that always you refers to that table in a query, you'll have to quote it. So the beginning of your query should be:
string query = "Select \"USERNAME\" from helperdata.credentials ... ";
My recommendation, is to modify your column and table names to don't use such identifiers. For this case you can do:
ALTER TABLE helperdata.credentials RENAME COLUMN "USERNAME" TO username;
The second problem, is the lack of string quotation when you concatenated the username from the textbox into the query. So, you should do something as the following (BAD PRACTICE):
string query = "Select \"USERNAME\" from helperdata.credentials where \"USERNAME\" = '"
+ textBox1.Text + "' and \"PASSWORD\" = '" + textBox2.Text + "'";
There is a huge problem with that, you can have SQL injection. You could create a function (or use one from Npgsql, not sure if there is) to escape the string, or, more appropriately, you should use a function that accept parameters in the query using NpgsqlCommand, which you can simple send the parameters or a use a prepared statement.
Check the Npgsql documentation, and find for "Using parameters in a query" and "Using prepared statements" to see examples (there are no anchors in the HTML to link here, so you'll have to search).

Check if data exists in database

I am creating a login system using c#. I want to check if the username the user enters is already part of the database. This is the code that connects to a data adapter and then updates this once I have taken the data from the check boxes.
NorthwindDataSetTableAdapters.CustomersTableAdapter north = new NorthwindDataSetTableAdapters.CustomersTableAdapter();
NorthwindDataSet.CustomersDataTable northtable = north.GetData();
NorthwindDataSet northwindDataSet1 = new NorthwindDataSet();
NorthwindDataSet.CustomersRow newCustomersRow =
northwindDataSet1.Customers.NewCustomersRow();
newCustomersRow.Username = TextBox1.Text.ToString();
newCustomersRow.Password = TextBox2.Text.ToString() ;
newCustomersRow.FirstName = TextBox3.Text.ToString();
newCustomersRow.Surname = TextBox4.Text.ToString();
northwindDataSet1.Customers.Rows.Add(newCustomersRow);
north.Update(northwindDataSet1.Customers);
northwindDataSet1.Customers.AcceptChanges();
if (Page.IsValid)
Response.Redirect("thankyou.aspx");
What is the best way to check the Username field for duplicate data?
Call me crazy, but I'd just do something like (using "dapper")
string username = ...
int existingId = connection.Query<int?>(
#"select top 1 Id from Users where UserName = #username",
new { username }).FirstOrDefault();
if(existingId.HasValue) {
// not available - do something
}
Note that there is a race condition here so you should still have a unique constraint on the column itself. You might also want to thing about case sensitivity: is "Fred" the same username as "fred"?
Why not to mark the table Column as primary key or unique? Then you handle the exception inside a try{}catcht{} statement.
Have you tried using DataTable.Select? Something like:
var UserFound = NorthTable.Select("UserName = '" + TextBox1.Text + "'");
if(UserFound.Length != 0)
{
// do something...
}

How to check if ID exists in database table in C#?

I am trying to delete entries by ID. I want to notify user that ID they try to delete doesn't exist. It doesn't create any problems, but I want to make everything clear.
How to do that? Do I have to use SQL string to do so?
I am using MS Access 2007 and this is how I delete item:
string SQL = "DELETE FROM PersonalData WHERE DataID = " + txtEntryID.Text;
private void DeleteData(string SQL)
{
// Creating an object allowing me connecting to the database.
// Using parameters in command will avoid attempts of SQL injection.
OleDbConnection objOleDbConnection = new OleDbConnection();
// Creating command object.
objOleDbConnection.ConnectionString =
"Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=" + filePath + ";" +
"Persist Security Info=False;" +
"Jet OLEDB:Database Password=" + pass + ";";
OleDbCommand objOleDbCommand = new OleDbCommand();
objOleDbCommand.CommandText = SQL;
// Assigning a connection string to the command.
objOleDbCommand.Connection = objOleDbConnection;
try
{
// Open database connection.
objOleDbConnection.Open();
objOleDbCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
// Displaying any errors that
// might have occured.
MessageBox.Show("Error: " + ex.Message);
}
finally
{
// Close the database connection.
objOleDbConnection.Close();
}
// Refreshing state of main window.
mainWindow.DisplayFileContent(filePath);
MessageBox.Show("Data was successfully deleted.");
// Clearing text box field.
txtEntryID.Clear();
}
In VBA code, you could use the DCount() function.
You can also just delete the records with a SQL statement and inform the user after the fact; from the user's point of view there's no difference:
Dim id As Long
id = GetAnIdFromTheUser()
With CurrentDb
Do
.Execute "DELETE FROM [TableName] WHERE ID = " & id
If .RecordsAffected > 0 Then
Goto Done
End If
MsgBox "That ID doesn't exist; please try another."
id = GetAnIdFromTheUser()
Loop
Done:
.Close
End With
EDIT:
In ADO.NET you can follow the same approach by examining the return value of ExecuteNonQuery. For example, you could declare your function as bool TryDeleteData(string SQL) and do something like
...
if (objOleDbCommand.ExecuteNonQuery() == 0)
return false;
...
You could use the DCount function of VBA:
DCount("*", "SomeTable", "ID = 1")
If this is 0 then you know the record doesn't exist and can inform the user.
Your question isn't clear enough, so I'm guessing that what you'd like to do is execute the DELETE query and then return whether records were deleted or not. If that's what you want to do you could do it like this:
DECLARE #deletedID AS INT
SELECT #deletedID = id FROM your_table WHERE id = <the id supplied by user>
DELETE FROM your_table
WHERE your_table.id = <the id supplied by user>
RETURN #deletedID
If the requested ID does not exist this will return NULL
EDIT
Based on the clarification in your comments, the following query should work just fine:
SELECT COUNT(DataId) as Cnt
FROM PersonalData WHERE DataId = <user_specified_id>
This query will produce a single column, single row result set (i.e. a scalar-value). The value is going to be either 1 or 0 (assuming only one entry may have the same id). If the count is 0 the entry does not exist.
P.S.
The way you are executing the query you're opening yourself to SQL injection attacks. Basically, someone could give you the following DataID: 0 OR 1 = 1 and guess what's going to happen - all the PersonalData records will be deleted!
A much better approach would be to use prepared statements. Or at the very least, make absolute sure that you sanitize and validate the user input before concatenating it into the query text.

Categories