My database is not adding users when I signup - php

This is my HTML file:
<div class="form">
<form action="register.php" method="POST" class="register-form">
<input type="text" placeholder="Username" name="username" required/>
<input type="password" placeholder="Password" name="password" required/>
<input type="text" placeholder="Email" name="email" required/>
<button type="submit">Create</button>
<p class="message"> Already Registered? Login
</p>
</form>
<form action="login.php" method="POST" class="login-form">
<input type="text" placeholder="Username" name="username" required/>
<input type="password" placeholder="Password" name="password" required/>
<button type="submit">login</button>
<p class="message">Not Registered? Register</p>
</form>
This is my PHP file:
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
if (!empty($username) || !empty($password) || !empty($email)) {
$serverName = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbname = "account";
//create connection
$conn = new MySQLI($serverName,$dbUsername,$dbPassword,$dbname);
if (mysqli_connect_error()) {
die('Connect Error('. mysqli_connect_errno().')'. mysqli_connect_error());
} else {
$SELECT = "SELECT email From users Where email = ? Limit 1";
$INSERT = "INSERT Into users (username, password, email) values(?, ?, ?)";
//Prepare statement
$stmt = $conn->prepare($SELECT);
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->bind_result($email);
$stmt->store_result();
$stmt->store_result();
$stmt->fetch();
$rnum = $stmt->num_rows;
if ($rnum==0) {
$stmt->close();
$stmt = $conn->prepare($INSERT);
$stmt->bind_param("sss", $username, $password, $email);
$stmt->execute();
echo "New record inserted sucessfully";
} else {
echo "Someone already register using this email";
}
$stmt->close();
$conn->close();
}
} else {
echo "All field are required";
die();
}
I have a database called account, with a table called users, columns called id, email, username & password. The ID is an INT, and selected as primary. And the rest is set as VARCHAR.
When I enter some names in the form, and press signup, it's giving me the result "New record inserted successfully", so I have no idea, why this doesn't work.

Your problem is the way you use mysqli. As I have said in the comments mysqli is not suitable for beginners, the API is very cumbersome.
Look at the lines before your INSERT statement. You perform a SELECT statement, presumably to check if the email has been used before and then you bind the result variable. The variable is called $email. You overwrite your user input with the result from SELECT. But this is not the right way.
The simple solution would be to name the variable something else, but the right answer is that you should fetch a count from the SQL not the value. See adjusted code below:
<?php
$username = filter_input(INPUT_POST, 'username');
$password = filter_input(INPUT_POST, 'password');
$email = filter_input(INPUT_POST, 'email');
if ($username && $password && $email) {
$serverName = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbname = "account";
//create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new MySQLI($serverName, $dbUsername, $dbPassword, $dbname);
$conn->set_charset('utf8mb4'); // always set the charset
//Prepare statement
$stmt = $conn->prepare("SELECT COUNT(email) From users Where email = ? Limit 1");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($exists); // we fetch the count
$stmt->fetch();
if (!$exists) {
$stmt = $conn->prepare("INSERT Into users (username, password, email) values(?, ?, ?)");
// Don't forget to hash the password and never store the real password anywhere
$hash = password_hash($password, PASSWORD_DEFAULT);
$stmt->bind_param("sss", $username, $hash, $email);
$stmt->execute();
echo "New record inserted sucessfully";
} else {
echo "Someone already register using this email";
}
} else {
echo "All field are required";
}
I remove the unnecessary code and removed the store_result() and num_rows. They are not helpful in this situation. Instead fetch a count of matching rows and check if the count is not 0 with if(!$exists)

Related

How do I insert values from a form using php and sql using my own script?

Hi first time user and beginner when it comes to using php,
How do I go about inserting values from a form using php and sql.
Ive created the following code using php and sql.
here is my form.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "datab";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// prepare and bind with form attached.
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
?>
<form action="/t.php" method="post">
First name:
<input type="text" name="firstname">
<br> Last Name:
<input type="text" name="lastname">
<br>Email:
<input type="text" name="email">
<input type="submit" value="Submit">
</form>
<?php
// set parameters and execute
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$stmt->execute();
$stmt->close();
$conn->close();
?>
the t.php file is simply saying entries were added successfully even though there is no logic there, just a simple echo comment.
I just want to know how to insert data using forms with php and sql.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "datab";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<form action="/t.php" method="post">
First name:
<input type="text" name="firstname">
<br> Last Name:
<input type="text" name="lastname">
<br>Email:
<input type="text" name="email">
<input type="submit" name="submit" value="Submit">
</form>
<?php
if(isset($_POST['submit']) && !empty($_POST['submit'])) {
// set parameters and execute
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
// prepare and bind with form attached.
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
$stmt->execute();
$stmt->close();
$conn->close();
}
?>
You can do it like this:
To prevent duplication, save the db connection in a file called db.php.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "datab";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Then, include it in the main.php file. Here's the main.php file written with prepared statement errors prevented.
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
try {
# check if all the params are set
if (
!empty($_POST['firstname']) &&
!empty($_POST['lastname']) &&
!empty($_POST['email'])
) {
$firstname = htmlspecialchars(trim($_POST['firstname']));
$lastname = htmlspecialchars(trim($_POST['lastname']));
$email = htmlspecialchars(trim($_POST['email']));
include_once 'db.php';
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
if (
$stmt &&
$stmt->bind_param("sss", $firstname, $lastname, $email) &&
$stmt -> execute()
) {
echo "Yay! Inserted.";
} else {
throw new Exception("Error in MYSQLI Statement");
}
} else {
throw new Exception("Some data is not set");
}
} catch (Exception $e) {
die($e -> getMessage());
}
} else { ?>
<form action="" method="post">
First name:
<input type="text" name="firstname">
<br> Last Name:
<input type="text" name="lastname">
<br>Email:
<input type="text" name="email">
<input type="submit" value="Submit">
</form>
<?php } ?>
The strings should be validated before inserted into the database. Here I have used htmlspecialchars() to prevent XSS and trim() to remove unnecessary white spaces.
Thanks.
Form action will call t.php, but you dont have it!
Create two files: myHtml.html and t.php in the same folder
myHtml.html
<html>
<form action="t.php" method="post">
First name:
<input type="text" name="firstname">
<br> Last Name:
<input type="text" name="lastname">
<br>Email:
<input type="text" name="email">
<input type="submit" value="Submit">
</form>
</html>
t.php
<?php
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "datab";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// prepare and bind with form attached.
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
// set parameters and execute
$stmt->execute();
$stmt->close();
$conn->close();

PHP - Session variables with prepared statements and parameterized queries

I tried to write a registration form. On submition it suppose to:
Get the data from the inputs to the sql database - as a row in the table.
Add the users email address as a session variable.
Redirects them to a second page.
It all happens, but it adds two identical rows instead of one.
I'll appreciate any answer you can give me that will explain why my script adds the same row twice into the database.
PHP:
<?php
ob_start();
session_start();
if($_POST) {
$email = $_POST['email'];
$password = $_POST['password'];
$name = $_POST['name'];
$error = "";
$link = mysqli_connect("xx", "xx", "xx", "xx");
if (mysqli_connect_error()) {
die("the connection was failed");
}
if ($email || $password || $name) {
$stmt = $link->prepare("INSERT INTO `Family` (email, password, name) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $email, $password, $name);
$stmt->execute();
if($stmt->execute()) {
$_SESSION['email'] = $email;
header("Location: session.php");
$stmt->close();
} else {
echo "it failed";
}
}
}
HTML:
<html>
<head>
</head>
<body>
<h1>Registration Form</h1>
<form method="post">
<p>Email:</p>
<input type="email" name="email">
<p>Password:</p>
<input type="password" name="password">
<p>Name:</p>
<input type="text" name="name">
<br><br><br>
<button type="submit">Submit</button>
</form>
</body>
</html>

Form data into database using PHP

I've created a HTML form that inserts user data into a database using MySQL and PHP.
HTML form:
<form action="index.php" method="POST" >
<div class="container">
<label for="username"><b>Username</b></label>
<input type="text" placeholder="Enter Username" id="username" name="username" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" id="psw" name="psw" required>
<label for="email"><b>Email address</b></label>
<input type="text" placeholder="Email address" id="email" name="email" required>
<input type="submit" value="Submit" name="Submit">
</div>
</form>
index.php:
// Create connection
$dbc = #mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
OR die('Could not connect to MySQL: ' .mysqli_connect_error());
if(isset($_POST['Submit'])) {
$USER = (isset($_POST['username']) ? $_POST['username'] : null);
$PASSWORD = (isset($_POST['psw']) ? $_POST['psw'] : null);
$EMAIL = (isset($_POST['email']) ? $_POST['email'] : null);
$stmt = $dbc->prepare("INSERT INTO webapp_db.users (username, password, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $USER, $PASSWORD, $EMAIL);
$stmt->execute();
echo "New records created successfully";
} else{
die('Error: '.mysqli_error($dbc));
}
$stmt->close();
$dbc->close();
And I don't get any errors. It says: "New records created successfully" but nothing has been created
Any idea where the problem is? Thank you in advance
Try wrapping the checks into isset() statements like so:
// Create connection
$dbc = #mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die('Could not connect to MySQL: ' .mysqli_connect_error());
if(isset($_POST['Submit'])) {
$USER = (isset($_POST['username']) ? $_POST['username'] : null);
$PASSWORD = (isset($_POST['psw']) ? $_POST['psw'] : null);
$EMAIL = (isset($_POST['email']) ? $_POST['email'] : null);
$stmt = $dbc->prepare("INSERT INTO webapp_db.users (username, password, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $USER, $PASSWORD, $EMAIL);
$stmt->execute();
echo "New records created successfully";
} else{
die('Error: '.mysqli_error($dbc));
}
$stmt->close();
$dbc->close();
Ok, remember that execute function returns a boolean. Try to check if the query were executed with success or not:
$executed = $stmt->execute();
if ($executed == true) { // or just "if ($executed) {" if you prefer
echo "New records created successfully";
} else {
echo "Oops! Something went wrong";
}
But if you need something more precise, ... try with errorInfo function, that returns an array.
if ($executed == 1) {
echo "New records created successfully";
} else {
print_r($stmt->errorInfo());
}

submit a html form to mySQL using php

very new to this, i am currently trying to create a log in system for my website. i have created a html log in form which i plan to use for users to create accounts. i have created a php page which has my code to connect to the server which is shown below.
when i fill the form i dont get any output. I'm not sure if the php code is in the wrong place (it is as a separate file) or no output is expected. when a form is submitted, the database doesn't seem to change when i submit it manually while testing.
My end goal is to be able to add users to the table called users in my database.
Here is my code for my log in form:
<body>
<h2>Sign Up</h2>
<p></p>
<form action="Create_User.php" method="post">
<div class="imgcontainer">
<img src="http://fc05.deviantart.net/fs70/f/2012/361/1/6/albert_einstein_by_zuzahin-d5pcbug.jpg" alt="Einstein the lad" class="img" />
</div>
<div class="container">
<label><b>Username</b></label>
<input type="text" placeholder="Please Enter your desired Username" name="username" required />
<label><b>Password</b></label>
<input type="password" placeholder="Please Enter Your Desired Password" name="password" required />
<label><b>Email Address</b></label>
<input type="email" placeholder="Please Enter Your Email Address" name="email" required />
<label><b>Date Of Birth</b></label>
<input type="date" name="date_of_birth" required />
<label><b>First Name</b></label>
<input type="text" placeholder="Please Enter your first name" name="first_name" required />
<label><b>Surname</b></label>
<input type="text" placeholder="Please Enter your surname" name="surname" required />
</div>
<div class="container" style="background-color: #f1f1f1">
<button type="submit">Sign Up</button>
<button class="signinbtn" onclick="location.href='/AccountRelatedPages/SignIn.aspx'">Already have an account? Sign in here</button>
</div>
</form>
</body>
here is the code in my php file:
<?php
$servername = "localhost";
$username = "root";
$password = "rootpass";
$dbname = "synther_physics";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO users (username, password, email, date_of_birth, first_name, surname)
VALUES ('<?php echo $_POST[$username];', '<?php echo $_POST[$password];', '<?php echo $_POST[$email], <?php echo $_POST[$date_of_birth];, <?php echo $_POST[$first_name], <?php echo $_POST[$surname];')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Again very new to all this so im trying my best to get my head around so please bear that in mind.
Thanks.
Putting all together from the comments, sql injections, password_hash(). for sql injections protection then u need use prepared statements. I won't say much a lot of important things were said in the comments, hope you went through them all, because I did.
This is how your code should look :
<?php
$servername = "localhost";
$username = "root";
$password = "rootpass";
$dbname = "synther_physics";
//Validate user inputs
$username = $_POST['username'];
$password = $_POST['password'];
$hash = password_hash($password, PASSWORD_DEFAULT);
$email = $_POST['email']; //VALIDATE the email
$dob = $_POST['date_of_birth'];
$fname = $_POST['first_name'];
$sname = $_POST['surname'];
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO users (username, password, email, date_of_birth, first_name, surname)
VALUES (?,?,?,?,?,?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ssssss", $username, $hash, $email, $dob, $fname, $sname);
if ($stmt->execute()) {
echo "New record created successfully";
} else {
echo "Error : " . $conn->error; // on dev mode only
// echo "Error, please try again later"; //live environment
}
$conn->close();
?>
Edit :
if your php is on the same file and the html, then to avoid undefined indexes notice, you will need to check if the form was submitted, before processing. what you need to do is to have a name attribute to your form button.
then check if form is submitted.
<?php
$servername = "localhost";
$username = "root";
$password = "rootpass";
$dbname = "synther_physics";
//Validate user inputs
if(isset($_POST['buttonName'])){
$username = $_POST['username'];
$password = $_POST['password'];
$hash = password_hash($password, PASSWORD_DEFAULT);
$email = $_POST['email']; //VALIDATE the email
$dob = $_POST['date_of_birth'];
$fname = $_POST['first_name'];
$sname = $_POST['surname'];
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO users (username, password, email, date_of_birth, first_name, surname)
VALUES ('?,?,?,?,?,?')";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ssssss", $username, $hash, $email, $dob, $fname, $sname);
if ($stmt->execute()) {
echo "New record created successfully";
} else {
echo "Error : " . $conn->error; // on dev mode only
// echo "Error, please try again later"; //live environment
}
$conn->close();
}
?>
Also you need to check if fields are set and not empty.

Storing data entered when signing up

I need to create a sign up page that will store user name email passwords and put them in a database so that the user can then login and access a profile etc.
I have made a database database however nothing will go into it. I input one manually but anything I try to do from the webpage won't go to the database.
Code for the webpage: Signup is the page I want displayed and adduser is the code for adding the data to the database.
Signup:
<?php include '../view/header.php';
?>
<br>
<br>
<h1 class="light white-text text-lighten-3">Sign up!</h1>
<br>
<br>
<form class="form" id="signup" action="addUser.php" method="post">
<div class="form-group ">
<label for="email">Email</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter Your Email">
</div>
<br>
<div class="form-group ">
<input id="user_name" type="text" class="validate" name="user_name"required="required">
<label for="user_name">User Name</label>
</div>
<br>
<div class="form-group col s6">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password" placeholder="Enter a Password">
</div>
<br>
<br>
<button type="submit" class="orange btn btn-primary">Submit</button>
</form>
<?php
include '../view/footer.php';
AddUser:
<script src="../js/materialize.js" type="text/javascript"></script>
<script src="../js/materialize.min.js" type="text/javascript"></script>
<script src="../js/init.js" type="text/javascript"></script>
<?php
$server = "localhost";
$username = 'root';
$Password ="";
$database = 'commish';
$con = mysqli_connect($server, $username, $Password, $database);
$email = filter_input(INPUT_POST, 'email');
$user_name = filter_input(INPUT_POST, 'user_name');
$password = filter_input(INPUT_POST, 'password');
new_user( $user_name, $password,$email, $con);
function new_user($user_name, $password, $email,$con)
{
global $con;
$query = "INSERT into users (user_name, password, email) VALUES (:user_name, :password, :email)";
$statement = $con->prepare($query);
$statement->bindValue(":user_name", $user_name);
$statement->bindValue(":password", $password);
$statement->bindValue(":email", $email);
$statement->execute();
echo 'Successfully created new user';
}
There's no bindValue() method in mysqli, PDO has. So here are the two approaches to solve your problem:
1)mysqli method:
Use bind_param() method to bind variables to your prepared statement. So your new_user() function should be like this:
function new_user($user_name, $password, $email,$con){
$query = "INSERT into users (user_name, password, email) VALUES (?, ?, ?)";
$statement = $con->prepare($query);
$statement->bind_param("sss", $user_name, $password, $email);
if($statement->execute()){
echo 'Successfully created new user';
}else{
// query failed
}
}
NOTE: Since you're passing the connection handler $con to this function, there's no need to use global $con;. Plus Globals are evil.
2)PDO method:
Keep your new_user() function as it is and change this line
$con = mysqli_connect($server, $username, $Password, $database);
to
$con = new PDO("mysql:host=$server;dbname=$database",$username,$Password);
Sidenote: Never store password as a plain readable text, always perform salted password hashing on raw password before inserting it into the table.
There's no bindValue() method in mysqli, you should use bind_param()
new_user function :
function new_user ($user_name, $password, $email)
{
global $con;
$stmt = $con->prepare("INSERT into users (user_name, password, email) VALUES (?,?,?)";
$stmt->bind_param("sss", $user_name, $password, $email);
$stmt->execute();
$stmt_error = $stmt->error;
$stmt->close();
if ($stmt_error)
echo 'Error on create new user: '.$stmt_error;
else
echo 'Successfully created a new user';
}

Categories