PHP Registration Script, Inserting to Database not working - php

I have an issue with my PHP code for a registration form on my website. Some of the code doesn't get executed when the form is submitted.
if ($fnameError = "" && $emailError = "" && $userError = "" && $passError = "" && $cpassError = "" && $tickError = "") {
$con = mysqli_connect("localhost","root","","login")or die("Can't connect to database");
$user = $_POST['user'];
$pass = $_POST['pass'];
$name = $_POST['fname'];
$email = $_POST['email'];
$pwd = crypt('$pass', '$user');
$pwd = md5($pwd);
$tblname = "users";
$flp="INSERT INTO $tblname (Name, Username, Password, Email Address)
VALUES
('$name','$user','$pass','$email')";
$res = mysqli_query($con, $flp)or die("Can't insert to table");
if ($res) {
$complete = "Registered successfully please log in to continue";
} else {
echo "error";
}
}
Everything works fine until it gets to the line starting $flp="INSERT INTO...
Can anyone assist in helping me debug this code, also, please don't link to already written code I want to be able to use this code.
EDIT:
I changed a line to purposely cause an error so I know PHP is reading the line and it does give me the syntax error for the line starting $res=mysqli_...
"Parse error: syntax error, unexpected '$res' (T_VARIABLE) in C:\XamppNew\htdocs\site\regusr.php on line 85"
I removed the semi-colon at the end of the Insert line just to get the error.
EDIT:
I've managed to isolate the problem to the start of the if statement. It seems to be that the line doesn't treat each error as having no content. However, if the error exists it will be displayed on the page next to the form and no such error gets displayed.

Try this:
<?php
//if ($fnameError = "" && $emailError = "" && $userError = "" && $passError = "" && $cpassError = "" && $tickError = "")
//{
// Connect to DB
$mysqli = new mysqli("localhost", "root", "", "login");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
// Parse Input
$user = $mysqli->real_escape_string($_POST['user']);
$pass = $mysqli->real_escape_string($_POST['pass']);
$pwd = md5(crypt('$pass', '$user'));
$name = $mysqli->real_escape_string($_POST['fname']);
$email = $mysqli->real_escape_string($_POST['email']);
// Insert Record
if ($mysqli->query("INSERT INTO users (`Name`, `Username`, `Password`, `Email Address`) VALUES ('$name', '$user', '$pwd', '$email')")) {
printf ("New user has id %d.\n", $mysqli->insert_id);
} else {
printf("Failed to insert row: %s\n", $mysqli->error);
}
// Close DB Connection
$mysqli->close();
//}
?>

You need to quote (with backticks) your column name Email Address since it has a space in it.

Use backticks in Email Address field because it has space.
$flp="INSERT INTO $tblname (`Name`, `Username`, `Password`, `Email Address`)

Try this ..........
$flp="INSERT INTO $tblname (Name, Username, Password, EmailAddress)
VALUES
('".$name."','".$user."','".$pass."','".$email."')";

Related

Editing user profile: How to avoid user from entering duplicate values?

I'm a newbie in PHP. I wanted the display warning messages user to avoid entering duplicate values such as username, email and telephone number.
For example, user wants to change their username. When the user submit the form after editing their username, a warning message is display saying that username has already been taken or already exists.
<?php
error_reporting(E_ALL ^ E_NOTICE);
session_start();
include("../config.php");
include("../errors.php");
include("../success.php");
$errors = array();
$successes = array();
if ($_SESSION["uName"]){
if ($_SESSION["uType"] != "admin") {
header("location:../user/dashboard_user.php");
} else if ($_SESSION["uType"] == "admin"){
if(isset($_POST["update"])) {
$fname = $_POST["fname"];
$telno = $_POST["telno"];
$uname = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$password = md5($password);
$sql = "UPDATE users SET fullname = '$fname', telno = '$telno', username = '$uname', email = '$email', password = '$password' WHERE id = '".$_SESSION['uId']."'";
if (mysqli_query($con, $sql)) {
array_push($successes, "Update Success!");
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
}
?>
What is the correct way to use the SELECT statement in the code to get the expected results?
You should really handle the issue in the database:
create unique index idx_username on users(username);
Then in your code do what you do and then simply:
define('MYSQL_UNIQUE_CONSTRAINT_VIOLATION', 1062);
if (mysqli_query($con, $sql)) {
array_push($successes, "Update Success!");
} elsif (mysql_errno() == MYSQL_UNIQUE_CONSTRAINT_VIOLATION ) {
echo "Error: username $username is already taken";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
This code is very crude of course, but it gives you the idea. If your code inside the class, then use const instead of define.
Also, your code is very much liable to SQL injection. Use parametrised query instead of using variable inside the sql string.

Php signup form doesn't work - Form just refreshes when input checks out requirement

The script doesn't throw any error, but if all the input fields are entered correctly, it just refreshs, and nothing happens.
I have included $salt and $link in header.php.
I might have overdid loops, but I spent couple of hrs trying to figure it out before posting it here.
<?php
if (array_key_exists('username', $_POST)||array_key_exists('pass', $_POST)||array_key_exists('email', $_POST)) {
if ($_POST["username"]!== "" && $_POST["email"]!== "" && $_POST["pass"]!== "" && $_POST['cpass']!== "" ){
if($_POST['pass']==$_POST['cpass']){
if (!mysqli_connect_error()) {
$query = "SELECT `username`, `email` FROM `users` WHERE `username` = '".mysqli_real_escape_string($link, $_POST['username'])."' OR `email` = '".mysqli_real_escape_string($link, $_POST['email'])."'";
$result = mysqli_query($link, $query);
if ($row = mysqli_fetch_array($result)) {
if ($row['username'] == $_POST['username']) {
echo "Username already exists!<br>";
//die("Awe! Someone took this username");
}
if ($row['email'] == $_POST['email']) {
echo "Email has been used once!<br>";
//die(":( Email is in use!");
}else if($row['username'] !== $_POST['username'] && $row['email'] !== $_POST['email']){
$email = mysqli_real_escape_string($link, $_POST["email"]);
$username = mysqli_real_escape_string($link, $_POST["username"]);
$pass = md5($salt.mysqli_real_escape_string($link, $_POST["pass"]));
$query = "INSERT INTO `users`( `username`, `pass`, `email`) VALUES ('$username', '$pass', '$email')";
if(mysqli_query($link, $query)){
echo "You were successfully registered";
} else {
echo "Something went wrong, Couldn't register at the moment!";
}
}
}
}else{
echo "An Error Occured while connecting !";
}
}else {
echo "Password didn't match!";
}
}else{
echo "Field(s) can't be left blank!";
}
}
?>
The problem of your code happens on :
if ($row = mysqli_fetch_array($result)) {
and since you didn't place any else for this "if" you don't see anything happens.
The problem is, this condition becomes true only if email or username is already inside the table.
so if given username and/or email is not already in the table, this condition becomes false and therefore it never reaches to inside block where you want to insert the new data.
There is also a side issue with this and lets say your query fetch 2 rows.. imagine this table.
userid - username - email
1 - user1 - user1#test.com
2 - user2 - user2#test.com
now lets say the given input data are
$_POST['username'] = 'user1';
$_POST['email'] = 'user2#test.com';
this will fetch 2 rows in your users table, but as you didn't make a loop you will only check for first row and it might cause bug or unexpected behavior in your script.
UPDATE : I also made a piece of code based on your code.. hope it helps you...
function validateInputs(){
$keys = array('username','pass','cpass','email');
foreach($keys as $key){
if(!isset($_POST[$key]) || empty($_POST[$key])){
throw new Exception("Field(s) can't be left blank!");
}
}
}
function validatePassword(){
if($_POST['pass'] !== $_POST['cpass']){
throw new Exception("Password didn't match!");
}
}
function checkForUniqueInput($email,$username){
global $link;
$query = "SELECT username, email FROM users WHERE username = '".$username."' OR email = '".$email."'";
$result = mysqli_query($link, $query);
if (mysqli_num_rows($result) > 0) {
throw new Exception("Username and/or email already exist");
}
}
function insertNewUser($email,$username,$pass){
global $link;
$query = "INSERT INTO users( username, pass, email) VALUES ('".$username."', '".$pass."', '".$email."')";
if(!mysqli_query($link, $query)){
throw new Exception("Something went wrong, Couldn't register at the moment!");
}
}
if(isset($_POST)){
try{
validateInputs();
validatePassword();
$email = mysqli_real_escape_string($link, $_POST["email"]);
$username = mysqli_real_escape_string($link, $_POST["username"]);
$pass = md5($salt.mysqli_real_escape_string($link, $_POST["pass"]));
checkForUniqueInput($email,$username);
insertNewUser($email,$username,$pass);
echo 'You were successfully registered';
}
catch(Exception $e){
echo 'Error : '.$e->getMessage();
}
}

how to avoid duplicating in php

i am new in terms of php. i am now creating a simple program which is similar as a login page. may you please help me to do my coding, i have mysql table named user which has 3 column userid, email and password. my primary is userid and it is an auto increment. how can i have code which is, the column email should no duplication or no same email. i have already code for avoiding empty fields i don't know now how to do about the duplication..
here is my sample code:
<?php
if(isset($_POST['submit'])){
$dbhost = 'localhost';
$dbuser = 'root';
$conn = mysql_connect($dbhost, $dbuser);
mysql_select_db('dtr');
if(! $conn ){
die('Could not connect: ' . mysql_error());
}
if(! get_magic_quotes_gpc() ){
$email = addslashes ($_POST['email']);
$password = addslashes ($_POST['password']);
}
else{
$email = $_POST['email'];
$password = $_POST['password'];
}
//validation
if($email == ''){
echo "empty ang email" ?></br><?php ;
return false;
}
if($password == ''){
echo "kailangan may password ka\n" ?></br><?php ;
return false;
}
---------------------->//select * table where username=user
{
$sql = "INSERT INTO user "."(email, password) "."VALUES('$email','$password')";
$retval = mysql_query( $sql, $conn );
}
if(! $retval ){
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
}
else
{
}
?>
help me plz..
you can try:
$sql = "SELECT userid from users WHERE email = ". $_POST["email"];
if (mysql_num_rows(mysql_query($sql, $con)) >= 1)
{
echo "That email you provided seems to be already used";
return;
}
And please thing about using a different db extension since mysql is deprecated as of PHP V. 5.5. It will give you better security features with binding and prepared statements.
Simply use this, I think it should give u help:
$name = $_POST[name];
$pass = $_POST[pass];
$user = "SELECT * from users WHERE email = '".$email."'";
$result = mysql_query($user);
if(mysql_num_rows($result)>0){
return "$result";
}
else{
mysql_query("INSERT INTO users(email, pass) VALUES ('$email', '$pass')");
}

registration form not not showing validation error

I am having issues getting the error to appear when a user is entering a user name that is already taken.
In the code below the database is updated when successful entry is made. However, when an entry is made with a duplicate user name, the entry is placed in the database and no error message is shown. I have looked on the net and tried a few methods and this what I have so far. Thank you for taking a look :)
<?php
// Create connection
$con = mysqli_connect('172.16.254.111', "user", "password", "database"); //(connection location , username to sql, password to sql, name of db)
// Check connection
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} //sql syntax below, first line is collumn titles on the db and second line is values from the html document
//$_post is a form of sending information in php
{
$username = strip_tags($_POST['username']);
$password = md5(strip_tags($_POST['pass']));
$password2 = md5(strip_tags($_POST['pass2']));
$fullname = strip_tags($_POST['fullname']);
$email = strip_tags($_POST['email']);
$department = strip_tags($_POST['department']);
if ($password != $password2) //password doestn equal same as password 2 then the message below is displayed (working)
{
echo "<H2>password doesn't match</H2>";
}
$usercheck = "SELECT * FROM Users WHERE username=$username";
$usercheck2 = mysql_query($usercheck);
if (mysql_fetch_assoc($usercheck2)) {
echo "<H2>This username already exists, please pick another</H2>";
} else {
$sql = "INSERT INTO Users(username, password, password2, email, fullname, department)
VALUES('$username','$password','$password2','$email','$fullname','$department')";
if (!mysqli_query($con, $sql)) {
die('Error: ' . mysqli_error($con));
}
echo "<H2>Registration was successful, please use the access console above</H2>";
}
}
?>
Excuse any comments in the code; I am a beginner at PHP and coding in general.
You're missing some quotes. Try this:
$usercheck = "SELECT * FROM Users WHERE username = '$username'";
// ----------------------------------was missing---^---------^
$usercheck2 = mysql_query($usercheck);
if (mysql_num_rows($usercheck2)) {
echo 'user exists';
}
Also, you shouldn't be using the mysql_* functions. Look into using PDO
Change $usercheck = "SELECT * FROM Users WHERE username=$username";
for this $usercheck = "SELECT * FROM Users WHERE username='$username'"; And tell me if it works.

Is there something wrong with the insert.php given below?

I have tried hard to debug the following insert.php file. There are no errors while running this and the associated webform file inwamp server, but it is not reading data to the database. Can someone comment on this?
?php
if (isset($_POST['submit'])) {
//Connect to the database
$host="localhost";
$user="root";
$password="";
$dbc=mysql_connect($host,$user,$password) or die("Connection Error");
$db_name="userregistration";
mysql_select_db("$db_name") or die ("Could not select database");
//Reading data from form and writing to the DB
$fname = $_POST['fname'];
$institution = $_POST['institute'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$pgm = $_POST['pgm'];
$address = $_POST['address'];
//Examining for input errors
$error = FALSE;
if (isset($address)) {
$address = trim($address);
$address = strip_tags($address);
}
if (isset($fname) &&
isset($institute) &&
isset($email) &&
isset($phone) &&
isset($pgm) &&
isset($address) &&
$error == FALSE) {
$process = TRUE;
} else {
$process = FALSE;
}
//Writing the multiple answers for user selected programs
while ((list($key,$val) = each($pgm))) {
$pgm .= "[" . $val . "]";
}
//Creating the table
$query = "create table userdata
( sid int unsigned not null auto_increment primary key,
fname char(50) not null,
institute char(50) not null,
email char(50) not null,
phone int unsigned,
pgm text not null,
address char(200) not null)";
$q = mysql_query($query);
//Inserting the data
$query = "insert into userdata values ('','$fname','$institute','$email','$phone','$pgm','$address')";
$q = mysql_query($query);
//Check whether data was properly inserted
if (!$q) {
exit("<p>MySQL Insertion failure.</p>");
} else {
mysql_close();
echo "<p>MySQL Insertion Successful</p>";
}
}
?>
Can someone comment on this ?
try adding
or die(mysql_error());
after your mysql_query($query). That will surely show an error if it failed...
did you try to echo out $q ? it should tell exactly what's wrong when trying to add to database..
//Check whether data was properly inserted
if (!$q) {
die(mysql_error());
exit();
} else {
mysql_close();
echo "<p>MySQL Insertion Successful</p>";
}
My best guess is that the table already exists and so when the user submits the form your code is again trying to create the table 'userdata' which is already there and then dies.
You should remove the create statement out of your code because on every submission it's going to try and create a table that already exists. You should also look about escaping the submtted data before you pass on to an SQL statement as you're just asking for SQL injection attacks as the code stands now.

Categories