Code to submit data from login page to MySQL database - php

I have created a simple HTML Login page.
I have created a PHP file to transfer data to MySQL database(Using MySQL workbench 8.0)
However, when I click submit, a page just open with some code from my PHP file and no data is transferred to my database.
How can I transfer data from my Login page to my MYSQL database?
I have saved my PHP file in the C://
Code for Login Page:
<html>
<head>
<title>Login</title>
</head>
<body>
<form action="/Test1.php">
Username:<br>
<input type="text" value="username"><br>
Password:<br>
<input type="text" value="password"><br>
<input type="submit" value="submit"><br>
</form>
</body>
</html>
CODE for PHP:
<html>
<? php
$username = filter_input(INPUT_POST, 'username');
$password = filter_input(INPUT_POST, 'password');
if (!empty($username)){
if (!empty($password)){
$host = "localhost:3306";
$dbusername = "root";
$dbpassword = "";
$dbname = "login";
// Create Connection
$conn = new mysqli ($host, $dbusername, $dbpassword, $dbname);
if (mysql_connect_error()){
die ( 'Connect Error ('.mysqli_connect_errno().')'.mysqli_connect_error());
}
else {
$sql = "INSERT INTO login.user (username, password)
values ('$username', '$password')";
if ($conn->query($sql)){
echo "New record is inserted successfully";
}
else {
echo "Error:".$sql."<br>".$conn->error;
}
$conn->close();
}
}
else {
echo "Password should not be empty";
die ();
}
else {
echo "Username should not be empty";
die();
}
?>
</html>
I expect data from HTML file to be inputed in MYSQL Database but instead a new page open up with this:
query($sql)){ echo "New record is inserted successfully"; } else { echo "Error:".$sql."
".$conn->error; } $conn->close(); } } else { echo "Password should not be empty"; die (); } else { echo "Username should not be empty"; die(); } ?>

Try this:
<html>
<?php
$username = filter_input(INPUT_POST, 'username');
$password = filter_input(INPUT_POST, 'password');
if (empty($username)) {
echo 'Username should not be empty';
exit;
}
if (empty($password)) {
echo 'Password should not be empty';
exit;
}
$host = 'localhost:3306';
$dbusername = '';
$dbpassword = '';
$dbname = '';
// Create Connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
$connection = new mysqli($host, $dbusername, $dbpassword, $dbname);
} catch (Exception $exception) {
exit('Error connecting to database');
}
$connection->set_charset('utf8mb4');
try {
$statement = $connection->prepare("INSERT INTO login.user (username, password) values (?, ?)");
$statement->bind_param('ss', $username, $password);
$statement->execute();
$statement->close();
echo 'New record is inserted successfully';
} catch (Exception $exception) {
echo 'Error: ' . $exception->getMessage();
}
$connection->close();
?>
</html>

Related

Adding a back button

I want to add a back button to this php code I'm using. So once I enter in details and click "Register", I get ""New record is inserted sucessfully".
Which is great but I'd like to add a back button that can take me back to another page.
Below is my code. I have no idea where to place the back button either
<?php
$FirstName = filter_input(INPUT_POST, 'FirstName');
$LastName = filter_input(INPUT_POST, 'LastName');
$username = filter_input(INPUT_POST, 'username');
$Email = filter_input(INPUT_POST, 'email');
$password = filter_input(INPUT_POST, 'password');
if (!empty($username)){
if (!empty($password)){
$host = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "test";
// Create connection
$conn = new mysqli ($host, $dbusername, $dbpassword, $dbname);
if (mysqli_connect_error()){
die('Connect Error ('. mysqli_connect_errno() .') '
. mysqli_connect_error());
}
else{
$sql = "INSERT INTO details (Username, Password, FirstName, LastName, Email)
values ('$username','$password','$FirstName','$LastName','$Email')";
if ($conn->query($sql)){
echo "New record is inserted sucessfully";
}
else{
echo "Error: ". $sql ."
". $conn->error;
}
$conn->close();
}
}
else{
echo "Password should not be empty";
die();
}
}
else{
echo "Username should not be empty";
die();
}
?>
if ($conn->query($sql)){
echo "New record is inserted sucessfully";
echo '<button onclick="history.go(-1);">Back </button>';
}
OR
echo 'Back';

Check MySQL database for duplicates before posting new record

I would like to stop user registration if the registered name already exists.
Here is my code:
<?php
$username = filter_input(INPUT_POST, 'name');
$password = md5(filter_input(INPUT_POST, 'password'));
print_r($_POST['name']);
if (empty($username)){
echo "Username should not be empty"; die();
}
if (empty($password)){
echo "Password should not be empty"; die();
}
$host = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "db_account";
//create connection
$conn = new mysqli($host, $dbusername, $dbpassword, $dbname);
// Check the database for duplicate username
$username_check_query = "SELECT * FROM t_account WHERE name='$username' LIMIT 1";
$result = mysqli_query($db, $user_check_query);
$username = mysqli_fetch_assoc($result);
if ($username) { // if user exists
if ($username['name'] === $username) {
echo "Username already exists"; die();
}
}
// Register user
if (mysqli_connect_error()) {
die('Connect Error ('. mysqli_connect_error() .') ' . mysqli_connect_error());
} else {
$sql = "INSERT INTO t_account (name, pwd)
VALUES('$username', '$password')";
if ($conn->query($sql)){
echo " Account created successfully!";
}
else{
echo "Error: ". $sql."<br>". $conn->error;
}
$conn->close();
}
}
?>
I'm still a newbie so I got no idea if its even correct. I used a part from a template and edited that. Now when I try to register, it gives me Error 500..
<form action="" method="post">
<input type="text" name="name">
<input type="text" name="password">
<button type="submit">send</button>
</form>
<?php
$username = filter_input(INPUT_POST, 'name');
$password = md5(filter_input(INPUT_POST, 'password'));
print_r($_POST['name']);
if (empty($username)){
echo "Username should not be empty"; die();
}
if (empty($password)){
echo "Password should not be empty"; die();
}
$host = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "db_account";
//create connection
$conn = new mysqli($host, $dbusername, $dbpassword, $dbname);
// Check the database for duplicate username
$username_check_query = "SELECT * FROM t_account WHERE name='$username' LIMIT 1";
$result = mysqli_query($conn, $username_check_query);
$username_from_db = mysqli_fetch_assoc($result);
if ($username_from_db) { // if user
if ($username_from_db['name'] === $username) {
echo "Username already exists"; die();
}
}
// Register user
if (mysqli_connect_error()){
die('Connect Error ('. mysqli_connect_error() .') '
. mysqli_connect_error());
} else{
$sql = "INSERT INTO t_account (name, pwd)
VALUES('$username', '$password')";
if ($conn->query($sql)){
echo " Account created successfully!";
}
else{
echo "Error: ". $sql."<br>". $conn->error;
}
$conn->close();
}
?>

Where to put MD5 function to make it work?

I need to send md5 hashed password to database.
<?php
$username = filter_input(INPUT_POST, 'name');
$password = filter_input(INPUT_POST, 'password');
print_r($_POST['name']);
if (empty($username)){
echo "Username should not be empty"; die();
}
if (empty($password)){
echo "Password should not be empty"; die();
}
$host = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "db_account";
//create connection
$conn = new mysqli($host, $dbusername, $dbpassword, $dbname);
if (mysqli_connect_error()){
die('Connect Error ('. mysqli_connect_error() .') '
. mysqli_connect_error());
} else{
$sql = "INSERT INTO t_account (name, pwd)
values ('{$username}','MD5({$password})')";
if ($conn->query($sql)){
echo "Account was created successfully!";
}
else{
echo "Error: ". $sql."<br>". $conn->error;
}
$conn->close();
}
?>
When I fill register form with password for example 123456 it sends it to database like this (MD5)123456 but not as a hashed code.
Also after successfull registration it only shows text after #echo, is possible to redirect user to another page?
Try to use the PHP md5() function:
$password = md5(filter_input(INPUT_POST, 'password'));
Also your statement:
$sql = "INSERT INTO t_account (name, pwd)
values ('{$username}','{$password}')";
I strongly suggest you use prepared statements. Not hard to learn and time well invested.

Data not inserting into database when using pdo

i am learning pdo and i tried to play with CRUD method. I am trying to insert data into database using pdo but it isn't inserting. Below is my code
<?php
$username = $_POST['username'];
$password = password_hash($_POST['password'], PASSWORD_BCRYPT ));
try {
$query = $connect->prepare("INSERT INTO users(username, password) VALUES(?,?)");
$query->execute(array($username, $password));
echo "data";
}
catch (PDOException $event) {
echo $event->getMessage();
}
?>
i have this index file named as index.php
<?php
require_once 'db.php';
session_start();
session_regenerate_id();
?>
<!DOCTYPE html>
<html>
<head>
<title>Sign-Up/Login Form</title>
</head>
<?php
if ($_SERVER['REQUEST_METHOD'] == '$_POST') {
if (isset($_POST['login'])) {
require 'login.php';
}
elseif (isset($_POST['register'])) {
require 'register.php';
}
}
?>
<body>
<form action="index.php" method="POST">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" name="register" value="Submit">
</form>
</body>
</html>
my db.php looks like
<?php
try {
$connect = new PDO('mysql:dbname=pdologin;host=localhost', 'root', '$$$$');
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $event) {
$event->getMessage();
}
?>
The problem is that your code never reaches your require scripts (login.php or register.php) because your conditional is incorrect.
You have: if ($_SERVER['REQUEST_METHOD'] == '$_POST')
It should be if ($_SERVER['REQUEST_METHOD'] == 'POST')
You're going to end up with something like below while learning or doing some small script that will need a connection, in the long run wrapping this stuff in a function or using a small helper or framework can make this a little easy. Great idea to learn but its still tedious boiler plate no matter how many years you write this stuff.
<?php
//db settings that are typically in a config somewhere
$db_servername = "localhost";
$db_username = "username for your database";
$db_password = "password for your database";
$db_name = "your_db_name";
try {
$connect = new PDO("mysql:host=$db_servername;dbname=$db_name, $db_username, $db_password");
// set the PDO error mode to exception
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo "Connected successfully";
}catch(PDOException $e){
//echo "Connection failed: " . $e->getMessage();
}
$sth = $connect->prepare("INSERT INTO users(username, password) VALUES(:username,:password)");
$username = $_POST['username'];
$password = password_hash($_POST['password'], PASSWORD_BCRYPT );
$sth->bindValue(':username', $username, PDO::PARAM_STR);
$sth->bindValue(':password', $password, PDO::PARAM_STR);
$sth->execute();
as a example my team now just writes database binding code like
<?php
//array of ids to insert
$binds['ids'] = array(1,3,4,5,6,7,9,08098);
//Database class is auto included with every script
$success = Database::query('insert into my_table (id) values(:ids)',$binds);
connect first
$connect = mysqli_connect("localhost","root","root","my_db");
then remove the parameters when executing
$query->execute();
try this
<?php
$connect = mysqli_connect("localhost","root","root","my_db");
$username = $_POST['username'];
$password = password_hash($_POST['password'], PASSWORD_BCRYPT );
try {
$query = $connect->prepare("INSERT INTO users(username, password) VALUES('$username', '$password')");
$query->execute();
}
catch (PDOException $e) {
echo $e->getMessage();
}
?>

Data already Inserted I want to update the data

I am getting issue in update code.I am able to inserted data in database.I am passing null values in table. I want to update that null values.I am getting the sccessfully message but data is not updating. Please help me....
//Insert code
<?php
// Start the session
session_start();
?>
<?php
// Start the session
session_start();
?>
<?php
try{
$product=$_POST['product'];
/*
$product2=$_POST['product2'];
$product3=$_POST['product3'];
*/
// form data
//database Connection details
$servername = "localhost";
$username = "root";
$password = "";
$database="store";
$error = "";
$conn=mysql_connect($servername, $username, $password) or die('Connection failed: ' . mysql_error());
#mysql_select_db($database, $conn) or die("Could not select your database".mysql_error());
$insertQuery = "Insert into contactus(Id,Product) values('null','$product')";
$result = mysql_query($insertQuery);
if($result){
echo "<script>alert('Thank You. Your Data Received Succefully.');location.href = '../index.html';</script>";
}
else
{
echo "<script>alert('Something went wrong with your data inserted. Please fill the form again.');location.href = '../index.html';</script>";
}
mysql_close($conn);
header('Location: /newstore/contact.html');
}
catch(Exception $e) {
echo ("<script>alert('Something went terribly wrong. Please try again later.');location.href = ''../index.html';</script>");
return false;
}
?>
//Update code
<?php
// Start the session
session_start();
?>
<?php
try{
// form data
$name=$_POST['name'];
$email=$_POST['email'];
$mobile=$_POST['mobile'];
$product=isset($_POST['product']);
//database Connection details
$servername = "localhost";
$username = "root";
$password = "";
$database="store";
$error = "";
$conn=mysql_connect($servername, $username, $password) or die('Connection failed: ' . mysql_error());
#mysql_select_db($database, $conn) or die("Could not select your database".mysql_error());
;if ((strlen($name) < 3) or (strlen($email) < 3) or(strlen($mobile) < 3))
{
echo ("<script>alert('Something went wrong with your data inserted. Please fill the form again.');location.href = '../newstore/index.html';</script>");
}else
{
$UpdateQuery = "update contactus set Name='$name',Email='$email',Mobile='$mobile' where Id='(select count(*) from contactus)' ";
$result = mysql_query($UpdateQuery);
if($result){
echo "<script>alert('Thank You. Your Data Received Succefully.');location.href = '../newstore/index.html';</script>";
}
else
{
echo "<script>alert('Something went wrong with your data inserted. Please fill the form again.');location.href = '../newstore/index.html';</script>";
}
}
mysql_close($conn);
}
catch(Exception $e) {
echo ("<script>alert('Something went terribly wrong. Please try again later.');location.href = ''../newstore/index.html';</script>");
return false;
}
?>
I see no point in doing an Insert and then doing an Update. You already have all the data, so just Insert it all at once.
EDIT AFTER COMMENTS
First Handler:
<?php
start_session();
if(isset($_POST['product'])){
$product=$_POST['product'];
//database Connection details
$servername = "localhost";
$username = "root";
$password = "";
$database="store";
$error = "";
$mysqli = new mysqli($servername, $username, $password, $database);
/* check connection */
if (mysqli_connect_errno()) {
echo "<script>alert('Something went wrong with your data inserted. Please fill the form again. (" . mysqli_connect_error() . ")');location.href = '../newstore/index.html'</script>");
exit();
}
if ($result = $mysqli->query("INSERT INTO contactus (Id,Product) VALUES ('null','$product')")) {
// Grab new ID when INSERT is successfull, add it to Session
$_SESSION['contact_id'] = $mysqli->insert_id;
echo "<script>alert('Thank You. Your Data Received Succefully.');location.href = '../index.html';</script>";
} else {
echo "<script>alert('Something went wrong with your data inserted. Please fill the form again.');location.href = '../index.html';</script>";
$mysqli->close();
exit();
}
$mysqli->close();
}
header('Location: /newstore/contact.html');
?>
Second Handler:
<?php
start_session();
// form data
$name=isset($_POST['name'])?$_POST['name']:"";
$email=isset($_POST['email'])?$_POST['email']:"";
$mobile=$_POST['mobile'];
if ((strlen($name) < 3) || (strlen($email) < 3) || (strlen($mobile) < 3)){
echo "<script>alert('Something went wrong with your data inserted. Please fill the form again.');location.href = '../newstore/index.html';</script>";
exit();
}
//database Connection details
$servername = "localhost";
$username = "root";
$password = "";
$database="store";
$error = "";
$mysqli = new mysqli($servername, $username, $password, $database);
/* check connection */
if (mysqli_connect_errno()) {
echo "<script>alert('Something went wrong with your data inserted. Please fill the form again. (" . mysqli_connect_error() . ")');location.href = '../newstore/index.html'</script>");
exit();
}
if ($stmt = $mysqli->prepare("UPDATE contactus SET `Name`=?, `Email`=?, `Mobile`=?) WHERE `ID`=?")){
/* bind parameters for markers */
$stmt->bind_param("sssi", $name, $email, $mobile, $_SESSION['contact_id']);
/* execute query */
$stmt->execute();
$result = $stmt->get_result();
if($result){
echo "<script>alert('Thank You. Your Data Received Succefully.');location.href = '../newstore/index.html';</script>";
} else {
echo "<script>alert('Something went wrong with your data inserted. Please fill the form again.');location.href = '../newstore/index.html';</script>";
}
$stmt->close();
}
$mysqli->close();
?>

Categories