Please review/comment: php mysql javascript (not school) - javascript

Many thanks to everyone. The html is fine, i believe the javascript is a problem still, and php looks ok, but I need a few more pointers. I have edited my code as follows...
html:
<input name="uname" type="text" placeholder="please enter a user name" required><br />
<input name="upassword" type="text" placeholder="please enter a password or passphrase" required><br />
<input id="register" name="register" type="submit" class="btn btn-primary btn-lg outline" onclick="register();"/>
function register() {
javascript
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "register.php",
data: { name: "uname", password: "password"},
success: function (result) {
alert("success");
}
});
}
And my biggest problem, php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
define('USER', 'root');
define('PASS', 'Schwinny2156!');
try {
$conn = new PDO("mysql:host=localhost;dbname=users;", USER, PASS);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('INSERT INTO `users` (name, password VALUES (:name,:password)');
$stmt->bindParam(':name', $_POST['uname']);
$stmt->bindParam(':password', $_POST['upassword']);
$stmt->execute()
}
catch(PDOException $e)
{
echo $stmt . "<br>" . $e->getMessage();
}
$stmt = null;

I fixed up whatever looked wrong, not sure if I missed something.
Edit: forgot to mention, lookup password_hash and implement that. Storing password in plaintext is a no go.
Edit 2: Added the password hash function to get your started. Use password_verify to verify passwords on login.
<form onsubmit="return register(this);">
<input name="uname" type="text" placeholder="please enter a user name" required><br />
<input name="upassword" type="text" placeholder="please enter a password or passphrase" required><br />
<input id="register" name="register" type="submit" class="btn btn-primary btn-lg outline"/>
</form>
js
function register(form) {
$.post("register.php", $(form).serialize());
return false;
}
php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
define('USER', 'root');
define('PASS', 'password');
try {
$conn = new PDO("mysql:host=localhost;dbname=users;", USER, PASS);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
define('uname', $_POST['uname']);
$passwordHash = password_hash($_POST['upassword'], PASSWORD_DEFAULT);
define('upassword', $passwordHash);
$sql = 'INSERT INTO `users` (name , password) VALUES (?, ?)';
$conn->prepare($sql)->execute([uname, upassword]);
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>

Your Using GET method to Send Data From jQuery $.get("register.php");AND your accessing data from POST from PHP. Use $.post("register.php"); in jQuery or use $_GET in PHP

Related

How to save data in my database with PHP

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".

Angularjs validate

I want validate my form using ajax , but the errors are not showing properly.
Here is my code:
Html
<body ng-app="app" ng-controller="dkController">
<form ng-submit="dk()">
<label>Username</label>
<input type="text" name="username" ng-model="formdata.user">
{{errorName}}
<label>Password</label>
<input type="text" name="password" ng-model="formdata.pass">
<label>Email</label>
<input type="text" name="email" ng-model="formdata.email">
<button type="submit" >Submit</button>
{{message}}
</form>
</body>
Js
function dkController($http,$scope){
$scope.formdata={};
$scope.dk = function(){
$http({
method:"POST",
url:"dk.php",
data:$.param($scope.formdata)
})
.then(function(response){
$scope.errorName = response.data.errors.username;
})
and PHP
$conn= new mysqli('localhost','root','','dangky');
$username = isset($_POST['username']) ? trim($_POST['username']) : '';
$sql="SELECT *FROM dangky where username='$username'";
$result= mysqli_query($conn,$sql);
$errors=array();
$data=array();
if(empty($username))
$errors['username']='user name is required';
if(mysqli_num_rows($result)>0){
$row = mysqli_fetch_assoc($result);
if ($row['username'] == $username){
$errors['check'] = 'Tên đăng nhập đã tồn tại';
}
}
if(!empty($errors)){
$data['success']=false;
$data['errors']=$errors;
}
echo json_encode($data);
Error username is showing but errors check not showing .
This is the php output
{"success":false,"errors":{"username":"user name is required"}} .
The problem is youu passed $scope.formdata which contains
{ user : 'someone', pass: 'abc123!', email: 'me#medotcom' }
Your PHP script is looking for post data { username: 'someone' }
So rename your ng-model to ng-model="formdata.username" or change your PHP to find $_POST['user']. Your choice but they must match.

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;

Login form using PHP and JQuery to validate login information from MySQL database

I have a login form that uses JQuery and PHP to validate a username and password. I am trying to switch over from extension mysql to mysqli for better practice and am having a lot of trouble. I think the error exists in the JQuery somewhere because I've tested the login.php validation and it works fine.
So here is my code:
index.php:
<!doctype html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#login_a").click(function(){
$("#shadow").fadeIn("normal");
$("#login_form").fadeIn("normal");
$("#user_name").focus();
});
$("#cancel_hide").click(function(){
$("#login_form").fadeOut("normal");
$("#shadow").fadeOut();
});
$("#login").click(function(){
var username=$('#user_name').val();
var password=$('#password').val();
$.ajax({
type: "POST",
url: "login.php",
data: "name="+username+"&pwd="+password,
success: function(html){
if(html=='true'){
$("#login_form").fadeOut("normal");
$("#shadow").fadeOut();
$("#profile").html("<a href='logout.php' id='logout'>Logout</a>");
}
else{
$("#add_err").html("*Wrong username or password");
}
},
beforeSend:function(){
$("#add_err").html("Loading...")
}
});
return false;
});
});
</script>
</head>
<body>
<?php session_start(); ?>
<div id="profile">
<?php if(isset($_SESSION['user_name'])){ ?>
<a href='logout_script_2.php' id='logout'>Logout</a>
<?php }else {?>
<a id="login_a" href="#">login</a>
<?php } ?>
</div>
<div id="login_form">
<form action="login_script_2.php" method="POST">
<label>User Name:</label>
<input type="text" id="user_name" name="user_name" />
<label>Password:</label>
<input type="password" id="password" name="password" />
<label></label><br/>
<input type="submit" id="login" value="Login" />
<input type="button" id="cancel_hide" value="Cancel" />
</form>
<div class="err" id="add_err"><br></div>
</div>
<div id="shadow" class="popup"></div>
</body>
</html>
login.php
<?php
session_start();
$con = mysqli_connect("localhost","root","PW","db") or die("Connection error: " . mysqli_error($con));
if(isset($_POST['submit'])){
$username = $_POST['name'];
$password = $_POST['pwd'];
$stmt = $con->prepare("SELECT * FROM tapp_login WHERE username = ? AND password = ? LIMIT 1");
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$stmt->bind_result($username, $password);
$stmt->store_result();
if($stmt->num_rows == 1)
{
if($stmt->fetch())
{
$_SESSION['Logged'] = 1;
$_SESSION['user_name'] = $username;
echo 'Access granted';
exit();
}
}
else {
echo "*Wrong username or password";
}
$stmt->close();
}
else {
}
$con->close();
?>
logout.php
<?php
session_start();
unset($_SESSION['user_name']);
header('Location: index.php');
?>
All the attempts to run the code give me the error in the JQuery validation "*Wrong username or password". Thanks in advanced!
When logging in using ajax, you are not posting submit, so this line
if(isset($_POST['submit'])){
is never true so your code never executes.
Either change it to
if(isset($_POST['name'])){
or add it to your ajax posted data
data: "submit=true&name="+username+"&pwd="+password,
AJAX is a partial submission. Make sure you're firing it without using a submit button, or return false; inside your click function, at the bottom. I would use <input type='button' id='login_a' />, if it's not a link. Additionally, you are not setting your submit button, like #Sean said, because it's AJAX.

Categories