Although everything looks fine in my program (e.g. register2.php), I have some syntax and binding issues. As it keeps throwing the error on line 73 even though the data successfully entered my database named "webprojadmin", and the table named "users".
here is my connected PDO database:
<?php
session_start();
$host = "127.0.0.1:3308";
$username = "root";
$password = "root";
$dbname = "webprojadmin";
$dsn = "mysql:host=$host;dbname=$dbname";
$optionen = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
try {
// Create connection
$cxn = new PDO($dsn, $username, $password, $optionen);
// set the PDO error mode to exception
$cxn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo "Success: A proper connection to MySQL was made! The"." ".$dbname." "."database is great." . PHP_EOL;
//echo "Host URL: " . $host . PHP_EOL;
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
And here is my program, register2.php
<?php
require "dbcxn.php";
?>
<center>
<div>
<h1>Add a new web user account</h1>
<form action="" method="post">
<p>Full Name:<input type="text" name="fullname" placeholder="enter your full name"></p>
<p>Email:<input type="text" name="email" placeholder="enter your email address"></p>
<p>Password:<input type="password" name="pass" placeholder="enter passowrd"></p>
<p>Type<select name="utype">
<option value="FA">Academic, Faculty & Staff</option>
<option value="UG">Undergraduate Student</option>
<option value="PG">Postgraduate Student</option>
<option value="AU">Undergraduate Alumni</option>
<option value="AP">Postgraduate Alumni</option>
</select><p>
<p>Bio:<br><textarea id="textboxid" type="text" name="bio" placeholder="May you introduce to us, briefly?"></textarea></p>
<p>Awards:<br><textarea id="textboxid" type="text" name="awards" placeholder="Have you received any awards? If yes, what are they?"></textarea></p>
<p>Publications:<br><textarea id="textboxid" type="text" name="pub" placeholder="Have you published any written works? If yes, what are they?"></textarea></p>
<p>Thesis Topic:<br><textarea id="textboxid" type="text" name="ttopic" placeholder="What is the title of the Thesis you are doing/about to do/recently done?"></textarea></p>
<p>Thesis abstract:<br><textarea id="textboxid" type="text" name="tabstract" placeholder="If you have told the thesis topic, what is it about? Tell us briefly. If not, leave it blank."></textarea></p>
<p><input type="submit" name="btn_register" value="Create an account"/></p>
</form>
</div>
</center>
<?php
if (isset($_POST["btn_register"])) //button name "btn_register"
{
$fullname = strip_tags($_POST["fullname"]);
$email = $_POST["email"];
$pass = $_POST["pass"];
$utype = $_POST["utype"];
$bio = $_POST["bio"];
$awards = $_POST["awards"];
$pub = $_POST["pub"];
$ttopic = $_POST["ttopic"];
$tabstract = $_POST["tabstract"];
$sql = "INSERT INTO users (fullname, email, pass, utype, bio, awards, pub, ttopic, tabstract) VALUES ('$fullname', '$email', '$pass', '$utype', '$bio', '$awards', '$pub', '$ttopic', '$tabstract')";
echo ("<pre>\n".$sql."\n</pre>\n");
if(empty($fullname)) {
$errorMsg[]="Please enter username"; //check username textbox not empty
}
else if(empty($email)) {
$errorMsg[]="Please enter email"; //check email textbox not empty
}
else if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errorMsg[]="Please enter a valid email address"; //check proper email format
}
else if(empty($pass)) {
$errorMsg[]="Please enter password"; //check passowrd textbox not empty
}
else if(strlen($pass) < 6) {
$errorMsg[] = "Password must be atleast 6 characters"; //check passowrd must be 6 characters
}
else
{
try
{
$select_stmt=$cxn->prepare("SELECT fullname, email FROM users
WHERE fullname=:ufname OR email=:uemail"); // sql select query
$select_stmt->execute(array(':ufname'=>$fullname, ':uemail'=>$email)); //execute query
$row=$select_stmt->fetch(PDO::FETCH_ASSOC);
if($row["fullname"]==$fullname){
$errorMsg[]="Sorry username already exists"; //check condition username already exists
}
else if($row["email"]==$email){
$errorMsg[]="Sorry email already exists"; //check condition email already exists
}
else if(!isset($errorMsg)) //check no "$errorMsg" show then continue
{
$new_pass = password_hash($pass, PASSWORD_DEFAULT); //encrypt password using password_hash()
$query = "INSERT INTO users (fullname, email, pass, utype, bio, awards, pub, ttopic, tabstract) VALUES ('$fullname', '$email', '$pass', '$utype', '$bio', '$awards', '$pub', '$ttopic', '$tabstract')";
//$query2 = $sql;
//$query2run = $cxn->prepare($query2);
//$query2exec = $query2run->execute();
//$row=$query2run->fetch(PDO::FETCH_ASSOC);
$insert_stmt=$cxn->prepare("INSERT INTO users (fullname, email, pass, utype, bio, awards, pub, ttopic, tabstract) VALUES (:ufname,:uemail,:upass,:uutype,:ubio,:uawards,:upub,:uttopic,:utabstract)"); //sql insert query
if ($insert_stmt->execute(array( ':ufname' =>$fullname,
':uemail'=>$email,
':upass'=>$new_pass,
':uutype'=>$utype,
':upass'=>$bio,
':upass'=>$awards,
':upass'=>$pub,
':upass'=>$ttopic,
':upass'=>$tabstract))) {
$registerMsg = "Register Successfully..... Please Click On Login Account Link"; //execute query success message
header("refresh:1; index.php");
}
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
}
if(isset($errorMsg))
{
foreach($errorMsg as $error)
{
?>
<div>
<strong>WRONG ! <?php echo $error; ?></strong>
</div>
<?php
}
}
if(isset($registerMsg))
{
?>
<div>
<strong><?php echo $registerMsg; ?></strong>
</div>
<?php
}
?>
</section>
Related
I have problem in my code it's login with any username and password without verify it from the database more explain below
I have 2 tables one for usernames and one for passwords, I trying to make my code like this
users table it's have: id, username, phone, email
password table it's have: id, userid, password
every password connected with id of the user by user_id field
I want my code work like this
if username, email or phone in one row equal to the password have the same user_id the same as in the row make login
Example
users table: 1, eddy, edd#example.com, 4493838
passwords table: 1, 1(please note: it's user id from users table), alfa
<?php
$servername = "localhost";$username = "username";$password = "password";$dbname = "myDBPDO";
if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Username']))
{?>
Welcome <? echo $_SESSION['users_id'] ?>
<?php
}
elseif(!empty($_POST['various-login']) && !empty($_POST['password']))
{
// PDO
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Database
$stmt = $conn->prepare("SELECT id as users_id, username, email, phone FROM users");
$stmt->execute();
$stmt = $conn->prepare("SELECT id as passwords_id, user_id, password FROM passwords");
$stmt->execute();
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
$various_login= $_POST['various-login'] == $userRow['email'] or $userRow['phone'];
$user_and_password = $userRow['users_id'] === $userRow['user_id'];
$password = $_POST['password'] == $user_and_password;
if($stmt->rowCount() == 1)
{
$email = $userRow['email'];
$_SESSION['Username'] = $username;
$_SESSION['email'] = $email;
$_SESSION['LoggedIn'] = 1;
echo "<h1>Success</h1>";
echo $email;
}
else
{
echo "<h1>Error</h1>";
echo "<p>Sorry, your account could not be found. Please click here to try again.</p>";
}}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
} else {?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Email/Phone: <input type="text" name="various-login" value="<?php echo $website;?>">
<br><br>
Password: <input type="password" name="password">
<br><br>
<input type="submit" name="submit" value="<?php echo $lang['NEXT']; ?>">
</form>
<?php}?>
Use this : (Not secure for SQLi)
<?php
$servername = "localhost";$username = "username";$password = "password";$dbname = "myDBPDO";
if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Username']))
{
echo "Welcome ".$_SESSION['Username'];
}
elseif(!empty($_POST['various-login']) && !empty($_POST['password']))
{
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Database
$stmt = $conn->prepare("SELECT id, username, email, phone FROM users WHERE lower(username) = '".strtolower($_POST['various-login'])."' OR lower(email) = '".strtolower($_POST['various-login'])."' OR phone = '".strtolower($_POST['various-login'])."'");
$stmt->execute();
$userdata = $stmt->fetch(PDO::FETCH_ASSOC);
if(!empty($userdata["id"]))
{
$stmt = $conn->prepare("SELECT id, user_id, password FROM passwords WHERE user_id = '".$userdata["id"]."' AND password = '".$_POST["password"]."'");
$stmt->execute();
$password_data = $stmt->fetch(PDO::FETCH_ASSOC);
if(!empty($password_data["id"]))
{
$_SESSION['users_id'] = $userdata["id"]
$_SESSION['Username'] = $userdata["username"];
$_SESSION['email'] = $userdata["email"];
$_SESSION['LoggedIn'] = 1;
echo "<h1>Success</h1>";
echo $email;
}
else
{
echo "<h1>Error</h1>";
echo "<p>Sorry, your account password is not valid. Please click here to try again.</p>";
}
}else{
echo "<h1>Error</h1>";
echo "<p>Sorry, your account could not be found. Please click here to try again.</p>";
}
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
} else {?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Email/Phone:
<input type="text" name="various-login" value="<?php echo $website;?>">
<br><br>
Password: <input type="password" name="password">
<br><br>
<input type="submit" name="submit" value="<?php echo $lang['NEXT']; ?>">
</form>
<?php } ?>
I'd highly recommend using a join so it's 1 SQL statement, as well as a sanitizing and validating your input.
SELECT users.*
FROM users
JOIN passwords ON passwords.user_id = users.id
WHERE (users.email = :email
OR users.phone = :phone)
AND passwords.password = :password
Here's the link to the documentation on prepared statements. I suggest you re-read that to understand why your existing code won't work (hint: you're selecting all records). http://php.net/manual/en/pdo.prepared-statements.php
Create your PDO Connection
Create your SQL
Bind your parameters
Execute the query
If you have a row, you found the user.
I'm sure you're already aware of the issues with using plain text passwords, and have assumed this is an assignment and not something used in production.
I have a user input form(HTML) that is supposed to take the information and insert it into a MySQL database via PHP. The PHP apparently executes and echoes "Your registration has completed successfully". A record is created in the database but the columns are blank(I have removed my server, database, and password from the PHP code).
HTML:
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="css/styles.css">
<title>User Portal</title>
</head>
<div class="inputContainer">
<header>
User Information Portal
</header>
<form action="php/userPost.php" method="post">
<label for=firstName">First Name</label>
<input type="text" id=firstName" name="fname">
<br><br>
<label for="lastName">Last Name</label>
<input type="text" id="lastName" name="lname">
<br><br>
<label for="eMail">Email</label>
<input type="text" id="eMail" name="email">
<br><br>
<label class="labelRole" for="userRole">Role -</label><br>
<input type="radio" id="userRole" name="role" value="Instructor"> Instructor
<input class="submitButton" type="submit" name="submit" value="Register">
</form>
</div>
</body>
PHP:
<?php
$sname = "server-name";
$uname = "username";
$pword = "password";
$dbname = "web_tech_test";
$conn = new mysqli($sname, $uname, $pword, $dbname);
if ($conn->connect_error) {
die("Connection failure: " . $conn->connect_error);
}
$fname = !empty($_POST['firstName']);
$lname = !empty($_POST['lastName']);
$email = !empty($_POST['eMail']);
$role = isset($_POST['userRole']);
$sql = "INSERT INTO users (first_name, last_name, email, role)
VALUES ('$fname', '$lname', '$email', '$role')";
if ($conn->query($sql) === TRUE) {
echo "Your registration has completed successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
This creates a new record in the DB but all the columns are blank. Any ideas why this may be happening?
$fname = !empty($_POST['firstName']);
$lname = !empty($_POST['lastName']);
$email = !empty($_POST['eMail']);
$role = isset($_POST['userRole']);
this code returns a boolean, not a string value...
Use !empty() just for validation
example
if(empty($_POST['eMail'])) {
die("Email cannot be empty");
}
You're confusing the id and the name tags on the inputs.
The name tags are the ones which will be submitted as keys to your server.
Try this in your server php script after submitting your form to see which key/values are actually received by the server:
var_dump($_POST);
Also, if you want to check that all fields have been filled out, use something similar as this:
if (empty($_POST['firstName'])) {
die("firstname is empty!");
}
In your current example you're actually saving a boolean to your variables.
And, last but not least, never insert variables from a potentially unsafe source (like a user input) directly into your SQL. Use pdo: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers for this
Full code example to get you started:
//prepare your values
if (empty($_POST['fname']) || empty($_POST['lname']|| empty($_POST['email']|| !isset($_POST['role'])) {
die ("some values were empty or not set");
}
//prepare your database
$db = new PDO('mysql:host=server-name;dbname=web_tech_test;charset=utf8mb4', 'username', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //throw an exception if there is an error
//create your query
$stmt = $db->prepare("INSERT INTO users (first_name, last_name, email, role) VALUES (:first_name,:last_name,:email,:role)"); //create a query statement
$stmt->bindValue(":first_name", $firstName); //put your values into your statement
$stmt->bindValue(":last_name", $lastName);
$stmt->bindValue(":email", $email);
$stmt->bindValue(":role", $role);
if ($stmt->execute()) { //execute the query
echo "Your registration has completed successfully";
} else {
echo "Error :(";
}
I am new to PHP and i am trying to built a registration form for users and to saved user input to database, but user data are not saving to database. Someone please help !
cofiguration.php
<?php
define('HOST','localhost');
define('USER','root');
define('PASSWORD_HOST','');
define('DATABASE','test_db');
if (defined('HOST') && defined('USER') && defined('PASSWORD_HOST') && defined('DATABASE')){
$conn=mysqli_connect(HOST,USER,PASSWORD_HOST,DATABASE);
}else{
die("connection failed:" .mysqli_connect_error());
}
?>
here i am updating my whole index.php file.
index.php
<!DOCTYPE html>
<html>
<style>
.error {color: #FF0000;}
</style>
<?php
require_once "configuration.php";
//set trigger for login form
$registereduserValidInput=true;
if (isset($_POST['RegisterSubmitButton']))
{
//if firstname field is empty
if (empty($_POST["firstname"]))
{
$firstnameErr="Let us know your first name";
$registereduserValidInput=false;
}else
{
$firstname = test_input($_POST["firstname"]);
if (!preg_match("/^[a-zA-Z ]*$/",$firstname))
{
$firstnameErr1="please provide letters only";
$registereduserValidInput=false;
}
}
/*.................................................................................................
...................................................................................................*/
//if last name field is empty
if (empty($_POST["lastname"]))
{
$lastnameErr="Please provide last name";
$registereduserValidInput=false;
}else
{
$lastname=test_input($_POST["lastname"]);
if (!preg_match("/^[a-zA-Z ]*$/",$lastname))
{
$lastnameErr1="Please provide letters only";
$registereduserValidInput=false;
}
}
/*.................................................................................................
...................................................................................................*/
//check email field
if (empty($_POST["useremail"]))
{
$emailErrA = "Email is required";
$registereduserValidInput = false;
}else
{
$email = test_input($_POST["useremail"]);
//email validation
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$emailErr1A = "Invalid email format";
}
}
/*.................................................................................................
...................................................................................................*/
//check password field
if(empty($_POST["userpassword"]))
{
$passwordErr="Password is required";
$registereduserValidInput = false;
}else {
$password = test_input($_POST["userpassword"]);
}
/*.................................................................................................
...................................................................................................*/
//password verification field
if(empty($_POST["verifypassword"]))
{
$verifypasswordErr="Re-enter your Password";
$registereduserValidInput = false;
}else {
$verifypassword = test_input($_POST["verifypassword"]);
}
/*.................................................................................................
...................................................................................................*/
//script to check whether the two password fields matches or not
if (strcmp($password, $verifypassword) !== 0)
{
$passwordnotmatch="Password do no match"; //if passwords do not match generate error to user
$registereduserValidInput = false;
}else {
$passwordmatch="password match";
}
/*.................................................................................................
...................................................................................................*/
/*.................................................................................................
...................................................................................................*/
// if all inputs are provided by user run sql query to check whether email is already registered or not
if($registereduserValidInput==true){
$sql1=mysqli_query($conn, "SELECT * FROM registereduser WHERE useremail='$_POST[email]'");
$rows1 = mysqli_num_rows($sql1);
if($rows1==0)
{
//insert user input to "registeredUser" table
$sqlTable ="INSERT INTO registereduser (firstname, lastname, useremail, userpassword) VALUES ('".$firstname."', '".$lastname."', '".$email."','".$password."')";
mysqli_query($conn, $sqlTable);
}else{
echo "This email ID is already registered with us. kindly login again!";
die;
}
}
}
?>
<body>
<form method="post" action="index.php">
<h2>Registration Form</h2><br><br>
Enter Your First Nmae:<br><br>
<input type="text" name="firstname" placeholder="First Name" value="">
<span class="error"> <?php echo $firstnameErr; ?> </span>
<span class="error"> <?php echo $firstnameErr1; ?> </span><br><br>
Enter Your Last Name:<br><br>
<input type="text" name="lastname" placeholder="Last Name" value="">
<span class="error"> <?php echo $lastnameErr; ?> </span>
<span class="error"> <?php echo $lastnameErr1; ?> </span><br><br>
Enter Your Email:<br><br>
<input type="text" name="useremail" value="" >
<span class="error"> <?php echo $emailErrA;?></span>
<span class="error"> <?php echo $emailErr1A;?></span><br><br>
Enter Your Password:<br><br>
<input type="password" name="userpassword" value="">
<span class="error"> <?php echo $passwordErr;?></span><br><br>
Re-enter Your Password:<br><br>
<input type="password" name="verifypassword" value="">
<span class="error"> <?php echo $verifypasswordErr;?></span>
<span class="error"> <?php echo $passwordmatch;?></span><br><br>
<input type="submit" name="RegisterSubmitButton" value="Click here to Register">
</form>
</body>
</html>
The code to perform the database query and insert should be:
if($registereduserValidInput==true){
$sql1=mysqli_query($conn, "SELECT * FROM registereduser WHERE useremail='$_POST[email]'") or die(mysqli_error($conn));
$rows1 = mysqli_num_rows($sql1);
if($rows1==0)
{
//insert user input to "registeredUser" table
$sqlTable ="INSERT INTO registereduser (firstname, lastname, useremail,userpassword) VALUES ('".$firstname."', '".$lastname."', '".$email."','".$password."')";
mysqli_query($conn, $sqlTable) or die(mysqli_error($conn));
}else{
echo "This email ID is already registered with us. kindly login again!";
die;
}
}
You were missing the $conn argument in the SELECT query (you had the variable at the end of the SQL instead), and you never called mysqli_query() on $sqlTable.
You should also look up how to use prepared statements and bind_param. Substituting variables into a query leaves you open to SQL injection.
Few error I have found..
No field for password in Form or any variable for $password.
Not getting any method name test_input
$sql1=mysqli_query("SELECT * FROM registereduser WHERE useremail='$_POST[email]',$conn");
should be like
$sql1=mysqli_query($conn, "SELECT * FROM mdm_users WHERE school_name='$_POST[useremail]'");
and Most
$sqlTable ="INSERT INTO 'registereduser' ('firstname', 'lastname', 'useremail','userpassword') VALUES ('".$firstname."', '".$lastname."', '".$email."','".$password."')";
line should be like
$sqlTable ="INSERT INTO registereduser (firstname, lastname, useremail,userpassword) VALUES ('".$firstname."', '".$lastname."', '".$email."','".$password."')";
mysqli_query($conn, $sqlTable);
please remove the single quotes in table and column names.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I've written this code for a registration page, but I am unable to get insert data into my database using PDO(or doing something incorrectly rather). Here is the registration page code:
<?php
if (empty($_POST)){
?>
<form name="registration" action="register.php" method="POST">
<label for "username">Username: </label>
<input type="text" name="username"/><br />
<label for "password">Password: </label>
<input type="password" name="password"/><br />
<label for "fname">First Name: </label>
<input type="text" name="fname"/><br />
<label for "lname">Last name: </label>
<input type="text" name="lname"/><br />
<label for "email">Email: </label>
<input type="text" name="email"/><br />
<button type="submit">Submit</button>
</form>
<?php
}
else{
$form = $_POST;
$username = $form['username'];
$password = $form['passowrd'];
$fname = $form['fname'];
$lname = $form['lname'];
$email = $form['email'];
$user = 'root';
$pass = 'pdt1848!';
$db = new PDO('mysql:host=localhost;dbname=phpproject', $user, $pass);
$sql = "INSERT INTO users (username, password, fname, lname, email)VALUES(:username, :password, :fname, :lname, :email)";
$query = $db->prepare($sql);
$result = $query->execute(array(':username'=>$username, ':password'=>$password,
':fname'=>$fname, ':lname'=>$lname, ':email'=>$email));
if ($result){
echo "Thanks for registering with us!";
} else {
echo "Sorry, an error occurred while editing the database. Contact the guy who built this garbage.";
};
};
?>
The error is right here, passowrd
$password = $form['passowrd'];
A mere typo.
change it to:
$password = $form['password'];
when one fails, the whole query fails.
Had you error reporting in your code, it would've picked it up right away.
Ways that you can use in the future are a try & catch method, such as:
try {
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
as well as
error_reporting(E_ALL);
ini_set('display_errors', 1);
Links that you can consult for further reading:
PDO
http://www.php.net/manual/en/pdo.error-handling.php
http://www.php.net/manual/en/pdo.errorinfo.php
MySQL
http://www.php.net/manual/en/mysqli.error.php
http://www.php.net/mysqli_error
(more)
http://php.net/manual/en/errorfunc.configuration.php#ini.display-errors
http://php.net/manual/en/errorfunc.configuration.php#ini.display-startup-errors
http://php.net/manual/en/function.error-reporting.php
Passwords
I also noticed that you are storing passwords in plain text. This is not recommended.
Use one of the following:
CRYPT_BLOWFISH
crypt()
bcrypt()
scrypt()
On OPENWALL
PBKDF2
PBKDF2 on PHP.net
PHP 5.5's password_hash() function.
Compatibility pack (if PHP < 5.5) https://github.com/ircmaxell/password_compat/
Other links:
PBKDF2 For PHP
Well I do something like this,
$user = 'your username';
$pass = 'your pass';
$db = new PDO( 'mysql:host=localhost;dbname=your_data_base_name', $user, $pass );
/*Grab Post*/
$form = $_POST;
$username = $form[ 'username' ];
$password = $form[ 'password' ];
$first_name = $form[ 'first_name' ];
$surname = $form[ 'surname' ];
$address = $form[ 'address' ];
$email = $form[ 'email' ];
// Sql
$sql = "INSERT INTO users ( username, password, first_name, surname, address, email ) VALUES ( :username, :password, :first_name, :surname, :address, :email )";
$result = $query->execute( array( ':username'=>$username, ':password'=>$password, ':first_name'=>$first_name, ':surname'=>$surname, ':address'=>$address, ':email'=>$email ) );
if ( $result ){
echo "Thank you. You have been registered";
} else {
echo "Sorry, there has been a problem inserting your details.";
}
In addition I always, enable my error reporting as Tuga suggested. It never fails me.
apart from the typo in the passowrd you should enable exceptions for PDO and use a try and catch statement to catch the exception. Also some other little changes, like structuring the PHP first and removing the odd re-assign of the POST superglobal.
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$result = "Thanks for registering with us!";
try{
$db = new PDO('mysql:host=localhost;dbname=phpproject', 'root', 'pdt1848!');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
$sql = "INSERT INTO users (username, password, fname, lname, email)
VALUES(:username, :password, :fname, :lname, :email)";
$query = $db->prepare($sql);
$query->execute(array(':username'=>$_POST['username'],
':password'=>$_POST['password'],
':fname'=>$_POST['fname'],
':lname'=>$_POST['lname'],
':email'=>$_POST['email']));
}catch(PDOException $e){
$result = 'Sorry, an error occurred while editing the database. Contact the guy who built this garbage.';
//or use $e->getMessage(); for the real error
}
echo $result;
}
else{ ?>
<form name="registration" action="register.php" method="POST">
<label for "username">Username: </label>
<input type="text" name="username"/><br />
<label for "password">Password: </label>
<input type="password" name="password"/><br />
<label for "fname">First Name: </label>
<input type="text" name="fname"/><br />
<label for "lname">Last name: </label>
<input type="text" name="lname"/><br />
<label for "email">Email: </label>
<input type="text" name="email"/><br />
<button type="submit">Submit</button>
</form>
<?php } ?>
Also its a very bad idea to store plain-text passwords in your db. ~ Read: Best way to store password in database.
Edit,
Added some validation of your inputs to help you get started, hope it helps. not tested.
<?php
try{
$db = new PDO('mysql:host=localhost;dbname=phpproject', 'root', 'pdt1848!');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
}catch(PDOException $e){
die('Sorry, an error occurred while editing the database. Contact the guy who built this garbage.');
//or use $e->getMessage(); for the real error
}
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
//create empty error array - to fill with errors if any
$error = array();
//validate username
if(empty($_POST['username'])){
$error['username'] = 'Enter a username';
}elseif(strlen($_POST['username']) <= 2){
$error['username'] = 'Username too short > 2 chars';
}else{
//check for existing user
$sql = "SELECT 1
FROM `users`
WHERE username = :username";
$query = $db->prepare($sql);
$query->execute(array(':username' => $_POST['username']));
$result = $query->fetchAll(PDO::FETCH_ASSOC);
if(!empty($result)){
$error['username'] = 'User already exists';
}
}
//validate pass
if(empty($_POST['password'])){
$error['password'] = 'Please enter password';
}elseif(strlen($_POST['password']) < 6){
$error['password'] = 'Password too short, password should be 6 chars or longer';
}
//validate fname
if(empty($_POST['fname'])){
$error['fname'] = 'Please enter your first name';
}
//validate fname
if(empty($_POST['lname'])){
$error['lname'] = 'Please enter your last name';
}
//validate email
if(empty($_POST['email'])){
$error['email'] = 'Please enter your email';
}else{
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
$error['email'] = 'Please enter valid email';
}
}
//no errors detected so insert
if(empty($error)){
$sql = "INSERT INTO users (username, password, fname, lname, email)
VALUES(:username, :password, :fname, :lname, :email)";
$query = $db->prepare($sql);
$query->execute(array(':username'=>$_POST['username'],
':password'=>$_POST['password'],
':fname'=>$_POST['fname'],
':lname'=>$_POST['lname'],
':email'=>$_POST['email']));
$result = 'Thanks for registering with us! Click here to login';
}else{
$result = 'Please correct the errors';
}
}?>
<?php echo isset($result) ? $result : null;?>
<form name="registration" action="register.php" method="POST">
<label for "username">Username: <?php echo isset($error['username']) ? $error['username'] : null;?></label>
<input type="text" name="username"/><br />
<label for "password">Password: <?php echo isset($error['password']) ? $error['password'] : null;?></label>
<input type="password" name="password"/><br />
<label for "fname">First Name: <?php echo isset($error['fname']) ? $error['fname'] : null;?></label>
<input type="text" name="fname"/><br />
<label for "lname">Last name: <?php echo isset($error['lname']) ? $error['lname'] : null;?></label>
<input type="text" name="lname"/><br />
<label for "email">Email: <?php echo isset($error['email']) ? $error['email'] : null;?></label>
<input type="text" name="email"/><br />
<button type="submit">Submit</button>
</form>
I have a registration form. In the database, the username and email are unique index. When the form submits and username or email are already present in the database, the values are not inserted. I want to notify the user that the values were not inserted. How can i do this?
HTML
<form action="register.php" method="post" id="reg" onsubmit='return validate();'>
Company Name:
<input type="text" class="inputs" name="name" id="name" /><br />
Email:
<input type="text" class="inputs" name="email" id="txtEmail" /><br />
User name:
<input type="text" class="inputs" name="uname" id="uname"/><br />
Password:
<input type="password" class="inputs" name="pass" id="pass1"/><br />
Conferm Password:
<input type="password" class="inputs" name="cpass" id="pass2"/><br /><br />
<input type="submit" value="Register" class="button" />
</form>
register.php:
include ("db.php");
if (isset($_POST['register'])) {
echo $name = ($_POST["name"]);
echo $email = ($_POST["email"]);
echo $uname = ($_POST["uname"]);
echo $password = ($_POST["pass"]);
mysqli_query($con,"INSERT INTO company_profile(user_name, password, company_name, email, phone, country, activation_string) VALUES ('$uname','$password','$name','$email','','','')");
}
*Sweet And Short *
First check that username or email is exist or not using select query if resulting is 0 (it means not exists), Insert query will run ahead
<?php
if($_POST['register']){
$uname = $_POST['uname'];
$email = $_POST['email'];
$name= $_POST['name'];
$pass= $_POST['pass'];
$result = mysqli_query($con, 'SELECT * from TABLE_NAME where email_id = "'.$email.'" or username = "'.$uname.'" ');
if(mysqli_num_rows($result) > 0){
echo "Username or email already exists.";
}else{
$query = mysqli_query($con , 'INSERT INTO TABLE_NAME (`email_id`, `username`,`name`,`pass`) VALUES("'.$email.'", "'.$email.'", "'.$uname.'","'.$name.'", "'.$pass.'")');
if($query){
echo "data are inserted successfully.";
}else{
echo "failed to insert data.";
}
}
}
?>
The query method would return true or false, depending on if the row has been inserted or not.
Try the following Code
include ("db.php");
if (isset($_POST['register']))
{
echo $name = ($_POST["name"]);
echo $email = ($_POST["email"]);
echo $uname = ($_POST["uname"]);
echo $password = ($_POST["pass"]);
$var = mysqli_query('SELECT * from company_profile where email_id = "'.$email.'" or username = "'.$uname.'" ');
$num = mysqli_num_rows($var);
if($num==0)
{
$result = INSERT INTO company_profile(user_name, password, company_name, email, phone, country, activation_string) VALUES ('$uname','$password','$name','$email','','','');
$res = mysqli_query($result);
if($res)
{
echo "Records Inserted Successfully!!";
}
else
{
echo "Records Inserted Failed!!";
}
}
else
{
echo "User with the Details Already exists!!"
}
}