An invalid parameter was passed to sqlsrv_fetch_array - php

I'm using PHP web service for my android development back end. The connection with php and MSSQL Server are successful but unfortunately I stuck at this part:
<?php
session_start();
include "connect.php";
$user_name = $_POST["username"];
$user_pass = strval($_POST["password"]);
//echo $user_name;
//echo $user_pass;
//$user_name = "admin";
//$user_pass = "admin";
$mysql_qry="SELECT ID, Password FROM user WHERE (ID = '" . $_POST["username"] . "' AND Password = '" . $_POST["password"] . "')";
$result= sqlsrv_query($conn ,$mysql_qry);
$row = sqlsrv_fetch_array($result);
if($row) {
$_SESSION["ID"] = $row['ID'];
header ('location:../createUser.php');
}else{
die( print_r( sqlsrv_errors(), true));
}
?>
It shows error: An invalid parameter was passed to sqlsrv_fetch_array.
This is my login form:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<meta name="description" content="" />
<meta name="author" content="" />
<title>Login</title>
<!-- Custom fonts for this template-->
<link
href="vendor/fontawesome-free/css/all.min.css"
rel="stylesheet"
type="text/css"
/>
<link
href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i"
rel="stylesheet"
/>
<!-- Custom styles for this template-->
<link href="css/sb-admin-2.min.css" rel="stylesheet" />
</head>
<body class="bg-gradient-primary">
<div class="container">
<!-- Outer Row -->
<div class="row justify-content-center">
<div class="col-xl-10 col-lg-12 col-md-9">
<div class="card o-hidden border-0 shadow-lg my-5">
<div class="card-body p-0">
<!-- Nested Row within Card Body -->
<div class="row">
<img class="col-lg-6 d-none d-lg-block " src="img/Login.png">
<div class="col-lg-6">
<div class="p-5">
<div class="text-center">
<h1 class="h4 text-gray-900 mb-4">
Welcome To DEMO 1
</h1>
</div>
<form class="user" method="POST" action="php/login.php">
<div class="form-group">
<input
type="text"
name="username"
class="form-control form-control-user"
id="exampleInputEmail"
aria-describedby="emailHelp"
placeholder="Enter Username..."
/>
</div>
<div class="form-group">
<input
type="password"
name="password"
class="form-control form-control-user"
id="exampleInputPassword"
placeholder="Password"
/>
</div>
<button
class="btn btn-primary btn-user btn-block"
type="submit"
>
Login
</button>
</form>
<hr />
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Bootstrap core JavaScript-->
<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- Core plugin JavaScript-->
<script src="vendor/jquery-easing/jquery.easing.min.js"></script>
<!-- Custom scripts for all pages-->
<script src="js/sb-admin-2.min.js"></script>
</body>
</html>
I already check on the parameter and everything looks just fine. Why is the error keep occur?

I think you need one parameter in
$row = sqlsrv_fetch_array($result);
So , change to
$row = sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC)
Or , edit your query
$mysql_qry="SELECT ID, Password FROM user WHERE ID = '$user_name' AND Password = '$user_pass' ";

Consdier the following:
One possible explanation for your error is that you are concatenating user input to build the SQL statement. In fact, you are injecting your code. Never do this, always use prepared statements and parameterized queries to prevent SQL injection. With PHP Driver for SQL Server, function sqlsrv_query() does both statement preparation and statement execution and can be used to execute parameterized queries.
You need to hash the passowrd, because at the moment you are passing the password as plain text. When the password is hashed, you may safely pass it to the database.
Check the result from sqlsrv_query() execution.
As a note, you may use sqlsrv_has_rows() function to check if the result set has one or more rows.
The next example, based on your code, may help to get your expected results:
<?php
session_start();
include "connect.php";
$user_name = $_POST["username"];
$user_pass = strval($_POST["password"]);
$mysql_qry = "
SELECT ID, Password
FROM user
WHERE ID = ? AND Password = ?
";
$params = array($user_name, $user_pass);
$result = sqlsrv_query($conn, $mysql_qry, $params);
if ($result === false) (
echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
exit;
)
if (sqlsrv_has_rows($result)) {
// You don't even need to fetch the record, just use:
// $_SESSION["ID"] = $user_name;
// header ('location:../createUser.php');
$row = sqlsrv_fetch_array($result);
if ($row === false) {
echo "Error (sqlsrv_fetch_array): ".print_r(sqlsrv_errors(), true);
exit;
}
$_SESSION["ID"] = $row['ID'];
header ('location:../createUser.php');
} else {
echo "User not found";
exit;
}
?>

Related

getting Invalid Email or Password in my localhost website

i'm using php 7.2.31 .. i'v already imported my DB file in phpmyAdmin
when i'm trying to login in admin website page (or the others 2 users ) it's getting this message :-
(Invalid Email or Password )
the email address and password already in the database and it's correct .. ! !
here's my login-in code :-
<?php session_start();?>
<link rel="stylesheet" href="popup_style.css">
<!DOCTYPE html>
<html lang="en">
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<head>
<title>Admin Panel</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="description" content="#">
<meta name="keywords" content="Admin , Responsive">
<meta name="author" content="Nikhil Bhalerao +919423979339.">
<link href="https://fonts.googleapis.com/css?family=Open+Sans:400,600,800" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="files/bower_components/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="files/assets/icon/themify-icons/themify-icons.css">
<link rel="stylesheet" type="text/css" href="files/assets/icon/icofont/css/icofont.css">
<link rel="stylesheet" type="text/css" href="files/assets/css/style.css">
</head>
<body class="fix-menu">
<?php
include('connect.php');
extract($_POST);
if(isset($_POST['btn_login']))
{
$passw = hash('sha256', $_POST['password']);
function createSalt()
{
return '2123293dsj2hu2nikhiljdsd';
}
$salt = createSalt();
$pass = hash('sha256', $salt . $passw);
//echo $pass;
if($_POST['user'] == 'admin'){
$sql = "SELECT * FROM admin WHERE loginid='" .$email . "' and password = '". $pass."'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result);
//print_r($row);
$_SESSION["adminid"] = $row['id'];
$_SESSION["id"] = $row['id'];
$_SESSION["username"] = $row['username'];
$_SESSION["password"] = $row['password'];
$_SESSION["email"] = $row['loginid'];
$_SESSION["fname"] = $row['fname'];
$_SESSION["lname"] = $row['lname'];
$_SESSION['image'] = $row['image'];
$_SESSION['user'] = $_POST['user'];
}else if($_POST['user'] == 'doctor'){
$sql = "SELECT * FROM doctor WHERE loginid='" .$email . "' and password = '". $pass."'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result);
//print_r($row);
$_SESSION["doctorid"] = $row['doctorid'];
$_SESSION["id"] = $row['doctorid'];
$_SESSION["password"] = $row['password'];
$_SESSION["email"] = $row['loginid'];
$_SESSION["fname"] = $row['doctorname'];
$_SESSION['user'] = $_POST['user'];
}else if($_POST['user'] == 'patient'){
$sql = "SELECT * FROM patient WHERE loginid='" .$email . "' and password = '". $pass."'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result);
//print_r($row);
$_SESSION["patientid"] = $row['patientid'];
$_SESSION["id"] = $row['patientid'];
$_SESSION["password"] = $row['password'];
$_SESSION["email"] = $row['loginid'];
$_SESSION["fname"] = $row['patientname'];
$_SESSION['user'] = $_POST['user'];
}
//print_r($row);
$count=mysqli_num_rows($result);
if($count==1 && isset($_SESSION["email"]) && isset($_SESSION["password"])) {
{
?>
<div class="popup popup--icon -success js_success-popup popup--visible">
<div class="popup__background"></div>
<div class="popup__content">
<h3 class="popup__content__title">
Success
</h3>
<p>Login Successfully</p>
<p>
<!-- <button class="button button--success" data-for="js_success-popup"></button> -->
<?php echo "<script>setTimeout(\"location.href = 'index.php';\",1500);</script>"; ?>
</p>
</div>
</div>
<!-- <script>
window.location="index.php";
</script> -->
<?php
}
}
else {?>
<div class="popup popup--icon -error js_error-popup popup--visible">
<div class="popup__background"></div>
<div class="popup__content">
<h3 class="popup__content__title">
Error
</h3>
<p>Invalid Email or Password</p>
<p>
<button class="button button--error" data-for="js_error-popup">Close</button>
</p>
</div>
</div>
<?php
}
}
?>
<?php
$que="select * from manage_website";
$query=$conn->query($que);
while($row=mysqli_fetch_array($query))
{
//print_r($row);
extract($row);
$business_name = $row['business_name'];
$business_email = $row['business_email'];
$business_web = $row['business_web'];
$portal_addr = $row['portal_addr'];
$addr = $row['addr'];
$curr_sym = $row['curr_sym'];
$curr_position = $row['curr_position'];
$front_end_en = $row['front_end_en'];
$date_format = $row['date_format'];
$def_tax = $row['def_tax'];
$logo = $row['logo'];
}
?>
<section class="login-block">
<div class="container-fluid">
<div class="row">
<div class="col-sm-12">
<div class="auth-box card" >
<div class="text-center">
<image class="profile-img" src="uploadImage/Logo/<?php echo $logo; ?>" style="width: 60%"></image>
</div>
<div class="card-block" >
<div class="row m-b-20">
<div class="col-md-12">
<h5 class="text-center txt-primary">Sign In</h5>
</div>
</div>
<form method="POST" >
<div class="form-group form-primary">
<select name="user" class="form-control" required="">
<option value="">-- Select One --</option>
<option value="admin">Admin</option>
<option value="doctor">Doctor</option>
<option value="patient">Patient</option>
</select>
<span class="form-bar"></span>
</div>
<div class="form-group form-primary">
<input type="email" name="email" class="form-control" required="" placeholder="Email">
<span class="form-bar"></span>
</div>
<div class="form-group form-primary">
<input type="password" name="password" class="form-control" required="" placeholder="Password">
<span class="form-bar"></span>
</div>
<div class="row m-t-25 text-left">
<div class="col-12">
<div class="forgot-phone text-right f-right">
Forgot Password?
</div>
</div>
</div>
<div class="row m-t-30">
<div class="col-md-12">
<button type="submit" name="btn_login" class="btn btn-primary btn-md btn-block waves-effect text-center m-b-20">LOGIN</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<script type="text/javascript" src="files/bower_components/jquery/js/jquery.min.js"></script>
<script type="text/javascript" src="files/bower_components/jquery-ui/js/jquery-ui.min.js"></script>
<script type="text/javascript" src="files/bower_components/popper.js/js/popper.min.js"></script>
<script type="text/javascript" src="files/bower_components/bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript" src="files/bower_components/jquery-slimscroll/js/jquery.slimscroll.js"></script>
<script type="text/javascript" src="files/bower_components/modernizr/js/modernizr.js"></script>
<script type="text/javascript" src="files/bower_components/modernizr/js/css-scrollbars.js"></script>
<script type="text/javascript" src="files/bower_components/i18next/js/i18next.min.js"></script>
<script type="text/javascript" src="files/bower_components/i18next-xhr-backend/js/i18nextXHRBackend.min.js"></script>
<script type="text/javascript" src="files/bower_components/i18next-browser-languagedetector/js/i18nextBrowserLanguageDetector.min.js"></script>
<script type="text/javascript" src="files/bower_components/jquery-i18next/js/jquery-i18next.min.js"></script>
<script type="text/javascript" src="files/assets/js/common-pages.js"></script>
</body>
<!-- for any PHP, Codeignitor or Laravel work contact me at mayuri.infospace#gmail.com -->
</html>
and the check-login file :-
<?php
session_start();
if((isset($_SESSION["email"]) && isset($_SESSION["password"]))){
$myemail = $_SESSION['email'];
}else {
header("location:login.php");
}
?>
thanks !
You are getting
invalid Email and password because the variable $email which you are using in your query has no email from the form. After this line:
$pass = hash('sha256', $salt . $passw);
Add this line:
$email = $_POST['email'];
This will solve your problem. But there are many other other problems in your code like it is open to SQL injection. You can use prepare statements.
PHP Prepared Statements. Always validate the data coming from users.
Do not store password as a plain text. See here password-encryption-storing-password-in-session
If you want to get only one record from a database always use LIMIT 1 in your code.

PHP page keeps redirecting to itself, wiping login form fields [duplicate]

This question already has answers here:
PHP isset $_session equal to string
(1 answer)
How to use store and use session variables across pages?
(8 answers)
Closed 2 years ago.
I'm working on a login page using PHP with the intent of the page to take the user to landing page. There is a database set up with all the form fields populated and I set up test code to verify if the fields were being pulled properly and they were. But when the login website itself is being used, it redirects to itself no matter what the fields are filled with and wipes the fields clean. I've tried several different things with how the page was being called but still cannot get it to do anything other than wipe the fields clean and redirect to a clean version of itself. Here is the relevant code
<?php
session_start();
include 'config.php';
if(isset($_SESSION['user'])!="" && isset($_SESSION['store'])!=""){
header('Location: http://server-ip/landing.php');
exit();
}
$error = false;
if($_SERVER["REQUEST_METHOD"] == "POST" && ($_POST['btn-login'])){
$storeid = $_POST['Store'];//grabs store someone is logging in to
$userid = trim($_POST['userID']); //grabs user ID, sql injection cleaning
$userid = strip_tags($userid);
$userid = htmlspecialchars($userid);
$pass = trim($_POST['passhash']); //grabs the user password, sql injection cleaning
$pass = strip_tags($pass);
$pass = htmlspecialchars($pass);
if(empty($storeid)){
$error = true;
$storeError = "Please select a store.";
}
if(empty($userid)){
$error = true;
$useridError = "Please enter your User ID.";
} else if (!filter_var($userid, FILTER_VALIDATE_INT)){
$error = true;
$useridError = "Please enter a valid User ID.";
}
if(empty($pass)){
$error = true;
$passError = "Please enter your password.";
}
//if no errors, continue
if(!$error){
$password = hash('sha256', $pass);
$res=mysqli_query($conn,"SELECT userID, passhash FROM User WHERE userID='$userid'");
$row = mysqli_fetch_array($res);
$count = mysqli_num_rows($res); //if userID and password are correct 1 row should be returned.
$sres=mysqli_query($conn,"SELECT storeID FROM Store WHERE storeID='$storeid'");
$srow = mysqli_fetch_array($sres);
if( $count == 1 && $row['password']==$password){
$_SESSION['user'] = $row['userID'];
$_SESSION['store'] = $srow['storeID'];
$_SESSION["loggedin"] = true;
header('Location: http://http://server-ip/landing.php');
exit();
} else{
$errMSG = "The userID or Password you entered was incorrect. Please try again.";
}
}
}
?>
<!doctype html>
<html lang="en">
<head>
<title>PIMSHOE Login</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<body>
<div class="container-fluid jumbotron text-center bg-primary text-white" style="margin-bottom:0">
<h1>PIMSHOE Admin</h1>
</div>
<?php if(isset($useridError) || isset($errMSG) ||isset($storeError) || isset($passError)) { ?>
<div role="alert" class="alert alert-danger text-center">
<?php
if(isset($useridError)) { echo $Error; }
if(isset($passError)) { echo $passError; }
if(isset($errMSG)) { echo $errMSG; }
if (isset($storeError)) { echo $storeError; }
?>
</div>
<?php } ?>
<div class="row mt-5">
<div class="col-sm-4">
</div>
<div class="col-sm-4">
<h2 class="text-center mb-4 mt-1">Sign in</h2>
<form id="loginform" class="form-horizontal" role="form" method="post" action="landing.php" accept-charset='UTF-8'>
<div class="form-group">
<label for="store"></label>
<?php
echo('<select class="form-control" id="store">
<option>Select Store</option>');
$sqli = "SELECT StoreID FROM Store";
$result = mysqli_query($conn, $sqli);
while($row = mysqli_fetch_array($result)){
echo('<option>'.$row['StoreID'].'</option>');
}
echo('</select>');
?>
</select>
</div>
<hr>
<div class="form-group">
<input type="text" name="user_name" class="form-control" maxlength="4" pattern="^[0-9]{4}" id="userID" placeholder="User ID">
</div>
<div class="form-group">
<input type="password" name="user_pass" class="form-control" id="password" placeholder="*********">
</div>
<div class="form-group">
<button id="btn-login" name="btn-login" type="submit" class="btn btn-primary btn-block bg-primary"> Login </button>
</div>
</form>
<!--Sign up Admins insert new users, maybe have it go to a form that sends a request email to an admin?-->
<p class="underlineHover">Forgot password?</p>
</div>
</div>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>
I think the problem is with your first if statement.
The function isset returns a boolean (true or false) and you are comparing its return with "". You could write the statement in one of the two ways:
if(isset($_SESSION['user']) && isset($_SESSION['store'])){
or
if($_SESSION['user']!="" && $_SESSION['store']!=""){

fail to create account via php on mysql database

I´m having trouble creating data onto a MySQL database via a php that I created in order to be able to create an account on a website I´m making I have the following php files that take care of the process (linked below), I have been looking to these lines of code for hours and I'm not able to figure out what is wrong with it ....
signup.php
<?php
require 'db.php';
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>AlojArt Reservas</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- styles -->
<link href="css/styles.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
</head>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (isset($_POST['login'])) { //user logging in
require 'login.php';
}
elseif (isset($_POST['register'])) { //user registering
require 'register.php';
}
}
?>
<body class="login-bg">
<div class="header">
<div class="container">
<div class="row">
<div class="col-md-12">
<!-------------------- Logo -------------------->
<div class="logo">
<h1>AlojArt Reservas</h1>
</div>
</div>
</div>
</div>
</div>
<div class="page-content container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="login-wrapper">
<div id="register">
<div class="box">
<form action="signup.php" method="post" autocomplete="off">
<div class="content-wrap">
<h6>Criar conta</h6>
<input class="form-control" type="text" placeholder="Nome" name="nome_titular">
<input class="form-control" type="text" placeholder="Nome de utilizador " name="username">
<input class="form-control" type="password" placeholder="Palavra-passe" name="password">
<input class="form-control" type="email" placeholder="Endereço de e-mail" name="email">
<div class="action">
<button class="btn btn-primary btn-lg" name="register" />Criar conta</button>
</div>
</div>
</form>
</div>
</div>
<div class="already">
<div id="login">
<p>Já tem conta?</p>
Iniciar sessão
</div>
</div>
</div>
</div>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://code.jquery.com/jquery.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="bootstrap/js/bootstrap.min.js"></script>
<script src="js/custom.js"></script>
</body>
</html>
register.php
<?php
require 'db.php';
session_start();
$_SESSION['nome_titular'] = $_POST['nome_titular'];
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
$_SESSION['email'] = $_POST['email'];
// Escape all $_POST variables to protect against SQL injections
$nome_titular = $mysqli->escape_string($_POST['nome_titular']);
$username = $mysqli->escape_string($_POST['username']);
$email = $mysqli->escape_string($_POST['email']);
$password = $mysqli->escape_string(password_hash($_POST['password'], PASSWORD_BCRYPT));
// Check if user with that email already exists
$result = $mysqli->query("SELECT * FROM Utilizador WHERE email='$email'") or die($mysqli->error());
// We know user email exists if the rows returned are more than 0
if ( $result->num_rows > 0 ) {
$_SESSION['message'] = 'O utilizador jรก existe!';
header("location: error.php");
}
else { // User doesn't already exist in a database, proceed...
$sql = "INSERT INTO Utilizador (nome_titular, username, email, password)"
. "VALUES ('$nome_titular','$username','$email','$password')";
// Add user to the database
if ( $mysqli->query($sql) ){
$_SESSION['logged_in'] = true;
header("location: dashboard.php");
}
else {
$_SESSION['message'] = "O registo falhou!";
header("location: error.php");
}
}
?>
EDIT: added db.php
db.php
<?php
/* Database connection settings */
$host = 'CENSORED';
$user = 'CENSORED';
$pass = 'CENSORED';
$db = 'projeto2_dcw';
$mysqli = new mysqli($host,$user,$pass,$db) or die($mysqli->error);
?>
I see there is no space ' ' before VALUES, this would cause failure of SQL.
Change your SQL to
$sql = "INSERT INTO Utilizador (nome_titular, username, email, password)"
. " VALUES ('$nome_titular','$username','$email','$password')";
If you still getting unexpected result, then please put following code to else get the error and comment out everything else.
printf("Error: %s\n", $mysqli->error);
==Update==
"Error: Duplicate entry '0' for key 'PRIMARY"
It refers to primary key constraint violation, in other word, you are trying to insert new value 0, which is already present in same column. Since, primary key doesn't allow duplicate. It is failing and falling to else block. To correct this issue, you need to make sure, you don't have duplicate entry for column which has primary key.
I see there is no connection for your page thats why it gets redirected to error.php change your db connection to this
<?php
$host = 'CENSORED';
$user = 'CENSORED';
$pass = 'CENSORED';
$db = 'projeto2_dcw';
$con = mysqli_connect("$host,$user,$pass,$db") or die($mysqli->error);
mysqli_select_db($con,"your db name");
?>
in the form change button
<button type="submit" class="btn btn-primary btn-lg" name="register" />Criar conta
ALTER TABLE Your table name
ADD PRIMARY KEY (ID);

Login with php and html

I am making a login page using html and php, i did a simple one which was working fine using these code :
HTML
Login Form
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="login">
<div class="login-triangle"></div>
<h2 class="login-header">Login</h2>
<form class="login-container" method="post" action="Login.php">
<p><input type="text" id="username" name="username" placeholder="Username"></p>
<p><input type="password" id="password" name="password" placeholder="Password"></p>
<p><input type="submit" value="Login"></p>
</form>
</div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
</body>
</html>
PHP
<?php
include ("dbconfig.php");
session_start();
$name = mysqli_real_escape_string($dbconfig, $_POST['username']); //to clean up, to avoid sql injection
//$name = md5($name);
$pw = mysqli_real_escape_string($dbconfig, $_POST['password']);
// $pw = md5($pw);
$sql_query="SELECT userid FROM user WHERE username='$name' AND password='$pw'";
$result = mysqli_query($dbconfig, $sql_query);
$row = mysqli_Fetch_array ($result, MYSQLI_ASSOC);
$count = mysqli_num_rows ($result);
if ($count >0){
$_SESSION['Login'] = $name;
header ("location:Welcome.php");
}
if($count == 1)
{
echo "wrong login details";
}
?>
But when i try to do the login with a new html file using the same php file it wont work at all, it keep saying "wrong login details" even though i am putting the right login in.
Here is the new html, i am thinking maybe it has to do with the additional classes which was added.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Kate's World Sign In</title>
<!-- Google Fonts -->
<link href='https://fonts.googleapis.com/css? family=Roboto+Slab:400,100,300,700|Lato:400,100,300,700,900' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="css/animate.css">
<!-- Custom Stylesheet -->
<link rel="stylesheet" href="css/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"> </script>
</head>
<body>
<Form method="post" action="Login.php">
<div class="container">
<div class="top">
<h1 id="title" class="hidden"><span id="logo">Log <span>In</span></span></h1>
</div>
<div class="login-box animated fadeInUp">
<div class="box-header">
<h2>Log In</h2>
</div>
<label for="username">Username</label>
<br/>
<input type="text" id="username" name="username" >
<br/>
<label for="password">Password</label>
<br/>
<input type="password" id="password" name="password">
<br/>
<button type="submit">Sign In</button>
<br/>
</div>
</div>
</Form>
</body>
<script>
$(document).ready(function () {
$('#logo').addClass('animated fadeInDown');
$("input:text:visible:first").focus();
});
$('#username').focus(function() {
$('label[for="username"]').addClass('selected');
});
$('#username').blur(function() {
$('label[for="username"]').removeClass('selected');
});
$('#password').focus(function() {
$('label[for="password"]').addClass('selected');
});
$('#password').blur(function() {
$('label[for="password"]').removeClass('selected');
});
</script>
</html>
No, the additional classes should not effect your PHP code.
To solve the problem, you need to see what you are receiving on the PHP side. Stick in a few tests - echo out some data. First, at the very beginning. Then, when you know for sure what is comign through, move your tests down the file a bit. Work out all the bugs, then remove all the tests.
For example, start by modifying your PHP like this:
<?php
session_start();
include ("dbconfig.php");
$name = mysqli_real_escape_string($dbconfig, $_POST['username']); //to clean up, to avoid sql injection
echo 'Name: ' . $name. '<br>';
$pw = mysqli_real_escape_string($dbconfig, $_POST['password']);
echo 'Password: ' . $pw. '<br>';
die();
Then, move down the file a bit and do this:
$sql_query="SELECT userid FROM user WHERE username='$name' AND password='$pw'";
$result = mysqli_query($dbconfig, $sql_query);
$row = mysqli_Fetch_array ($result, MYSQLI_ASSOC);
$count = mysqli_num_rows ($result);
echo 'Rows found: ' .$count. '<br>';
if ($count >0){
echo 'Inside count > 0<br>';
$_SESSION['Login'] = $name;
header ("location:Welcome.php");
}else{
echo 'Inside count ELSE<br>';
echo "wrong login details";
}
Notes:
PHP header() method will not work if other header messages have been sent. Alternative: echo '<meta http-equiv="refresh" content="0; url=http://new.example.com/address" />';
Note McKenzma's observations about your if ($count >0){ code: both IF statements will be true if $count==1.
Note that session_start() should be the very first instruction in your PHP file. See my example code above
You should have used if and else, not if and if.
<?php
$count = mysqli_num_rows ($result);
if ($count >0){
$_SESSION['Login'] = $name;
header ("location:Welcome.php");
} else {
echo "wrong login details";
}
?>
Your 2nd conditional should be "$count != 1". You want to return exactly one row for a successful login.

Can't figure out where $_SESSION['x'] goes to store registration form data to session

I am going crazy trying to learn how to use sessions to store values of custom fields in my registration_form.php so I can call the data on other pages. I have read all sorts of websites but nobody seems to explain where exactly I am supposed to put the code to capture the data. I have two custom registration fields I added to a script (bio and displayname). I tried inserting this code on the registration form at the top and bottom and also on a register.php (both scripts below).
Where does the code go to store these fields to a session? I know it is wrong below because at this point I have tried placing it everywhere in everyway I can....
//registration_form.php
<?php session_start();
$_SESSION['displayname'] = $displayname;
$_SESSION['bio'] = $bio;
$author = $_SESSION['displayname'];
$bio = $_SESSION['bio'];
?>
<HTML>
<head>
<title>Practice</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="css/style.css" rel="stylesheet" media="screen">
</head>
<body>
<script src="js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/jquery.validate.js"></script>
<div class="logo">
<h2><?php include('db.php'); echo $logotxt; ?></h2>
</div>
<form class="form-horizontal" id="register_form" method="post">
<h2>Register</h2>
<div class="line"></div>
<div class="control-group">
<input type="text" id="inputEmail" name="email" placeholder="Email">
</div>
<div class="control-group">
<input type="text" id="inputuserid" name="username" placeholder="Username">
</div>
<div class="control-group">
<input type="text" id="displayname" name="displayname" placeholder="Display name">
</div>
<div class="control-group">
<textarea name="bio" class="textfield" id="bio" cols="25" rows="7" placeholder="Bio
(optional). Tell us about yourself."></textarea>
</div>
<button type="submit" class="btn btn-large btn-primary btn-sign-in" data-loading-
text="Loading...">Register</button>
Sign in
<div class="messagebox">
<div id="alert-message"></div>
</div>
</form>
<?php
// starting the session
session_start();
if (isset($_POST['Submit'])) {
$_SESSION['displayname'] = $displayname;
$_SESSION['bio'] = $bio;
}
?>
//register.php
<?php
include("db.php");
$con=mysql_connect($server, $db_user, $db_pwd) //connect to the database server
or die ("Could not connect to mysql because ".mysql_error());
mysql_select_db($db_name) //select the database
or die ("Could not select to mysql because ".mysql_error());
//prevent sql injection
$username=mysql_real_escape_string($_POST["username"]);
$displayname=mysql_real_escape_string($_POST["displayname"]);
$password=mysql_real_escape_string($_POST["password"]);
$email=mysql_real_escape_string($_POST["email"]);
$bio=mysql_real_escape_string($_POST["bio"]);
//check if user exist already
$query="select * from ".$table_name." where username='$username'";
$result=mysql_query($query,$con) or die('error');
if (mysql_num_rows($result))
{
die($msg_reg_user);
}
//check if user exist already
$query="select * from ".$table_name." where email='$email'";
$result=mysql_query($query,$con) or die('error');
if (mysql_num_rows($result))
{
die($msg_reg_email);
}
session_start();
$_SESSION['displayname'] = $displayname;
$_SESSION['bio'] = $bio;
$activ_key = sha1(mt_rand(10000,2222).time().$email);
$hashed_password = crypt($password);
$query="insert into ".$table_name."(username,displayname,password,email,activ_key,bio)
values ('$username','$displayname','$hashed_password','$email','$activ_key','$bio')";
if (!mysql_query($query,$con))
{
die('Error: ' . mysql_error());
}
I am not sure what you are trying to here but should not your form action in regisration_form.php be set to register.php?
<form class="form-horizontal" id="register_form" method="post" action="register.php">
Then you form will be submitted to register.php. The way you have set up Session in register.php is basically correct. To access the session value in other pages do:
$displayname= $_SESSION['displayname'];
$bio=$_SESSION['bio'];

Categories