Duplication of record on insert in php, mysql - php

I notice sometimes that there are duplicated data when inserting in the database. It doesn't always happen but what might be the issue here? Here is my code.
$sql = $conn->query("INSERT INTO registration(lrn, department_id, fname, mname, lname, contact_no, email, persontocontact, emergency_contact, agreement, statuss) VALUES('".$_POST['userid']."','".$_POST['departmentid']."', '".$_POST['fname']."', '".$_POST['mname']."', '".$_POST['lname']."', '".$_POST['contact_no']."','".$_POST['email']."', '".$_POST['persontocontact']."', '".$_POST['emergency_contact']."', '".$_POST['agreement']."', 'pending')");
if($sql->rowCount() > 0){
echo "success";
}

It only happens sometimes means it is not the code that is doing it but the user actions like refresh on that page.
You should make it much more secure and handle the refresh situation but to answer to your question use this code.
$checkid = $_POST['userid'];//Specifically taking it here so you can know this is what we are looking for.
$sql = $conn->query("Select * from registration WHERE lrn = '$checkid'");
if($sql->rowCount() > 0){
echo "User Already Exists";
}
else
{//Move forward
$sql = $conn->query("INSERT INTO registration(lrn, department_id, fname, mname, lname, contact_no, email, persontocontact, emergency_contact, agreement, statuss) VALUES('".$_POST['userid']."','".$_POST['departmentid']."', '".$_POST['fname']."', '".$_POST['mname']."', '".$_POST['lname']."', '".$_POST['contact_no']."','".$_POST['email']."', '".$_POST['persontocontact']."', '".$_POST['emergency_contact']."', '".$_POST['agreement']."', 'pending')");
if($sql->rowCount() > 0){
echo "success";
}
}//Main if closes here

Related

Cannot insert data in SQL table when using the same code as previous query

I need to insert two pieces of data into two different tables. It successfully does it with one of the tables but not the second. I have used or die mysqli_error to see if it will tell me the error, but it does not show anything. See the code below:
$sql = "INSERT INTO ticketUsers
(name, emailAddress, password)
SELECT * FROM (SELECT '$name', '$emailAddress', '$dbPassword') AS tmp
WHERE NOT EXISTS (
SELECT name
FROM ticketUsers
WHERE emailAddress = '$emailAddress'
)
LIMIT 1";
$query = mysqli_query($connection, $sql);
if($query)
{
echo "Success entering ticket Users";
}
else if(!$result)
{
echo "Cant enter information";
}
$sql = "INSERT INTO tickets
(id, emailAddress, urgency, subject,
description, relevantURL, status)
VALUES ('$id', '$emailAddress', '$username', '$urgency',
'$subject', '$description2', '$relevantURL', 'Open')";
$query = mysqli_query($connection, $sql);
if($query)
{
echo "Success entering tickts";
}
else if(!$result)
{
echo "Cant enter information";
}
if (!sql)
{
echo "There has been an error creating your ticket.";
}
In your second query, you try to insert in a table with 7 fields 8 values.
I think you don't want to insert '$username' in the query.

PHP/MySQLi Not finding existing user

For some reason, the code seems to not be able to find any existing usernames. I can't find anything wrong with my code though. Any help will be appreciated.
$Name = $_POST["User"];
$Pass = $_POST["Pass"];
$get = "SELECT * FROM Logins";
$result = mysqli_query($conn, $get);
$found = false;
echo $Name;
$sql=mysqli_query("SELECT FROM Logins (ID, Username, Password) WHERE Username=$Name");
if(mysqli_num_rows($sql) > 0) {
echo "Username Taken";
} else {
$sql = "INSERT INTO Logins (ID, Username, Password) VALUES (0, '$Name', '$Pass')";
if (mysqli_query($conn, $sql)) {
echo "Account Created";
} else {
echo mysqli_error($conn);
}
}
When I post to the site, $Name is correct.
You have an incorrect syntax near your select statement. It's
SELECT FROM Logins (ID, Username, Password) WHERE Username=$Name")
You need:
SELECT ID, Username, Password
FROM Logins
WHERE Username='$Name'
Also note, you should be using prepared statement which will avoid need for quotes and will avoid your code vulnerable from SQL Injection.

Check if name already exist

I have this code.
This code can check if form number is already existing in the database.
Now i want to check if the firstname and lastname is already existing.what and where should i
$FNresult = mysql_query("SELECT COUNT(*) FROM profile WHERE FormNo = '$FrmN' ");
if (!$FNresult) {
die(mysql_error());
}
if (mysql_result($FNresult, 0, 0) > 0) {
echo "<br>Form number already exist!";
}
else {
$sql = "INSERT INTO profile
(FormNo, FirstName, LastName, Address, Email, MobileNo,
LandlineNo, Amount, Term, Manner)
VALUES ('$FrmN', '$FN', '$LN', '$ADD', '$E', '$MOBILE',
'$LAND', '$AMNT', '$TRM', '$MNNR')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "<br>1 record added!";
}
mysql_close($con);
$sql = mysqli_query("SELECT firstname,lastname FROM profile WHERE firstname = '$firstname' and lastname = '$lastname'");
$rownum = mysqli_num_rows($sql);
if( $rownum > 0 )
die('Your name already exists in database');
Note = I wrote mysqli_* but you are using mysql_*
You can change it depending on how you want it to be.
You should change your mysql_* to mysqli_* as the first one has been deprecated and will be deleted in the future
Something similar to the code above must do the trick.
Good Luck

Unique user id code in php doesnt work

Recently i was searching for unique username registration using php.. I came across a piece of code which i am displaying below:
<?php
$fname=trim($_POST['fname']);
$lname=trim($_POST['lname']);
$email=trim($_POST['email']);
$usn=trim($_POST['usn']);
$dept=trim($_POST['dept']);
$pass=trim($_POST['pass']);
$tel=trim($_POST['tel']);
$dbh = mysql_connect('localhost', 'root','') or die("<h3 style=\"color:red;\" align=\"center\">SERVER ERROR</h3>");
mysql_select_db('fy') or die("<h3 style=\"color:red;\" align=\"center\">SERVER ERROR</h3>");
$error= mysql_query("SELECT * FROM stud WHERE email='$email' OR usn='$usn' OR tel='$tel'") or die (mysql_error());
if (mysql_num_rows($error) > 0);
{
die ("Sorry! Either email, usn or tel already exists!");
}
$query="INSERT INTO stud (fname, lname, email, tel, usn, dept, pass) VALUES ('$fname', '$lname', '$email', '$tel', '$usn', '$dept', '$pass')";
mysql_query($query);
$query="INSERT INTO log VALUES ('$usn','$pass',0,0)";
mysql_query($query);
print("REGISTERED");
?>
LOGIN<br />
At this moment my database is completely empty. I've just created the database stud with the desired columns. Now the problem is when i try to register using my registration page, it gives me the error i specified in die that is
"Sorry! Either email, usn or tel already exists!"
How is this possible if there are no values in the database. In the registration form I've given
action="register.php"
as a processing file. Also I've tried with mysql_fetch_assoc(), but i get the same error. Any help is appreciated. Thank you .
Your first problem is that, as John Conde states, your code is vulnerable to SQL injection attacks.
Your second problem, and to answer your question, is probably because you have this:
if (mysql_num_rows($error) > 0);
instead of this:
if (mysql_num_rows($error) > 0)

Using select count to verify values between 2 tables

Please i want a select count statement to retrieve value from a table row and verify it against another table row using php.
meaning
Hello Guys/Gurus
Please I have an issue, am some months into php and i need your help/assistance.
This is the flow. a client register at another site, when we confirm the registration, we send them a code.
The code is generated and saved in another table name called code and column generated_code.
I develop a form (http://cash2money2020.com/form.html)
So all i want is if someone inputs the generated code we sent to them, and filled it in the form, it makes a database checks to see if the code exists in the other table, if yes, submit form..if not, error message that the code is invalid and the form will not be submitted:
$query = "INSERT INTO registration
(id, fname, lname, address1, address2, city, state, country, email, phone, home_phone, dob, gender, living, qualification, mental, mental_details, criminal, criminal_details, kin_name, kin_phone, kin_relationship, tv_appearance, work_financial, tv_station, why, interesting, impressive, generated_code, submitted_date)
VALUES
('', '$fname', '$lname', '$address1', '$address2', '$city', '$state', '$country', '$email', '$phone', '$home_phone', '$dob', '$gender', '$living', '$qualification', '$mental', '$mental_detail', '$criminal', '$criminal_details', '$kin_name', '$kin_phone', '$kin_relationship', '$tv_appearance', '$work_financial', '$tv_station', '$why', '$interesting', '$impressive', '$code', now()) ";
This is what i have done so far
$result = mysqli_query("select count(generated) from code ");
if (!$result) echo mysqli_error();
$row = mysqli_fetch_row($result);
$query = "INSERT INTO registration (generated_code) VALUES ('$code')";
if ($query != $row) {
//code to submit and process the form
}
else
{
//error message
}
Please help am stucked !!!
something like this should do (according to the last comment):
$link = mysqli_connect("my_host", "my_user", "my_password", "my_db");
$result = mysqli_query($link, "select * from code where generated = '$code'");
if (!$result) die("mysql error: " . mysqli_error());
$row = mysqli_fetch_row($result);
if ( $row !== false ) {
// code to submit and process the form
// you might use the result with $row[<fieldname>]
}
else
{
// error message
}
You need to add some error handling and unescaping values (like $code)

Categories