How to save data in my database with PHP - javascript

When I send data to my php file. Data is not getting stored in the database. My php code is below.
I am using one.com as my host. There I can use to php code using some components. So I gave an external link to the button to submit to php file.
But I cannot submit data to php code using button name or class attribute.
How can I store data in database using php file.
Please help me in this issue.Thank you in advance.
HTML:
<form method="post" action="register.php">
<div class="input-group">
<lable>Username</lable>
<input type="text" name="Username" required>
</div>
<div class="input-group">
<lable>Email</lable>
<input type="text" name="Email" required>
</div>
<div class="input-group">
<lable>Password</lable>
<input type="password" name="password_1" required></div>
<div class="input-group">
<lable>Confirm Password</lable>
<input type="password" name="password_2" required>
</div>
<p>Already a User?</p>
</form>
PHP:
<?php
$Username = "";
$Email = "";
$errors = array();
// connect to the database
$db = mysqli_connect('hostname', 'root', 'password', 'dbname');
echo "database connected";
// if the register button is clicked
$username = $_POST['Username'];
$email = $_POST['Email'];
$password_1 = $_POST['password_1'];
$password_2 = $_POST['password_2'];
echo "data is taken";
// if there are no errors, save user to database
$sql = "INSERT INTO Users(Username, Email, password) VALUES('$username',
'$email', '$password_1')";
mysqli_query($db, $sql);
echo "data inserted successfully";
?>

Is your database correct?
// connect to the database
$db = mysqli_connect('hostname', 'root', 'password', 'dbname');
echo "database connected";
And remember it always printed "database connected".

Related

Insert data from PHP to HTML

I have this PHP which picks up information from a form in HTML and I wanted to put that information on a div on other HTML
Nome: <?php
global $user;
$user = $_POST['user'];
echo ucfirst($user) ?>
<br />
Password: <?php
global $pass;
$pass = $_POST['pass'];
echo $pass ?>
<br />
Data de nascimento: <?php
global $date;
$date = $_POST['date'];
echo $date ?>
I have this HTML
// HTML that I get the information from
<form method="post" id="formDetails">
<label for="name">Nome: </label> <br>
<input type="text" id="username" name="user" placeholder="username"> <br> <br>
<label for="password">Password: </label> <br>
<input type="password" id="password" name="pass" placeholder="password"> <br> <br>
<label for="date">Nascimento: </label> <br>
<input type="text" name="date" id="datepicker" placeholder="Data de Nascimento"> <br> <br>
<button type="submit" id="btn">Submit </button>
</form>
// HTML that I want to insert the data
<h1> Dados Pessoais </h1>
<div>
<div class="mensagem" id="mensagem"></div>
</div>
And I'm using this js line
// AJAX PART
var uName = $("input[name=user]").val();
var passwrd = $("input[name=pass]").val();
var dat = $("input[name=date]").val();
$("#formDetails").submit(function(){
$.post('process.php', {user: uName, pass: passwrd, date: dat})
.done(function(data) {
window.location.href = 'informacoes.html';
$('.mensagem').html(data);
$('.mensagem').show();
});
});
I had this code before and it didn't work either
// AJAX PART
var uName = $("input[name=user]").val();
var passwrd = $("input[name=pass]").val();
var dat = $("input[name=date").val();
$("#formDetails").submit(function(){
$.ajax({
type: 'POST',
url: 'process.php',
data: $("form").serialize(),
success : function(data) {
if($("#mensagem").hasClass('mensagem')){
$(".mensagem").html(data);
$(".mensagem").show();
} else {
$(".back").html(data);
$(".back").show();
}
},
error: function (xhr,ajaxOptions,throwError){
alert("erro");
},
});
return false;
I tried to get the information from data and put it inside the div class "mensagem" and show her but when it submits goes to the other HTML neither shows me the div neither the information and when I inspected element on browser I put the div visible and the information wasn't there and I don't really know what to do and I searched and I couldn't find anything useful
You are just making it to complicated for a simple form.I would suggest you to make a connection.php file where in you connect you database to Your table
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "podcast";
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
create an index.php file.
Create a regular html submit form.
Include this button to your form.
<button type="submit" id="btn" name="submit-btn">Submit </button>
Add this piece of php code above and this creates a function to your button
<?php
require $connection;
if(isset($_POST['submit-btn'])){
$user = $_POST['user'];
$pass = $_POST['pass'];
$date = $_POST['date'];
try{
$insert_query = "INSERT INTO `table_name`(`column_1`, `column_2`, `column_3`) VALUES (:column_1, :column_2, :column_3)";
$query_exec = $con->prepare($insert_query);
$query_exec ->execute(array(":column_1" => $user, ":column_2" => $pass, ":column_3" => $date));
}
catch(PDOException $e) {
echo "Error: Data Insertion Failed";
}
}
?>

"Email is required" error in PHP registration script

I'm currently writing a script that preforms basic user registration.
When the user arrives on the landing page, I have a JS script that identifies their email from the URL and fills it in the email input box (which is disabled). After, the user just needs to put in their password to create an account. However, PHP throws the error "Email is required" even though it's been filled by the JS script.
I've tried to change the status of the input box to disabled to enabled which doesn't do much to help. I've attached the files involved in the process below. Any help would be greatly appreciated.
fillEmail.js
$(document).ready(function() {
var link = window.location.href;
var emailIndex = link.indexOf("email");
if(emailIndex != -1) {
link = link.substring(emailIndex + 6);
} else {
link = "";
}
document.getElementById("email").value = link;
//$('#email').attr('disabled', 'disabled');});
register.php
<?php include('server.php') ?>
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="header">
<h2>Register</h2>
</div>
<form method="post" action="register.php">
<?php include('errors.php'); ?>
<div hidden class="input-group">
<label>Username</label>
<input type="text" name="username" value="user">
</div>
<div class="input-group">
<label>Email</label>
<input type="email" name="email" id="email" value="<?php echo $email; ?>" disabled>
</div>
<div class="input-group">
<label>Password</label>
<input type="password" name="password_1">
</div>
<div class="input-group">
<label>Confirm password</label>
<input type="password" name="password_2">
</div>
<div class="input-group">
<button type="submit" class="btn" name="reg_user">Register</button>
</div>
</form>
</body>
<script
src="https://code.jquery.com/jquery-3.4.1.js"
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous">
</script>
<script type='text/javascript' src="fillEmail.js"></script>
</html>
server.php
<?php
session_start();
// initializing variables
$username = "";
$email = "";
$errors = array();
// connect to the database
$db = mysqli_connect('localhost', 'root', '', 'registration');
// REGISTER USER
if (isset($_POST['reg_user'])) {
// receive all input values from the form
$username = mysqli_real_escape_string($db, $_POST['username']);
$email = mysqli_real_escape_string($db, $_POST['email']);
$password_1 = mysqli_real_escape_string($db, $_POST['password_1']);
$password_2 = mysqli_real_escape_string($db, $_POST['password_2']);
// form validation: ensure that the form is correctly filled ...
// by adding (array_push()) corresponding error unto $errors array
if (empty($username)) { array_push($errors, "Username is required"); }
if (empty($email)) { array_push($errors, "Email is required"); }
if (empty($password_1)) { array_push($errors, "Password is required"); }
if ($password_1 != $password_2) {
array_push($errors, "The two passwords do not match");
}
// first check the database to make sure
// a user does not already exist with the same username and/or email
$user_check_query = "SELECT * FROM users WHERE username='$username' OR email='$email' LIMIT 1";
$result = mysqli_query($db, $user_check_query);
$user = mysqli_fetch_assoc($result);
if ($user) { // if user exists
if ($user['username'] === $username) {
array_push($errors, "Username already exists");
}
if ($user['email'] === $email) {
array_push($errors, "email already exists");
}
}
// Finally, register user if there are no errors in the form
if (count($errors) == 0) {
$password = md5($password_1);//encrypt the password before saving in the database
$query = "INSERT INTO users (username, email, password)
VALUES('$username', '$email', '$password')";
mysqli_query($db, $query);
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
}
}
?>
I'm fairly new to PHP so any help would be greatly appreciated. Thanks so much in advance!
As per my comment, you can simply use readonly instead of disabled to achieve a similar effect. Also please use prepared statements to protect against SQL injection. mysqli_real_escape_string is not enough
In order for the value to be submitted the field cannot be disabled.
Simple solution, create another fields as (hidden), these are submitted
<input type="email" id="email" value="<?php echo $email; ?>" disabled>
<input type="hidden" name="email" value="<?php echo $email; ?>">
Or you could simply change the attribute from disables to readonly

Game Login and Database [duplicate]

I am trying to create website with login form with some PHP code, were user will try to login with username and password and page will then show "welcome....". AT the moment when user try to put username and password website that shows up is blank, nothing is on it. Also i already have created mysql database with username and password.
this login form on my main page index.html:
<form id="form" method="post" action="login.php">
<label for="username">Username:</label>
<input type="text" name="username" size="15" required="required" />
<label for="password">Password:</label>
<input type="password" name="password" size="15" required="required" />
<input id="loginButton" type="submit" name="submit" value="LOGIN" />
</form>
and this is my php page login.php:
<?php
session_start();
$host = "localhost";
$username = "*******";
$password = "*******";
$db_name = "********";
$tbl_name = "users";
$conn = mysql_connect("$host", "$username", "$password") or die("Cannot connect");
mysql_select_db("$db_name", $conn) or die("Cannot connect");
$myusername = $_POST['username'];
$mypassword = $_POST['password'];
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql = "SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
if ($count == 1) {
session_register("username");
session_register("password");
header("location:page1.html");
} else {
echo "Wrong Username or Password";
}
?>
and on my welcome page - page1.html i have included some php code:
<?php
session_start();
if(!session_is_registered(username)){
header("location:index.html");
}
?>
First off...dont store the password in the session. Thats just asking for trouble.
session_register("password");
Secondly....session_register() is a deprecated function and shouldn't be used anymore.
Instead do...
$_SESSION['username'] = $myusername;
Third....
header("location:page1.html");
Should be a PHP file if you want sessions to work across pages..
header("location:page1.php");
Then in that PHP page do...
session_start();
if(!isset($_SESSION['username'])){
header("location:index.php");
} else {
// Display stuff to logged in user
}

Php login work only when mysqli_num_rows equal to Zero, otherwise doesn't work.I am stuck

here's the code guys please help me
if mysqli_num_rows==false Than code works but why num rows doesn't work i can't get it i tried everything but same error appears
<?php
//Start session
session_start();
//Include database connection details
require_once('db.php');
if(isset($_POST['submit'])){
$username=$_POST['username'];
$password=$_POST['password'];
$query="SELECT * FROM users WHERE username='$username' and password='$password'";
$result=mysqli_query($con,$query);
if($row=mysqli_num_rows($result)==1){
mysqli_fetch_array($con,$result);
echo 'Logged in';
header('location:profile.php');
}
else{
echo 'error occured';
}
}
?>
<form method="POST">
<input type="text" name="username" placeholder="username">
<input type="text" name="password" placeholder="password">
<input type="submit" name="submit">
</form>
<form method="POST">
<input type="text" name="username" placeholder="username">
<input type="text" name="password" placeholder="password">
<input type="submit" name="submit">
</form>
<?php
error_reporting(E_ALL); // check all type of error
ini_set('display_errors',1); // display those errors
session_start();
require_once('db.php');
if(!empty(trim($_POST['username'])) && !empty(trim($_POST['password']))){ // check with posetd value
$user_name = trim($_POST['username']);
$password = md5(trim($_POST['password']));
$query = "SELECT * FROM users where username='$username' and password = '$password'"; // don't use plain password, use password hashing mechanism
$result = mysqli_query($con,$query); // run the query
if(mysqli_num_rows($result)>0){ // if data comes
// here do some data assignment into session
header('location:profile.php'); // go to other page
}else{
echo "Login creadentials are not correct"; // else no user is there with the given credentials
}
}else{
echo "please fill the form value";
}
?>
Note:-
Read and use prepared statements to prevent your code from SQL Injection. :-http://us.php.net/manual/en/mysqli-stmt.prepare.php
Above file extension must be .php

Create modal alert instead of page redirect validation in PHP

I want to have server side validation. Is there a way how can I have the alert like this image whenever the user input the data like email that exist in my database, the alert will appear when I hit the sumbit button. Thanks in advance. :D
Here's my create_acc.html
<form action="create_acc.php" method="POST" id="fieldform">
<dl>
<p><dt>Email Address:</dt>
<dd>
<input type="text" name="e-mail" id="e-mail" class="text" placeholder="Your Email will be your log in" autocomplete="off">
</dd>
</p>
<p><dt>Create Password:</dt>
<dd>
<input type="password" name="password" id="password" class="text" placeholder="Remember your password" autocomplete="off">
</p>
<p>
<p><dt>Your Complete name:</dt>
<dd>
<input type="text" name="name" id="name" class="text" placeholder="Your Complete name" autocomplete="off">
</p>
<p>
<dt>
<input type="submit" value="Submit">
</dt>
</p>
</dl>
</form>
Here's my create_acc.php
<?php
session_start();
$email = $_POST['e-mail'];
$name = $_POST['name'];
$pass = $_POST['password'];
$hash = hash('sha256',$pass);
function createSalt(){
$text = md5(uniqid(rand(), true));
return substr($text,0,3);
}
$salt = createSalt();
$pass = hash('sha256',$salt.$hash);
$conn = mysqli_connect('localhost','root','','mydb');
$email = mysqli_real_escape_string($conn,$email);
$query = "INSERT INTO customers(Email,Password,Name,salt) VALUES('$email','$pass','$name','$salt')";
mysqli_query($conn,$query);
mysqli_close($conn);
header('Location: index.php');
?>
You could use ajax to do this. When the user submits the form you would send an ajax request with the form data to your php script, the script will then respond with a value that you use to deside if you should display an alert or not, here is a basic example using jquery:
$(document).ready(function() {
// catch submit events for your form
$('#your-form-id').submit(function() {
// make an ajax request to your validation script
$.ajax{(
url:'create_acc.php',
type:'POST',
data:$(this).serialize(),
dataType:'json',
success:function(response) {
if(!response.success) {
alert('Something went wrong!');
}
}
});
return false;
});
});
Then in your php script you return a code telling the client how it went:
// create_acc.php
// I assume the form only has one value 'email'
$success = false;
if(isset($_POST['email'])) {
// here you would check if the email already
// exists in the database
$query = "SELECT * FROM <table> WHERE email = ?";
$stmt = $con->prepare($query);
$stmt->bind_param('s', $_POST['email']);
// execute the query and check if a row was returned
}
// if everything went fine you should change success to true
// return json response to client
$response = array('success' => $success);
print json_encode($response);
exit;

Categories