Register new user - Problem with SQLSTATE - php

Implementing a simple register system and after implementing try to test it I get this error message:
SQLSTATE[HY093]: Invalid parameter number: parameter was not defined
My code for register user is:
<?php
session_start();
require_once('config.php');
if(isset($_POST['submit']))
{ if(isset($_POST['name'],$_POST['lastname'],$_POST['email'],$_POST['pass']) && !empty($_POST['name']) && !empty($_POST['lastname']) && !empty($_POST['email']) && !empty($_POST['pass']))
{
$name= trim($_POST['name']);
$lastname = trim($_POST['lastname']);
$email= trim($_POST['email']);
$pass= trim($_POST['pass']);
$options = array("cost"=>4);
$hashPassword = password_hash($pass,PASSWORD_BCRYPT,$options);
$date = date('Y-m-d H:i:s');
if(filter_var($email, FILTER_VALIDATE_EMAIL))
{
$sql = 'SELECT * FROM members WHERE email = :email';
$stmt = $pdo->prepare($sql);
$p = ['email'=>$email];
$stmt->execute($p);
if($stmt->rowCount() == 0)
{
$sql = "insert into members (name, lastname, email, `pass`, created_date,updated) values(:name,:lastname,:email,:pass,:created_date,:updated)";
try{
$handle = $pdo->prepare($sql);
$params = [
':name'=>$name,
':lastname'=>$lastname,
':email'=>$email,
':pass'=>$hashPassword,
':created_date'=>$date,
':updated'=>$date
];
$handle->execute($params);
$success = 'Successfull registration!';
}
catch(PDOException $e){
$errors[] = $e->getMessage();
}
}
else
{
$valName= $name;
$valLastname= $lastname;
$valEmail= '';
$valPass= $pass;
$errors[] = 'Email address already registered';
}
}
else
{
$errors[] = "Email address is not valid";
}
}
else
{
if(!isset($_POST['name']) || empty($_POST['name']))
{
$errors[] = 'Error 1!';
}
else
{
$valIme= $_POST['name'];
}
if(!isset($_POST['lastname']) || empty($_POST['lastname']))
{
$errors[] = 'Error 2!';
}
else
{
$valLastname= $_POST['lastname'];
}
if(!isset($_POST['email']) || empty($_POST['email']))
{
$errors[] = 'Error 4!';
}
else
{
$valEmail= $_POST['email'];
}
if(!isset($_POST['pass']) || empty($_POST['pass']))
{
$errors[] = 'Error 5!';
}
else
{
$valPass= $_POST['pass'];
}
}
}
?>
I don't get where the problem could be. I think is that I need to change the date value inserted to the database, and that could be a problem. Can someone test this code and tell me where is the problem?

Related

PHP Login Code not working - Database Connection is okay

I'm trying to set up a Register + Login for one of my Sites. The Registration process works completely fine but the Login seems to fail every time.
This is the register.php
<?php
require_once "config.php";
require_once "session.php";
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
$fullname = trim($_POST['name']);
$email = trim($_POST['email']);
$password = trim($_POST['password']);
$confirm_password = trim($_POST['confirm_password']);
$password_hash = password_hash($password, PASSWORD_BCRYPT);
if($query = $db->prepare("SELECT * FROM users WHERE email =?")) {
$error = '';
$query->bind_param('s', $email);
$query->execute();
$query->store_result();
if ($query->num_rows >0) {
$error .= '<p class="error">E-Mail already registered</p>';
}
if (empty($confirm_password)) {
$error .= '<p class="error">Passwords do not match.</p>';
}
if (empty($error)) {
$insertQuery = $db->prepare("INSERT INTO users (name, email, password) VALUES (?, ?, ?);");
$insertQuery->bind_param("sss", $fullname, $email, $password_hash);
$result = $insertQuery->execute();
if ($result) {
$error .= '<p class="success">Your Registration was succesful!</p>';
} else {
$error .= '<p class="error">Something went wrong!</p>';
}
}
}
$query->close();
$insertQuery->close();
mysqli_close($db);
}
?>
This is the Login.php
<?php
require_once "config.php";
require_once "session.php";
$error = '';
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
$email = trim($_POST['email']);
$password = trim($_POST['password']) ;
if (empty($email)) {
$error .= '<p class="error">Please enter email.</p>';
}
if (empty($password)) {
$error .= '<p class="error">Please enter password.</p>';
}
if (empty($error)){
if($query = $db->prepare("SELECT * FROM users WHERE email = ?")) {
$query->bind_param('s',$email);
$query->execute();
$row = $query->fetch();
if ($row) {
if (password_verify($password, $row['password'])) {
$_SESSION["userid"] = $row['id'];
$SESSION["user"] = $row;
header("location: index2.php");
exit;
}else{
$error.= '<p class="error">The password is not valid.</p>';
}
}else{
$error.= '<p class="error">Wrong mail.</p>';
}
}
$query->close();
}
mysqli_close($db);
}
?>
According to Online PHP Checker my Code should be correct. There are no Errors in Console and I really don't know what exactly i did wrong. Hope someone can help me with this!
This line is the issue, I expect:
$row = $query->fetch();
According to the documentation, the fetch() function returns true, false or null - it does not return a row of data. You need to use bind_result() to map the results from the query into variables.
https://www.php.net/manual/en/mysqli-stmt.fetch.php

localhost: data not going into database

i am trying to make a registration system but when i register the data isn't there.
i tried to search same questions but i couldn't find the issue, and the worst is that the script detect the database but wont get the data in.
The PHP script :
<?php
$bdd = new PDO('mysql:host=127.0.0.1;dbname=fireblock', 'root', '');
if(isset($_POST['submitform'])) {
$username = htmlspecialchars($_POST['username']);
$email = htmlspecialchars($_POST['email']);
$email2 = htmlspecialchars($_POST['email2']);
$pass = sha1($_POST['pass']);
$pass2 = sha1($_POST['pass2']);
if(!empty($_POST['username']) AND !empty($_POST['email']) AND !empty($_POST['email2']) AND !empty($_POST['pass']) AND !empty($_POST['pass2'])) {
$usernamelength = strlen($username);
if($usernamelength <= 255) {
if($email == $email2) {
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
$reqemail = $bdd->prepare("SELECT * FROM members WHERE email = ?");
$reqemail->execute(array($email));
$emailexist = $reqemail->rowCount();
if($emailexist == 0) {
if($pass == $pass) {
$insertmbr = $bdd->prepare("INSERT INTO members(username, email, pass) VALUES(?, ?, ?)");
$insertmbr->execute(array($username, $email, $pass));
$error = "Your account has been created! Connect";
} else {
$error = "Your passs are not the same!";
}
} else {
$error = "Email already used!";
}
} else {
$error = "Your email is invalid!";
}
} else {
$error = "Your emails are not the same!";
}
} else {
$error = "Your username can't get upper than 255 characters!";
}
} else {
$error = "Every fields should be filled!";
}
}
?>

PDOException: in C:\wamp64\www\Fireblock\index.php on line 3

Help i wanna make a register system but when i try to access the page on localhost it say me this :
Fatal error: in C:\wamp64\www\Fireblock\index.php on line 3
PDOException: in C:\wamp64\www\Fireblock\index.php on line 3
Idk what's wrong in line 3 since i was following a tutorial oof
My php script :
<?php
try {
$bdd = new PDO('mysql:host=127.0.0.1;dbname=fireblock;', 'root', ''); //where is the error
if (isset($_POST['submitform'])) {
$username = htmlspecialchars($_POST['username']);
$email = htmlspecialchars($_POST['email']);
$email2 = htmlspecialchars($_POST['email2']);
$pass = password_hash($_POST['password']);
$pass2 = password_hash($_POST['password2']);
if (!empty($_POST['username']) AND !empty($_POST['password']) AND !empty($_POST['password2'])) {
$usernamelength = strlen($username);
if ($usernamelength <= 255) {
if ($email == $email2) {
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
if ($password == $password2) {
$insertmember = $bdd->prepare("INSERT into members(username, email, password) VALUES(?, ?, ?)");
$insertmember->execute(array(
$username,
$email,
$password
));
$error = "Your account has been created!";
} else {
$error = "Your passwords aren't the same!";
}
} else {
$error = "Your email address isn't valid!";
}
} else {
$error = "Your emails aren't the same!";
}
} else {
$error = "Your username can't be higher than 255 characters!";
}
} else {
$error = "Every fields should be completed!";
}
}
} catch (PDOException $ex) {
print $ex->getMessage();
}
?>
I putted all the PHP part
Try
$bdd = new PDO('mysql:host=127.0.0.1;dbname=fireblock', 'root', '');
i have removed a semi-colon at the end of the last key/value pair (after fireblock) as it is not used in any code examples i used for comparrison with your code.

Cannot make register to work with reCAPTCHA2

I cannot make the register to work with recaptcha but it work normally without it
<?php
require_once("database.php");
$conn= pdo_con();
ini_set('SMTP','smtp.intnet.mu');
ini_set('smtp_port',25);
ini_set('sendmail_from','admin#example.co.uk');
if(!empty($_POST) || isset($_POST['regis_submit'])){
// Should the code be place here cause I already try it. //
$errors = array();
if (empty($_POST['firstname']) || empty($_POST['regis_username']) || empty($_POST['lastname']) || empty($_POST['inputEmail'])
|| empty($_POST['phone_num']) || empty($_POST["gender"]) || empty($_POST['regis_pass']) || empty($_POST["postal_address"])
|| empty($_POST["DateField"]) ){
$errors[] = 'Value(s) in the form missing, please fill them all out!';
exit();
} else if(!preg_match ('%^[A-Za-zÀàÂâÇçÉéÈèÊêËëÔôÙùÎîÏïÛûÜü\.\' \-]{2,15}$%', $_POST['firstname'])){
$errors['firstname'] = '<p><font color="red">Please enter your first name!</font></p>';
exit();
} else if ( etc...
}
else if (count($errors) > 0) {
foreach($errors as $error) {
echo $error;
}
} else {
$firstname = escape_data($_POST['firstname']);
$username = escape_data($_POST['regis_username']);
$lastname = escape_data($_POST['lastname']);
$email = escape_data($_POST['inputEmail']);
$telephone = escape_data($_POST['phone_num']);
$password = escape_data($_POST['regis_pass']);
$address = escape_data($_POST['postal_address']);
$gender = escape_data($_POST['gender']);
$date = escape_data($_POST['DateField']);
//check if user already exist
$exist = "";
$query = $heidisql->prepare("SELECT user_id as 'exist' FROM users WHERE user_username='$username' OR email_address='$email' ");
$query->execute();
while($userRow = $query->fetch(PDO::FETCH_ASSOC)) {
$exist = $userRow['exist'];
}
if(strlen($exist) > 0){
echo 'Account already exist!';
exit();
} else {
$sql = "";
$stmt = $heidisql->prepare($sql);
$token = bin2hex(random_bytes(20));
$hash = password_hash($password, PASSWORD_BCRYPT);
$stmt->execute(array ( ... ));
my email here
if (mail($to, $subject, $message, $headers)) { // Sending email // email_to, subject, body,email_from
echo 'Thank you for your registration. Check your email, and click on the link to activate your account ';
exit();
} else {
echo'Server failed to sent message, please try again later.';
exit();
}
}
} // END of else statement
exit();
}
debug($errors);
}
WHere exactly should I put the captcha code below into my code... I already try to put it on top but I get an error. Undefined $responseKey or something like that.
$secretKey = "xxxx";
$responseKey = $_POST['g-recaptcha-response'];
$userIP = $_SERVER['REMOTE_ADDR'];
$url = "https://www.google.com/recaptcha/api/siteverify";
$response = file_get_contents($url."?secret=".$secretKey."&response=".$responseKey."&remoteIP=".$userIP);
$data_response = json_decode($response);
if(isset($data_response->success) AND $data_response==true){
} else {
}
The and div are properly place into my form. I just cant pinpoint where the code should be placed exactly.

Check if username exists PDO

How would I be able to check multiple factors combined instead of checking for each one? So basically I'm using PDO and I have to make sure that the usernames and emails are unique. So how would I do that? I've seen
if ( $sthandler->rowCount() > 0 ) {
// do something here
}
But is there a better way to do it. Also if there isn't can someone explain how I'd work with that.
EDIT
Here's my query code that inputs into the database
<?php
try {
$handler = new PDO('mysql:host=localhost;dbname=s','root', '*');
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e){
exit($e->getMessage());
}
$name = $_POST['name'];
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$password1 = $_POST['passwordconf'];
$ip = $_SERVER['REMOTE_ADDR'];
//Verifcation
if (empty($name) || empty($username) || empty($email) || empty($password) || empty($password1))
{
echo "Complete all fields";
}
// Password match
if ($password != $password1)
{
echo $passmatch = "Passwords don't match";
}
// Email validation
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
echo $emailvalid = "Enter a valid email";
}
// Password length
if (strlen($password) <= 6){
echo $passlength = "Choose a password longer then 6 character";
}
function userExists($db, $user)
{
$userQuery = "SELECT * FROM userinfo u WHERE u.user=:user;";
$stmt = $db->prepare($userQuery);
$stmt->execute(array(':user' => $user));
return !!$stmt->fetch(PDO::FETCH_ASSOC);
}
$user = 'userName';
$exists = userExists($db, $user);
if(exists)
{
// user exists already.
}
else
{
// user doesn't exist already, you can savely insert him.
}
if(empty($passmatch) && empty($emailvalid) && empty($passlength)) {
//Securly insert into database
$sql = 'INSERT INTO userinfo (name ,username, email, password, ip) VALUES (:name,:username,:email,:password,:ip)';
$query = $handler->prepare($sql);
$query->execute(array(
':name' => $name,
':username' => $username,
':email' => $email,
':password' => $password,
':ip' => $ip
));
}
?>
<?php
//Connections
try {
$handler = new PDO('mysql:host=localhost;dbname=s','root', '*');
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e){
exit($e->getMessage());
}
$name = $_POST['name'];
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$password1 = $_POST['passwordconf'];
$ip = $_SERVER['REMOTE_ADDR'];
//Verifcation
if (empty($name) || empty($username) || empty($email) || empty($password) || empty($password1)){
$error = "Complete all fields";
}
// Password match
if ($password != $password1){
$error = "Passwords don't match";
}
// Email validation
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
$error = "Enter a valid email";
}
// Password length
if (strlen($password) <= 6){
$error = "Choose a password longer then 6 character";
}
if(!isset($error)){
//no error
$sthandler = $handler->prepare("SELECT username FROM users WHERE username = :name");
$sthandler->bindParam(':name', $username);
$sthandler->execute();
if($sthandler->rowCount() > 0){
echo "exists! cannot insert";
} else {
//Securly insert into database
$sql = 'INSERT INTO userinfo (name ,username, email, password, ip) VALUES (:name,:username,:email,:password,:ip)';
$query = $handler->prepare($sql);
$query->execute(array(
':name' => $name,
':username' => $username,
':email' => $email,
':password' => $password,
':ip' => $ip
));
}
}else{
echo "error occured: ".$error;
exit();
}
Something like this should work:
function userExists($db, $user)
{
$userQuery = "SELECT * FROM userinfo u WHERE u.user=:user;";
$stmt = $db->prepare($userQuery);
$stmt->execute(array(':user' => $user));
return !!$stmt->fetch(PDO::FETCH_ASSOC);
}
$user = 'userName';
$exists = userExists($db, $user);
if(exists)
{
// user exists already.
}
else
{
// user doesn't exist already, you can savely insert him.
}
The code you show has no much sense to check if username and email are unique. You should set UNIQUE KEY on the database.

Categories