submit a html form to mySQL using php - 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.

Related

Save login form data using php

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
?>

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();

Can't insert data with php into mysql

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

Inputting data from a HTML form to MYSQL using PHP error

I am having some trouble using PHP to input data into a MYSQL database from a form. Below I have included the files and I would just like to mention I've previously inputted data by changing the values:
VALUES ('Jake', 'Doe', 'john#example.com')";
and it works.
index.php
<?php include 'assets/header.php';$title='Home Page';?>
<div class="context">
<form action="connect_to_mysql.php" method="post">
<label>First Name:</label>
<input type="text" name="first_name" id="fist_name" required="required" placeholder="Please Enter First Name"/><br /><br />
<label>Last Name:</label>
<input type="text" name="last_name" id="last_name" required="required" placeholder="Please Enter Your Last Name"/><br/><br />
<label>Email:</label>
<input type="email" name="email" id="email" required="required" placeholder="Please Enter Your Email"/><br/><br />
<input type="submit">
</form>
</div>
<?php include 'assets/footer.php';?>
connect_to_mysql.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$first_name = mysql_real_escape_string($_POST['first_name']);
$last_name = mysql_real_escape_string($_POST['last_name']);
$email = mysql_real_escape_string($_POST['email']);
$sql = "INSERT INTO hello_world (firstname, lastname, email)
VALUES ('.$first_name', '.$last_name', '.$email')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Error:
Fatal error: Uncaught Error: Call to undefined function
mysql_real_escape_string() in
E:\XAMPP\htdocs\mysql\connect_to_mysql.php:14 Stack trace: #0 {main}
thrown in E:\XAMPP\htdocs\mysql\connect_to_mysql.php on line 14
Use this code and check if the error still comes up
Note: this code is connecting via the PDO class
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new PDO('mysql:host='.$servername.';dbname='.$dbname.';', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$first_name = mysql_real_escape_string($_POST['first_name']);
$last_name = mysql_real_escape_string($_POST['last_name']);
$email = mysql_real_escape_string($_POST['email']);
$sql = $conn->prepare("
INSERT INTO hello_world(first_name, lastname, email)
VALUES (:firstname, :lastname, :email)
");
$sql->execute([
'firstname' => $firstname,
'lastname' => $lastname,
'email' => $email
]);
if ($sql->rowCount() > 0) {
echo "New record created successfully";
}
else
{
//error message
}
?>

PHP/MySQL Creates Blank Record In Database

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 :(";
}

Categories