Getting error: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined - php

I know what this error means, but I don't know why it is showing. I've checked names of variables, names of PDO variables, names of tables in database and still nothing.
If I copy insert into phpMyAdmin, it runs perfectly. If I change all variables from $this-> to 'abcd' it gives me the same error.
I really don't know what it is going on ...
Error:
SQLSTATE[HY093]: Invalid parameter number: parameter was not defined
Code:
class Users {
public $username = null;
public $password = null;
public $useremail = null;
public $steam_id = null;
public $salt = "Zo4rU5Z1YyKJAASY0PT6EUg7BBYdlEhPaNLuxAwU8lqu1ElzHv0Ri7EM6irpx5w";
public function __construct( $data = array() ) {
if( isset( $data['username'] ) ) $this->username = stripslashes( strip_tags( $data['username'] ) );
if( isset( $data['password'] ) ) $this->password = stripslashes( strip_tags( $data['password'] ) );
if( isset( $data['useremail'] ) ) $this->useremail = stripslashes( strip_tags( $data['useremail'] ) );
if( isset( $data['steam_id'] ) ) $this->steam_id = stripslashes( strip_tags( $data['steam_id'] ) );
}
public function storeFormValues( $params ) {
//store the parameters
$this->__construct( $params );
}
public function register() {
$correct = false;
try {
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql1 = "SELECT * FROM users WHERE user_name = :username LIMIT 1";
$polacz1 = $con->prepare( $sql1 );
$polacz1->bindValue( "username", $this->username, PDO::PARAM_STR );
$polacz1->execute();
$row = $polacz1->fetch();
$sql2 = "SELECT * FROM users WHERE user_email = :useremail LIMIT 1";
$polacz2 = $con->prepare( $sql2 );
$polacz2->bindValue( "useremail", $this->useremail, PDO::PARAM_STR );
$polacz2->execute();
$row1 = $polacz2->fetch();
$sql3 = "SELECT * FROM users WHERE steam_id = :steam_id LIMIT 1";
$polacz3 = $con->prepare( $sql2 );
$polacz3->bindValue( "steam_id", $this->steam_id, PDO::PARAM_STR );
$polacz3->execute();
$row2 = $polacz3->fetch();
if($row == NULL){
if($row1 == NULL){
if($row1 == NULL){
$checksum = bin2hex(mcrypt_create_iv(22, MCRYPT_DEV_URANDOM));
$sql = "INSERT INTO users(user_name, user_email, user_pass, steam_id, email_hash) VALUES(:username, :useremail, :password, :steamid, :emailhash)";
$polacz = $con->prepare( $sql );
$polacz->bindValue( ":username", $this->username, PDO::PARAM_STR );
$polacz->bindValue( ":useremail", $this->useremail, PDO::PARAM_STR );
$polacz->bindValue( ":password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR );
$polacz->bindValue( ":steamid", $this->steam_id, PDO::PARAM_STR );
$polacz->bindValue( ":emailhash", $checksum, PDO::PARAM_STR );
$polacz->execute();
return '<div class="alert alert-success" role="alert">Zostałeś pomyślnie zarejestowany. Sprawdź podany adres email i aktywuj swoje konto!</div>';
//return "Rejestracja przebiegła pomyślnie, możesz się zalogować.";
} else return '<div class="alert alert-danger" role="alert">Podany steam ID już istnieje.</div>';
}
else
{
return '<div class="alert alert-danger" role="alert">Podany e-mail już istnieje.</div>';
}
}
else
{
return '<div class="alert alert-danger" role="alert">Podany użytkownik już istnieje.</div>';
}
}catch( PDOException $e ) {
return $e->getMessage();
}
}
}

Related

PHP PDO login code - repeats error, not able to login [ correct username and password is entered]

I am struggling to get the login code to run successfully. It keeps on echoing the "Username or Password incorrect.." section, though the correct username and password in entered. Am I missing something somewhere, please help.
<?php
//Check login details
session_start();
//get user input from the form
if (isset($_POST['Submit'])) {
$username = checkData($_POST['username']);
$password = checkData($_POST['password']);
require ('config.php'); //database connection
global $dbselect;
$qry = 'SELECT username, password
FROM users
WHERE username = :username AND password = :password
LIMIT 1';
$statement = $dbselect->prepare($qry);
$statement->bindValue(':username', $username);
$statement->bindValue(':password', $password);
$statement->execute();
$login = $statement->fetch(PDO::FETCH_ASSOC);
if (count($login) > 0 && password_verify($password, $login['password'])) {
$_SESSION['username'] = $login['username'];
header('location:home.html');
} else {
echo "Username or Password incorrect. Please try again.";
}
$statement->closeCursor();
}
//validate data
function checkData($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
The following worked in test ( up to the password_verify where I used a different test as I have PHP 5.3.2 and hence no password_verify ) ~ hopefully it might prove of benefit.
<?php
session_start();
/* error messages used to display to user */
$ex=array(
0 => 'One or more required POST variables are not set',
1 => 'Both username & password are required',
2 => 'Failed to prepare SQL query',
3 => 'Query failed',
4 => 'No results',
5 => 'Invalid login details'
);
if( $_SERVER['REQUEST_METHOD']=='POST' ){
try{
if( isset( $_POST['Submit'], $_POST['username'], $_POST['password'] ) ) {
$username = !empty( $_POST['username'] ) ? filter_input( INPUT_POST, 'username', FILTER_SANITIZE_STRING ) : false;
$password = !empty( $_POST['password'] ) ? filter_input( INPUT_POST, 'password', FILTER_SANITIZE_STRING ) : false;
if( $username && $password ){
require('config.php');
global $dbselect;/* ??? */
/* use the username in the sql not password & username */
$sql='select `username`, `password`
from `users`
where `username` = :username';
$stmt=$dbselect->prepare( $sql );
/* only proceed if prepared statement succeeded */
if( $stmt ){
$stmt->bindParam( ':username', $username );
$status=$stmt->execute();
if( !$status )throw new Exception('',3);
$rows=$stmt->rowCount();
if( !$rows > 0 )throw new Exception('',4);
$result = $stmt->fetchObject();
$stmt->closeCursor();
/* password_verify is available from PHP 5.5 onwards ~ I have 5.3.2 :( */
if( $result && function_exists('password_verify') && password_verify( $password, $result->password ) ){
/* valid */
$_SESSION['username']=$username;
exit( header('Location: home.html') );
} else {
/* bogus - invalid credentials */
throw new Exception('',5);
}
} else {
/* sql prepared statement failed */
throw new Exception('',2);
}
} else {
/* either username or password was empty */
throw new Exception('',1);
}
} else {
/* one or more POST variables are not set */
throw new Exception('',0);
}
}catch( Exception $e ){
/* set a session variable to ensure error message is displayed only once */
$_SESSION['error']=$ex[ $e->getCode() ];
/* reload the login page with error code */
exit( header( 'Location: ?error=' . $e->getCode() ) );
}
}
?>
<!doctype html>
<html>
<head>
<title>Login</title>
</head>
<body>
<!-- the php/html login page -->
<form method='post'>
<input type='text' name='username' />
<input type='password' name='password' />
<input type='submit' name='Submit' value='Login' />
<?php
if( $_SERVER['REQUEST_METHOD']=='GET' && isset( $_GET['error'], $_SESSION['error'] ) ){
unset( $_SESSION['error'] );
/* display the error message */
echo "<h2 style='color:red'>{$ex[ $_GET['error'] ]}</h2>";
}
?>
</form>
</body>
</html>
/**
* You might need to save a hashed copy of the password at the point of
* user creation, so that you can password_verify the input password against the hashed
* copy returned from the DB.
* something like this :
* $hashed = password_hash($password, PASSWORD_BCRYPT);
* NOTE : I've changed you code to an extent, pls adapt.
*/
//Check login details
session_start();
//get user input from the form
if (isset($_POST['Submit'])) {
$username = checkData($username);
$password = checkData($password);
$dbname = "testo";
$servername = "localhost";
$conn = new PDO("mysql:host=$servername;dbname=$dbname", "root", "");
$parr = array($username,$password);
$qry = 'SELECT username, password, phashed
FROM users
WHERE username = ? AND password = ?
LIMIT 1';
$stmt = $conn->prepare($qry);
$Qres = $stmt->execute($parr);
$login = ($Qres) ? $stmt->fetchAll(PDO::FETCH_ASSOC) : array();
if (count($login) > 0 && password_verify($password, $login[0]['phashed'])) {
$_SESSION['username'] = $login[0]['username'];
header('location:home.html');
} else {
echo "Username or Password incorrect. Please try again.";
}
$conn = null;
}
//validate data
function checkData($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}

Prepared-statement MySQLI: INSERT doesn't work [duplicate]

This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 2 years ago.
I am a coding beginner and can't solve this error.I tried to create a login/register script but my INSERT statement doesn't work and I can't find the error:/ Sry for my bad english, I am german.
"Fatal error: Call to a member function bind_param() on boolean in"
if (isset($_POST['registrieren']) && $_POST['name'] != "" && $_POST['password'] != "")
{
$url = 'https://www.google.com/recaptcha/api/siteverify';
$privateKey = "???????????????????????????";
$response = file_get_contents($url . "?secret=" . $privateKey . "&response=" . $_POST['g-recaptcha-response'] . "&remoteip=" . $_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
if (isset($data->success) && $data->success == true)
{
$name = $_POST['name'];
$password = $_POST['password'];
$username_exists = $db->prepare("SELECT name from users WHERE name = ? ");
$username_exists->bind_param('s', $name);
$username_exists->execute();
if ($username_exists->num_rows) {
echo "<div class='fehler'>Name bereits vergeben!</div>";
} else {
$verschlüsseln = password_hash($password, PASSWORD_DEFAULT);
$insert = $db->prepare("INSERT INTO users (name, password) VALUES (?, ?)");
$insert->bind_param("ss", $name, $verschlüsseln);
$insert->execute();
$_SESSION['name'] = $name;
$_SESSION['password'] = $password;
header("Location: http://localhost/data/login/me.php");
}
} else {
echo "<div class='fehler'>Captcha-Check failed!</div>";
}
}
The error suggests that the prepare statement has failed but it's not clear which one. The code below is not tested and I wonder whether the accent on the u might have caused issues (?) so I renamed that variable to $hash
<?php
if( !empty( $_POST['registrieren'] ) && !empty( $_POST['name'] ) && !empty( $_POST['password'] ) && !empty( $_POST['g-recaptcha-response'] ) ){
$url = 'https://www.google.com/recaptcha/api/siteverify';
$privateKey = "6LdBNScTAAAAALrn5__S9lfV3EuSFu9Si_gwWeus";
$response = file_get_contents( $url . "?secret=" . $privateKey . "&response=" . $_POST['g-recaptcha-response'] . "&remoteip=" . $_SERVER['REMOTE_ADDR'] );
$data = json_decode( $response );
if( isset( $data->success ) && $data->success == true ) {
$name = $_POST['name'];
$password = $_POST['password'];
$stmt = $db->prepare("SELECT `name` from `users` WHERE `name` = ?;");
if( !$stmt ){
exit('Error preparing sql select statement');
}
$stmt->bind_param( 's', $name );
$stmt->execute();
if ( $stmt->num_rows ) {
echo "<div class='fehler'>Name bereits vergeben!</div>";
} else {
/* release results from previous cmd */
$stmt->free_result();
/* Is it possible that the accent on the 'u' caused problems? */
$hash = password_hash( $password, PASSWORD_DEFAULT );
$stmt = $db->prepare( "INSERT INTO `users` (`name`, `password`) VALUES (?, ?);" );
if( !$stmt ){
exit('Error preparing sql insert statement');
}
$stmt->bind_param( "ss", $name, $hash );
$stmt->execute();
/* again, free the results */
$stmt->free_result();
/* do you really want to store a password in a session variable? */
$_SESSION['name'] = $name;
$_SESSION['password'] = $password;
header("Location: http://localhost/data/login/me.php");
}
} else {
echo "<div class='fehler'>Captcha-Check failed!</div>";
}
}
?>

How to check if user already exist?

class Users {
public $username = null;
public $password = null;
public $salt = "Zo4rU5Z1YyKJAASY0PT6EUg7BBYdlEhPaNLuxAwU8lqu1ElzHv0Ri7EM6irpx5w";
public function __construct( $data = array() ) {
if( isset( $data['username'] ) ) $this->username = stripslashes( strip_tags( >$data['username'] ) );
if( isset( $data['password'] ) ) $this->password = stripslashes( strip_tags( >$data['password'] ) );
}
}
public function storeFormValues( $params ) {
$this->__construct( $params );
}
public function register() {
$correct = false;
try {
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "INSERT INTO users(username, password) VALUES(:username, :password)";
$stmt = $con->prepare( $sql );
$stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
$stmt->bindValue( "password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR );
$stmt->execute();
return "Registration Successful <br/> <a href='index.php'>Login Now</a>";
}catch( PDOException $e ) {
return $e->getMessage();
}
}
}
I would like to check if a user already exist in my database, because it lets me create accounts with same username anytime.
Thanks.
I would recommend a few things to help here.
1) Make your username column unique in the database. This would prevent usernames that are not unique from being inserted.
2) Once you have a unique index on username, attempt the insert, and check for success on the insert. Since you can get the error code from mysql, if the query was not successful and the error code is due to a duplicate value...throw the username already exists error.
This is the basic idea of how to return if the username exists.
public function username($username)
{
$sth = $this->db->prepare("SELECT id, username FROM table WHERE username = ?");
$sth->execute(array($username));
$row = $sth->fetch();
if(username == $row['username'])
{
do code here since username does not exist
} else {
echo 'username already exists';
}
}
$sell= mysql_query("select * from `signup` where emailid='$email'");
$cntc=mysql_num_rows($sell);
if($cntc==0) {
$sql=mysql_query("INSERT INTO `signup`(`firstname`,`lastname`,`emailid`,`dob`,`companyname`,`phoneno`,`password`) VALUES ('$name','$lastname','$email','$dob','$comname','$phone','$pass')");
if($sql) {
echo'inserted successfully';
}
} else {
echo'Email is already exist. ';
}

Get ID from table inside session user id

Hi I am trying to get value from userID column in my table inside the sessein array.
in my register class I have the following code:
<?php
class Users {
public $username = null;
public $password = null;
public $salt = "Zo4rU5Z1YyKJAASY0PT6EUg7BBYdlEhPaNLuxAwU8lqu1ElzHv0Ri7EM6irpx5w";
public function __construct( $data = array() ) {
if( isset( $data['username'] ) ) $this->username = stripslashes( strip_tags( $data['username'] ) );
if( isset( $data['password'] ) ) $this->password = stripslashes( strip_tags( $data['password'] ) );
}
public function storeFormValues( $params ) {
//store the parameters
$this->__construct( $params );
}
public function userLogin() {
$success = false;
try{
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT * FROM users WHERE username = :username AND password = :password LIMIT 1";
$stmt = $con->prepare( $sql );
$stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
$stmt->bindValue( "password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR );
$stmt->execute();
$valid = $stmt->fetchColumn();
if( $valid ) {
$success = true;
$_SESSION['userID'] = $user->user_id;
}
for which syntaxis I am not very sure that it will sessionize the UserID value of the logged user.
and in the login where the array is created I have
<?php
session_start();
include_once("config.php"); //include the settings/configuration
?>
<?php
//else look at the database and see if he entered the correct details
} else {
session_start();
$usr = new Users;
$usr->storeFormValues( $_POST );
if( $usr->userLogin() ) {
header( 'Location: cursos.php' ) ;
$_SESSION["loggedIn"] = true;
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
$_SESSION['userID'] = $_POST['userID'];
but it gives me every time NULL result how to fix it ?
first of all if you're posting the form you should use $_POST['userID'] and first check it if you retrieving the value in your $_POST['userID'] then you have to start session like this
session_start();
$_SESSION['userID'] = $_POST['userID']
but the first one code i understand you're using codeigniter or OOP $user->user_id the first $user is your variable and second one is user_id which may be your access modifier also check $user->user_id it has value then do same
session_start();
$_SESSION['userID'] = $user->user_id;

Set userid into the session array how?

Hello I am posting maybe 4th question about this issue but nobody can help me so far, so let's start from the begining, what I need is simple I need to: Set userID variable from column name "userID' inside table named "users" into the Sessions array: $_SESSION['userID']
here is my login page code:
<?php
session_start();
include_once("config.php"); //include the settings/configuration
?>
<?php if( !(isset( $_POST['login'] ) ) ) { ?>
<?php
//else look at the database and see if he entered the correct details
} else {
session_start();
$usr = new Users;
$usr->storeFormValues( $_POST );
if( $usr->userLogin() ) {
header( 'Location: cursos.php' ) ;
$_SESSION["loggedIn"] = true;
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
and here is my user class which operates the function login:
public function userLogin() {
$success = false;
try{
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT * FROM users WHERE username = :username AND password = :password LIMIT 1";
$stmt = $con->prepare( $sql );
$stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
$stmt->bindValue( "password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR );
$stmt->execute();
$result = $sth->fetch(PDO::FETCH_ASSOC);
$success = true;
if ($result!==false) { // Check there is a match
$_SESSION['userID']= $result['userID'];
}
$success = true;
$con = null;
return $success;
}catch (PDOException $e) {
echo $e->getMessage();
return $success;
The code is working fine I just want to add addition to it which will get the userID value from the column of the users table inside the database ans store it to the $_SESSION['userID'] after user is loged in.
So any idea how to reach this goal in my code ? thanks!
If you just want the UserID from the table, you're going to have to do a $stmt->fetch() to load it first, then you can store it in your SESSION.
So after the execute in function userLogin() do:
$result = $stmt->fetch(PDO::FETCH_ASSOC);
If the user was found $result will then contain all of the fields from the users table. So:
if ($result!==false) { // Check there is a match
$_SESSION['userID']= $result['userID'];
}

Categories