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)
Related
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
Looks like I'm connecting to the server just fine. The problem seems to happen when it runs the query. It keeps saying
Error Querying Database
Here is my code:
<?php
$dbc = mysqli_connect('localhost', 'elvis_store')
or die('Error connecting to MySQL server.');
$first_name = $_POST['firstname'];
$last_name = $_POST['lastname'];
$email = $_POST['email'];
$query = "INSERT INTO email_list (first_name, last_name, email)" .
"VALUES ('$first_name', '$last_name', '$email')";
mysqli_query($dbc, $query)
or die('Error querying database.');
echo 'Customer added.';
mysqli_close($dbc);
?>
You are getting this error because in your MySQLi connection you only give a location and username. You do not give a database name to be used. if you have no password, you need to write your connection like this:
$dbc = mysqli_connect('localhost', 'elvis_store', NULL, 'dbName)
or
$dbc = mysqli_connect('localhost', 'dbUsername', NULL, 'elvis_store')
if "elvis_store" is the database name and not the username. Remember, a mysqli connection is: mysqli_connect(dbLocation, dbUsername, dbPassword, dbName).
Also, as Ed has pointed out in another answer, there is also a syntax error in your MySQL statement. Here is the snippet from Ed's answer:
$query = "INSERT INTO email_list (first_name, last_name, email) " . "VALUES ('$first_name', '$last_name', '$email')";
You have multiple problems.
Problem 1: Syntax error
Your query has a typo (a missing space). Your query code
$query = "INSERT INTO email_list (first_name, last_name, email)" .
"VALUES ('$first_name', '$last_name', '$email')";
produces this query:
INSERT INTO email_list (first_name, last_name, email)VALUES ('$first_name', '$last_name', '$email')
-- ^ syntax error, missing space
To fix it, change your code to this:
$query = "INSERT INTO email_list (first_name, last_name, email) " .
"VALUES ('$first_name', '$last_name', '$email')";
At least for testing purposes, you probably should look at the output of mysqli_error() instead of using a generic message like Error querying database. Even in production, you'll want to trap and log the real error somehow.
Problem 2: You don't select a database
Edit: I missed this in my first glance at your question, but as Stephen Cioffi points out, you also need to select a database before running your query. You can do this with the schema parameter to mysqli_connect() or by using mysqli_db_select().
Both of these issues—the typo and the failure to select a database—will cause problems; you must fix both.
Problem 3: Huge SQL Injection Vulnerability
This is not strictly part of the answer, but it's important. You are wide open to SQL injection. You need to use prepared statements. Otherwise, you are going to get hacked. Imagine that the POSTed firstname is this:
', (SELECT CONCAT(username, ',', password) FROM users WHERE is_admin = 1), 'eviluser#example.com') --
Your query becomes (with some added formatting):
INSERT INTO email_list (first_name, last_name, email)
VALUES ('',
(SELECT CONCAT(username, ',', password) FROM users WHERE is_admin = 1),
'eviluser#example.com'
) -- ', 'value of lastname', 'value of email')
Then, when you email your users, somebody's going to get an email with a recipient like
"Duke,mySup3rP#ssw0rd!" <eviluser#example.com>
And... you're hosed.
(Hopefully, you're salting and hashing passwords, but still, this is disastrous.) You must use prepared statements.
Below is my php code, which should take the data from my form and put it into two tables in my database. However I keep getting an SQL syntax error by the values, I was originally putting the values in ' ' however I got the error so then I changed the values to backticks . But that still didnt seem to make much difference. Im receiving the error, however street, city, county, postcode, tel and date of birth are all inputting into the users table. But nothing else, and nothing is going into the members table.
Any help would be greatly appreciated. Many thanks
$con = mysql_connect("localhost", "alex", "");
if(!$con)
{
die('Could not connect: ' .mysql_error());
}
mysql_select_db("gym", $con);
//** code above connects to database
$sql ="INSERT INTO users (First_Name, Last_Name, Street, City, County, Postcode, Telephone, Email, Date_Of_Birth, Gender)
VALUES
(`$_POST[FirstName]`,
`$_POST[LastName]` ,
`$_POST[Street]`,
`$_POST[City]`,
`$_POST[County]`,
`$_POST[Postcode]`,
`$_POST[Tel]`,
`$_POST[Email]`,
`$_POST[Date_Of_Birth]`,
`$_POST[Gender]`)";
$result1=mysql_query($sql,$con);
$sql1 = "INSERT INTO members( Membership_Number, Membership_Type, Membership_Referal, Trainer_Required, Medical_Informaton, Contract, Card_Holder_Name, Bank, Card_Number, Sort_Code, valid, Exp, Security_Number
VALUES
(`$_POST[MembershipNumber]`,
`$_POST[MembershipType]`,
`$_POST[MembershipReferral]`,
`$_POST[TrainerRequired]`,
`$_POST[MedicalInformation]`,
`$_POST[Contract]`,
`$_POST[BankBranch]`,
`$_POST[CardHolderName]`,
`$_POST[CardNUMBER]`,
`$_POST[Expiry]`,
`$_POST[SecurityCode]`)";
$result2=mysql_query($sql1,$con);
//***** code below is error message if it doesnt work
if($result1 && $result2){
printf("window.alert(\"New Record Added!\");");
}
else
{
echo "Error:". mysql_error()."";
}
mysql_close($con)
?>
Remove backtics and add `single quote` to values parameter
User SQL query like.
$sql = "INSERT INTO users (First_Name, Last_Name) VALUES('".$_POST[FirstName]."','".$_POST[LastName]."')";
You must pass parameter between {$_POST['variable']} like this:
$sql1 = "INSERT INTO members( Membership_Number, Membership_Type, Membership_Referal, Trainer_Required, Medical_Informaton, Contract, Card_Holder_Name, Bank, Card_Number, Sort_Code, valid, Exp, Security_Number
VALUES
(`{$_POST['MembershipNumber']}`,
`{$_POST['MembershipType']}`,
`{$_POST['MembershipReferral']}`,
`{$_POST['TrainerRequired']}`,
`{$_POST['MedicalInformation']}`,
`{$_POST['Contract']}`,
`{$_POST['BankBranch']}`,
`{$_POST['CardHolderName']}`,
`{$_POST['CardNUMBER']}`,
`{$_POST['Expiry']}`,
`{$_POST['SecurityCode']}`)";
please use ' not use `
just like
'$_POST[value]', ........, ........
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)
I'm having trouble with the following code:
$sql= "INSERT INTO Users(Username, Password, Lastname, Email) VALUES
('$hash', '$lastname', '$email', '$email')";
mysqli_query($MyConnection, $sql);
if(!mysqli_query($MyConnection, $sql)) {
echo 'We are sorry, there are some problems with saving your data. Please try again within a few minutes.';
}
else {
echo 'We have succesfully saved your data. An activation e-mail will now be send to the e-mail address that you
have provided us.';
}
I get no direct errors as due to mistyping or misusing a function. I do get however the message of the if-statement in a failure, the "We are sorry(..)" text.
There must be a problem with the execution of the mysqli_query($MyConnection, $sql) function. But I don't see where it is.
P.S. I can't post images, because my reputation is below 10. (Which is quite weird to limit it to that point)
As some of you have provided most / all of the code:
<?php
// Opens the connection of the MySQL Database
$MyConnection = mysqli_connect('fdb6.biz.nf', '1446018_amp', '-')
or die("Could not connect to the database, please try again");
mysqli_select_db($MyConnection,'Users');
mysqli_connect_errno();
// Website Url:
$website = 'http://www.askmephilosophy.co.nf/';
// Information provided by the user
$username = $_POST['username'];
$password = $_POST['password']; // Will get encrypted.
$lastname = $_POST['lastname'];
$email = $_POST['email'];
// A higher "cost" is more secure but consumes more processing power
$cost = 5;
// Create a random salt
$salt = strtr(base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)), '+', '.');
// Prefix information about the hash so PHP knows how to verify it later.
// "$2a$" Means we're using the Blowfish algorithm. The following two digits are the cost parameter.
$salt = sprintf("$2a$%02d$", $cost) . $salt;
// Hash the password with the salt
$hash = crypt($password, $salt);
$sql= "INSERT INTO Users(Username, Password, Lastname, Email) VALUES
('$hash', '$lastname', '$email', '$email')";
mysqli_query($MyConnection, $sql);
var_dump(mysqli_error($MyConnection));
if(mysqli_query($MyConnection, $sql)) {
echo 'We have succesfully saved your data. An activation e-mail will now be send to the e-mail address that you
have provided us.';
}
else {
echo 'We are sorry, there are some problems with saving your data. Please try again within a few minutes.';
mysqli_error($MyConnection);
}
mysqli_close($MyConnection);
?>
$sql= "INSERT INTO Users(Username, Password, Lastname, Email) VALUES
('$hash', '$lastname', '$email')";
This is your first issue; your table has four columns, and you're passing it three. This query is guaranteed to fail.
mysqli_query($MyConnection, $sql);
if(!mysqli_query($MyConnection, $sql)) {
You're calling the query function twice. You can do this with a single call:
if(!mysqli_query($MyConnection, $sql)) {
// add some error handling code here
// store the return value of mysqli_error() somewhere
echo 'We are sorry, there ar....';
Since you're using mysqli_, you should also be using prepared statements; I hope at least you're sanitising the database inputs before you try to add them to the database.
Why do you only have 3 values, it doesn't match the number of items you are trying to Insert (4) ...
$sql= "INSERT INTO Users(Username, Password, Lastname, Email) VALUES
('$username', '$hash', '$lastname', '$email')";
EDIT:
I would probably write it like this
$sql= "INSERT INTO Users(Username, Password, Lastname, Email) VALUES
({$username}, {$hash}, {$lastname}, {$email})";
EDIT:
Your password cannot be '-'
I would update your connection info like so:
$db = new mysqli('fdb6.biz.nf', 'user', 'pass', 'Users');
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
EDIT AGAIN:
$myConnection = new mysqli('fdb6.biz.nf', 'user', 'pass', '1446018_amp');
$myConnection->mysqli_select_db($MyConnection,'Users');
try adding, I think you forgot this. Values always have to equal to columns
$sql= "INSERT INTO Users(Username, Password, Lastname, Email) VALUES
('$username', '$hash', '$lastname', '$email')";
First of all you are inserting twice that records, as there are two instances of mysqli_query($MyConnection, $sql);. You can just remove the first.
The problem here is that you are inserting 3 values in 4 fields.
Anyway you can get the specific error with
mysqli_error($MyConnection);
Add it at the end your echo forever or var_dump(mysqli_error($MyConnection)); in a new line.