Issue with Form and PDO - php

I plan to clean up the code, and make it more OOP friendly later, but for now I am struggling to get this to work. I have managed to get down for it to echo 'hi', but the execute doesn't seem to be putting anything into the database, and it is not giving me any errors. The code is
public function newAccount(array $data) {
$error = NULL;
//Check first name length, and make sure its over 2 characters
if (strlen($data['fname']) > 2) {
$fname = $data['fname'];
}
else {
$fname = FALSE;
$error .= "Please put in a valid First Name. <br />";
}
//Check if last name length is over 2 characters
if (strlen($data['lname']) > 2) {
$lname = $data['lname'];
}
else {
$lname = FALSE;
$error .= "Please enter a valid Last Name. <br />";
}
// Check username
if (strlen($data['user']) > 3) {
$user = $data['user'];
}
else {
$user = FALSE;
$error .= "Username must be longer than 3 characters.<br />";
}
// Mske sure password is atleast 6 characters, and retyped correctly
if (strlen($data['pass']) > 5) {
if ($data['pass'] == $data['repass']) {
$pass = $data['pass'];
}
else {
$pass = FALSE;
$error .= "Passwords do not match.<br />";
}
}
else {
$pass = FALSE;
$error .= "Password must be longer than 6 characters.";
}
//make sure email looks correct, strpos makes sure there is an '#'
if (strlen($data['email']) > 5 && strpos($data['email'], '#')) {
$email = $data['email'];
}
else {
$email = FALSE;
$error .= "Please enter a valid email. <br />";
}
// Check if user is suppose to be admin
if (isset($data['admin'])) {
$admin = '1';
}
else {
$admin = '0';
}
if ($fname && $lname && $user && $pass && $email) {
echo 'hi';
try {
$sth = $this->dbc->prepare("INSERT INTO users(user, password first_name, last_name, email, admin) VALUES(:user, MD5(:pass), :fname, :lname, :email, :admin)");
$sth->execute(array(":user" => $user,
":pass" => $pass,
":fname" => $fname,
":lname" => $lname,
":email" => $email,
":admin" => $admin)
);
}
catch (PDOException $e) {
echo $e->getMessage();
}
}
else {
echo "Error" . $error;
}
}
Thanks in advance!

In your insert query, you are missing a comma after password field.
It should be
$sth = $this->dbc->prepare("INSERT INTO
users(user, password, first_name, last_name, email, admin)
VALUES(:user, MD5(:pass), :fname, :lname, :email, :admin)");
Also, when testing is entered string is email address or not, use filter_var(). Like this:
if( filter_var($data['email'], FILTER_VALIDATE_EMAIL) {
//do this...

Related

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.

Check if user exists Registration

I am building a social app in Corona SDK with PHP being the back-end.
I am trying to sign up to the app but a block of code is getting skipped over.
if (!$errors) {
$stmt = $con->prepare("SELECT username, email FROM users WHERE username=? OR email=?");
$stmt->bind_param("ss", $_POST['username'], $_POST['email']);
$stmt->execute();
foreach ($stmt->get_result() as $row) {
foreach (['username', 'email'] as $field) {
if ($row[$field] == $_POST[$field]) {
echo "Sorry, that " . $field . " is already in use.";
die();
}
}
}
}
That code checks if the username or email that was entered is already in the DB. It works fine with my website but it doesn't work with the app. I commented out all of the other echo statements and verified that that specific block of code just doesn't run. Can someone help me ?
/*if ($_SERVER['REQUEST_METHOD'] != 'POST' || ! isset($_POST['Register'])) {
// Use full absolute URL header('Location: https://www.yoursite.com/index.php');
//header('Location: index.php');
echo "Not POST";
die();
} */
require 'config/connect.php';
$con = new mysqli(...$dbCredentials);
$username = $_POST['username'] ?? '';
$email = $_POST['email'] ?? '';
$pw = $_POST['pw'] ?? '';
$errors = [];
if (!trim($username)) {
echo 'Fill in username to sign up';
die();
}
if (!preg_match("/^[a-zA-Z0-9]{5,}$/", $username)) {
echo 'Invalid username, only letters and/or digits.';
die();
}
if (!trim($pw)) {
echo 'Fill in password to sign up';
die();
}
if (!trim($email)) {
echo 'Fill in email to sign up';
die();
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo 'Invalid email';
die();
}
if (!$errors) {
$stmt = $con->prepare("SELECT username, email FROM users WHERE username=? OR email=?");
$stmt->bind_param("ss", $_POST['username'], $_POST['email']);
$stmt->execute();
foreach ($stmt->get_result() as $row) {
foreach (['username', 'email'] as $field) {
if ($row[$field] == $_POST[$field]) {
echo "Sorry, that " . $field . " is already in use.";
die();
}
}
}
}
$ipAddress = $_SERVER['REMOTE_ADDR'];
if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
$ipAddress = array_pop(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']));
}
if (!$errors) {
$pw = password_hash($_POST['pw'], PASSWORD_BCRYPT, ['cost' => 14]);
$stmt = $con->prepare("INSERT INTO users (username, email, pw, ip_address)
VALUES (?, ?, ?, ?)");
$stmt->bind_param("ssss", $username, $email, $pw, $ipAddress);
$stmt->execute();
$_SESSION["user_id"] = $_POST['username'];
echo "success";
die();
} else {
echo 'something is wrong here.';
die();
}
$_SESSION['error'] = '<b><p style="color: #fff; font-size: 30px; top: 34%;right: 50%;position: absolute;">
' . $errors . '</p></b>';
//header('Location: index.php');
//exit();
You should the early returns concept. First check if there are errors, show error message and exit. If there are no errors then move ahead further to the desired case. This may help.
if ($errors) {
echo 'something is wrong here.';
die();
}
Too complicated! I would simplified that like:
SELECT COUNT(`username`) FROM `users` WHERE username=? OR email=?;
$stmt->bind_param("ss", $username, $email);
In PDO there is a function called fetchColumn() to get the count as int. Its either 0 or 1. There should be a similar function in mysqli. I think it's mysqli_fetch_field()
username, password and email can simplified as well:
if (empty(trim($username)) or !ctype_alnum($username))
{ die('Username is either empty or invalid! Only alphanumeric characters'); }
if (empty(trim($pw)))
{ die('Fill in password to sign up'); }
if (empty(trim($email)) or !filter_var($email, FILTER_VALIDATE_EMAIL))
{ die('Email is either empty or not a valid address!'); }
if (!$errors) { can't be false
$pw = password_hash($pw);
never store username in session always user id its way safer!
If this should not work try to place an var_dump($errors) before sql check.
If this should not work check database connection and bind params values

how to validate one variable either of two variables in php

i have two variables mobile and email now i want to validate both but i want the user to leave blank one of the fields if user does not have one for ex if a user does not want to register with his email then he can go to mobile number for registration and vice versa this is my validation code
<?php
$emailError = "";
$fullnameError = "";
$usernameError = "";
$passwordError = "";
$mobileerror = "";
$errors = 0;
if ((isset($_POST['submit']))) {
$email = strip_tags($_POST['email']);
$fullname = strip_tags($_POST['fullname']);
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$mobile = strip_tags($_POST['mobile']);
$fullname_valid = $email_valid = $mobile_valid = $username_valid = $password_valid = false;
if (!empty($fullname)) {
if (strlen($fullname) > 2 && strlen($fullname) <= 30) {
if (!preg_match('/[^a-zA-Z\s]/', $fullname)) {
$fullname_valid = true;
# code...
} else {
$fullnameError = "fullname can contain only alphabets <br>";
$errors++;
}
} else {
$fullnameError = "fullname must be 2 to 30 char long <br>";
$errors++;
}
} else {
$fullnameError = "fullname can not be blank <br>";
$errors++;
}
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$query2 = "SELECT email FROM users WHERE email = '$email'";
$fire2 = mysqli_query($con, $query2) or die("can not fire query" . mysqli_error($con));
if (mysqli_num_rows($fire2) > 0) {
$emailError = $email . "is already taken please try another one<br> ";
} else {
$email_valid = true;
}
# code...
} else {
$emailError = $email . "is an invalid email address <br> ";
$errors++;
}
# code...
if ($mobile) {
$query4 = "SELECT mobile FROM users WHERE mobile = '$mobile'";
$fire4 = mysqli_query($con, $query4) or die("can not fire query" . mysqli_error($con));
if (mysqli_num_rows($fire4) > 0) {
$mobileerror = "is already taken please try another one<br> ";
} else {
$mobile_valid = true;
}
}
if (!empty($username)) {
if (strlen($username) > 4 && strlen($username) <= 15) {
if (!preg_match('/[^a-zA-Z\d_.]/', $username)) {
$query = "SELECT username FROM users WHERE username = '$username'";
$fire = mysqli_query($con, $query) or die("can not fire query" . mysqli_error($con));
if (mysqli_num_rows($fire) > 0) {
$usernameError = '<p style="color:#cc0000;">username already taken</p>';
$errors++;
} else {
$username_valid = true;
}
} else {
$usernameError = "username can contain only alphabets <br>";
$errors++;
}
} else {
$usernameError = "username must be 4 to 15 char long <br>";
$errors++;
}
} else {
$usernameError = "username can not be blank <br>";
$errors++;
}
if (!empty($password)) {
if (strlen($password) >= 5 && strlen($password) <= 15) {
$password_valid = true;
$password = md5($password);
# code...
} else {
$passwordError = $password . "password must be between 5 to 15 character long<br>";
$errors++;
}
# code...
} else {
$passwordError = "password can not be blank <br>";
$errors++;
}
//if there's no errors insert into database
if ($errors <= 0) {
if ($fullname_valid && ($email_valid || $mobile_valid )&& $password_valid && $username_valid) {
$query = "INSERT INTO users(fullname,email,username,password,avatar_path) VALUES('$fullname','$email','$username','$password','avatar.jpg')";
$fire = mysqli_query($con, $query) or die("can not insert data into database" . mysqli_error($con));
if ($fire) {
header("Location: dashboard.php");
}
}
}
}
?>
now when i use email and leave blank mobile the code works fine but when i use email and leave blank mobile then error occurs how to solve this problem
Use one more flag
$isValid_email_mobile = FALSE;
When control flow enters into if (filter_var($email, FILTER_VALIDATE_EMAIL)) then on SUCCESS just set $isValid_email_mobile = TRUE; It will be same if control enters in condition if ($mobile) again on SUCCESS , set it as $isValid_email_mobile = TRUE;
When $isValid_email_mobile = FALSE; becomes TRUE then you know that of the field/variable has passed your requirement and its ready for DB INSERT
Then
In your last IF condition when you try to INSERT just change IF condition to the following
IF ($fullname_valid && $isValid_email_mobile && $password_valid && $username_valid)
One more thing whenever you are using Flag logic always set your flag to some default value before using it.
now when i use email and leave blank mobile the code works fine but when i use email and leave blank mobile then error occurs
you have:
if (!empty($fullname)) {}
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {}
if ($mobile) {}
if (!empty($username)) {}
if (!empty($password)) {}
To remove the error, try adding
if (!empty($mobile)) {
Also, I would suggest to wrap the statements a bit more. You only need one to fail in order to stop input. You could do something like this:
$mobileOrEmail = false;
if (!empty($fullname) && !empty($username) && !empty($password) {
//check fullname, username and password
if (!empty($mobile) {
//check mobile, if it passes
$mobileOrEmail = true;
}
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
//check email, if it passes
$mobileOrEmail = true;
}
if (!$mobileOrEmail) $errors++;
} else {
//missing input values
$errors++;
}
Personally, I would create a function for each input field.
function checkUsername($username){
//check username
return true;
}
function checkEmail($email) {
//check email
return true;
}
....
then you can run
if (checkUsername($username) && checkPassword($password)
&& checkFullname($fullname) && (checkEmail($email) || checkEmail($email)) {
//user input correct
} else {
//user input failed
}
Just to give it more structure

What is wrong with my Register function?

Problem & Explanation
Hello I have just coded a function that first does checking if account exists in database with that name, and then if email exists in database with that entered email.
If not, return true + insert data.
But in this case, nothing happens on submit, it just shows the form, but doesn't inserts the data..
What is wrong with it?
function createAccount($name, $password, $email)
{
global $pdo;
$check_in = $pdo->prepare("SELECT * FROM users WHERE user_name = :username LIMIT 1");
$check_in->execute( array(':username' => $name) );
if (!$check_in->rowCount())
{
$check_in = email_exists($email);
if ($check_in === false)
{
$insert_in = $pdo->prepare
("
INSERT INTO
users
(user_name, user_password, user_email)
VALUES
(:name, :password, :email)
");
$insert_in->execute( array
(
':name' => $name,
':password' => $password,
':email' => $email
));
return true;
}
else
{
return 'exists';
}
}
else
{
return 'user_in_use';
}
}
function email_exists($email)
{
global $pdo;
$check = $pdo->prepare("SELECT * FROM users WHERE user_email = :email LIMIT 1");
$check->execute( array(':email' => $email) );
if ($check->rowCount())
{
return true;
}
else
{
return false;
}
}
This is how I make up the register:
# Creating shortcuts
if (isset($_POST['username']) && isset($_POST['password']) && isset($_POST['email']))
{
$name = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
}
# Creating errors array
$errors = array();
if (isset($_POST['submit']))
{
$check_in = createAccount($name, $password, $email);
if ($check_in === true)
{
echo 'Created account sucessfully!';
}
else if ($check_in == 'already_in_use')
{
echo 'Could not create account because name already in use..';
}
else if($check_in == 'exists')
{
echo 'Email already in use..';
}
}
Question:
What is wrong with this code & how do I fix this? I have no errors at all.
It just won't insert any data to the Database.
Yes, the PDO connection & statements are right, because the login works perfectly.
Thanks a lot!
EDIT!
if ($check_in === true)
{
echo 'Created account sucessfully!';
}
else if ($check_in == 'already_in_use')
{
echo 'Could not create account because name already in use..';
}
else if($check_in == 'exists')
{
echo 'Email already in use..';
} else {
echo 'Error is there...';
}
It's echoing 'Error is there...' apon submit!
I just want to slap myself!.....
The problem was: The fields were set as INT, therefore we could not store anything but ints...

Categories