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());
}
Related
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)
html webpage screenshotphp code shown on button clickmySql database tableI need to store user login data. i am using phpMyAdmin. When I click on submit button, data is not stored. Instead the php code is shown. Both code files are given below. What I am doing wrong. Help me. I
am unable to store user data using phpmyadmin in xampp.
my html code
<html>
<head>
<title>Yahoo Signin And Signup Form</title>
</head>
<body>
<h2 style="color: midnightblue">yahoo!</h2>
<hr color="magenta">
<form method="post" action="connect.php" >
<fieldset style="background:#6495ED;">
<legend style="padding:20px 0; font-size:20px;">Signup:</legend>
<label for ="firstName">Enter First Name</label><br>
<input type="text" placeholder="First name" id="firstName" name ="firstName">
<br>
<label for ="lastName">Enter Last Name</label><br>
<input type="text" placeholder="Last name" id="lastName" name ="lastName">
<br>
<label for ="email">Enter Email</label><br>
<input type="text" placeholder="Email" id="email" name ="email"><br>
<label for ="password">Enter Password</label><br>
<input type="password" placeholder="Password" id="password" name ="password">
<br>
<label for ="number">Enter Mobile Number</label><br>
<input placeholder="03---" id="number" name ="number"><br>
<label for ="date">Enter Date of Birth</label><br>
<input type="text" placeholder="DD/MM/YY" id="date" name ="date"><br>
<label for ="gender">Enter Gender</label><br>
<input type="text" placeholder="Male/Female/Other" id="gender" name
="gender"><br>
<br><button style="background-color:orangered;border-
color:dodgerblue;color:lightyellow">Signup</button>
</fielsdet>
</form>
</body>
</html>
my connect.php
<?php
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$password = $_POST['password'];
$number = $_POST['number'];
$date = $_POST['date'];
$gender = $_POST['gender'];
// Making Connection with database
$con = new mysqli('localhost','root','','phpdata');
if ($con -> connect_error) {
die('Connection failed :'.$conn -> connect_error);
}
else{
$stmt = $con->query("INSERT INTO signup(firstName, lastName, email, password,
number, date, gender)
values(?,?,?,?,?,?,?)");
$stmt->bind_param("ssssiss",$firstName, $lastName, $email, $password,
$number, $date, $gender);
$stmt->execute();
echo "Sign up successful";
$stmt->close();
$con->close();
}?>
Use prepare instead of query. All everything is ok.:
$stmt = $con->prepare("INSERT INTO signup(firstName, lastName, email, password, number, date, gender)
values(?,?,?,?,?,?,?)");
And make button type as submit:
<br><button type="submit" style="background-color:orangered;border-color:dodgerblue;color:lightyellow">Signup</button>
here is the code, it works fine with me
<?php
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$password = $_POST['password'];
$number = $_POST['number'];
$date = $_POST['date'];
$gender = $_POST['gender'];
// Making Connection with database
$con = new mysqli('localhost','root','','phpdata');
if ($con -> connect_error) {
die('Connection failed :'.$conn -> connect_error);
}
else{
$stmt = $con->query("INSERT INTO signup(firstName, lastName, email, password, number, date, gender)
values("'.$firstName.'","'.$lastName.'","'.$email.'","'.$password.'","'.$number.'","'.$date.'","'.$gender.'")");
if ($con->query($stmt) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$con->close();
}//end of else of connection
?>
Add type in your submit button.
<button type='submit' style="background-color:orangered;border-color:dodgerblue;color:lightyellow">Signup</button>
and also your question marks and params ara not matching. it should be match. otherwise data won't store your db
correct that line also
The main problem is you are not loading code via apache server try to open http://localhost/signup.html instead of C:/xmapp/htdocs/connect.php
It seems you want to user PDO but your connection string not correct
<?php
$firstName = trim($_POST['firstName']);
$lastName = trim($_POST['lastName']);
$email = trim($_POST['email']);
$password = md5(trim($_POST['password']));
$number = trim($_POST['number']);
$date = trim($_POST['date']);
$gender = trim($_POST['gender']);
$con= new PDO("mysql:host=127.0.0.1;dbname=phpdata", 'root', 'root');
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sqli = "INSERT INTO signup(firstName, lastName, email, password, number, date, gender)
values(?,?,?,?,?,?,?)";
try {
$stmt= $con->prepare($sqli);
$stmt->bindParam(1,$firstName);
$stmt->bindParam(2,$lastName);
$stmt->bindParam(3,$email);
$stmt->bindParam(4,$password);
$stmt->bindParam(5,$number);
$stmt->bindParam(6,$date);
$stmt->bindParam(7,$gender);
$status = $stmt->execute();
echo "Sign up successful";
$stmt->close();
$con->close();
} catch(PDOException $e) {
echo "Error ".$e->getMessage();
}
?>
another problem is with your html form button type is missing
<button type="submit".... />
Here is the complete code after analyzing it for a lot of time. in your $stmt variable there was no query, it was empty. This code works fine just copy and paste it.
<?php
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$password = $_POST['password'];
$number = $_POST['number'];
$date = $_POST['date'];
$gender = $_POST['gender'];
// Making Connection with database
$con = new mysqli('localhost','root','','abc');
if ($con -> connect_error) {
die('Connection failed :'.$conn -> connect_error);
}
else{
$sql = "INSERT INTO signup(firstName, lastName, email, password, number, date, gender)
values('$firstName','$lastName','$email','$password','$number','$date','$gender')";
if ($con->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
$con->close();
}//end of else of connection
?>
so i am working on the simple project and i dont know why, but i can't insert data into the database
Here is my connection to database
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$database = "register";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $register);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
And in this part of code i am trying to insert data:
<?php
if (isset($_POST['submitreg'])){
$username = mysqli_real_escape_string($conn, $_POST['username']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$sql = "INSERT INTO users (email, username, password) VALUES ('$email', '$username', '$password')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
header("Location: signin.php");
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
mysqli_close($conn);
?>
And then i am inserting the code, i am getting this error:
Error: INSERT INTO users (email, username, password) VALUES ('gerulisjonas#gmail.com', 'jonas2422', 'password')
Thank you in advance :)
extra:
Form
<form id="register" class="signinform" action="includes/registerinc.php" method="post">
<div class="formcenter">
<input type="text" name="username" value="" placeholder="user name"><br>
<input type="email" name="email" value="" placeholder="email"><br>
<input type="password" id="passwordid" name="password" value="" placeholder="password"><br>
<input type="password" name="passwordtwo" value="" placeholder="repeat password"><br>
<input type="submit" name="submitreg" class="btn btn-success" value="Register"></input>
</div>
</form>
When creating your connection you named the variable that holds the database name $database, but when you pass it along to mysqli_connect you are using $register.
Try this instead:
$database = "register";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
Hey guys sorry I did bother you, i just run trough my code and i found that i did not included connection.php file in my register.php file
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.
i have been staring at this page for half an hour trying to figure out where i am going wrong. The first two variables are found and inserted into database, however the last two, 'email' and 'password' are not found, not inserted into database but still however pass the if statement. Any help will be much appreciated.
Form.php
<form name="signup" method="POST" action="signup.php">
<label for="signupFirstName">First Name</label>
<input type="text" id="signupFirstName" name="signupFirstName" />
<label for="signupLastName">Last Name</label>
<input type="text" id="signupLastName" name="signupLastName"/>
<label for="signupEmail">Email</label>
<input type="text" id="signupEmail" name="signupEmail" />
<label for="signupConfirmEmail">Confirm Email</label>
<input type="text" id="signupConfirmEmail" name="signupConfirmEmail"/>
<label for="signupPassword">Password</label>
<input type="text" id="signupPassword" name="signupPassword"/>
<label for="signupConfirmPassword">Confirm Password</label>
<input type="text" id="signupConfirmPassword" name="signupConfirmPassword"/>
<button name="submit" type="submit" >Submit Form</button>
</form>
signup.php
<?php
if (isset($_POST['signupFirstName']) || isset($_POST['signupLastName']) || isset($_POST['signupEmail']) || isset($_POST['signupPassword']) ) {
echo $_POST['signupEmail'];
$mysqli = new mysqli('localhost', 'user1', 'password', 'db2');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $mysqli->prepare("INSERT INTO members (First_Name, Last_Name, Email, Password) VALUES (?,?,?,?)");
$stmt->bind_param('ssss',$sample,$lastName,$email,$password);
// escape the POST data for added protection
$sample = isset($_POST['signupFirstName'])
? $mysqli->real_escape_string($_POST['signupFirstName'])
: '';
$lastName = isset($_POST['signupLastName'])
? $mysqli->real_escape_string($_POST['signupLastName'])
: '';
$email = isset($_POST['signupEmail'])
? $mysqli->real_escape_string($_POST['signupEmail'])
: '';
$password = isset($_POST['signupPassword'])
? $mysqli->real_escape_string($_POST['signupPassword'])
: '';
/* execute prepared statement */
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
/* close statement and connection */
$stmt->close();
/* close connection */
$mysqli->close();
}
else{
echo "broken";
}
?>
You seem to be binding the params to your query before you actually set the variables. Move the bind_param() call above the execute() call.
You can also refactor your code to take out a lot of the junk. Example below:
<?php
function arr_get($array, $key) {
if (isset($array[$key])) {
return $array[$key];
}
return '';
}
if (isset($_POST['signupFirstName']) || isset($_POST['signupLastName']) || isset($_POST['signupEmail']) || isset($_POST['signupPassword']) ) {
echo $_POST['signupEmail'];
$mysqli = new mysqli('localhost', 'user1', 'password', 'db2');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $mysqli->prepare("INSERT INTO members (First_Name, Last_Name, Email, Password) VALUES (?,?,?,?)");
$stmt->bind_param('ssss', arr_get($_POST, 'signupFirstName'), arr_get($_POST, 'signupLastName'), arr_get($_POST, 'signupEmail'), arr_get($_POST, 'signupPassword'));
/* execute prepared statement */
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
/* close statement and connection */
$stmt->close();
/* close connection */
$mysqli->close();
}
else {
echo "broken";
}
?>