So this is my second project with PDO and after checking with my first project I can not for the life of me figure out why this INSERT is not working and I am not getting an error message. This is the firs time I am using PDO inside of sublime 3. Don't think this has anything to do with it just figured Id add that.
Here is my connection which is giving me no problems but here just in case!
<?php
$connString = "mysql:host=localhost;dbname=rmldb";
$uname = "root";
$pwd = "DB_PASS";
try{
$pdo = new PDO($connString, $uname, $pwd);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
echo "Connection failed: " . $e->getMessage();
}?>
Here is my php with the query:
I checked to see if I was making it to the try/catch by adding an echo and I am getting all the way through to the end of the 'try' block but still nothing is being inserted and I cannot figure out why.
if($_SERVER["REQUEST_METHOD"] == "POST"){
$formdata['fname'] = trim($_POST['fname']);
$formdata['lname'] = trim($_POST['lname']);
$formdata['email'] = trim($_POST['email']);
$formdata['pwd'] = trim($_POST['pwd']);
$formdata['pwd2'] = trim($_POST['pwd2']);
$formdata['phone'] = trim($_POST['phone']);
$formdata['date'] = $_POST['dateCreated'];
//Checking for empty form values
if(empty($formdata['fname'])){
$err = 1;
$errfname = "First name is required";
}
if(empty($formdata['lname'])){
$err = 1;
$errlname = "Last name is required";
}
if(empty($formdata['email'])){
$err = 1;
$erremail = "Email is required";
}
if(empty($formdata['pwd'])){
$err = 1;
$errpwd = "Please enter a password";
}
if(empty($formdata['pwd2'])){
$err = 1;
$errpwd2 = "Please enter a password";
}
if(empty($formdata['phone'])){
$formdata['phone'] = "N/A";
}
//Checking for matching password values
if($formdata['pwd'] != $formdata['pwd2']){
$err = 1;
$errpwd = "Passwords do not match";
$errpwd2 = "Passwords do not match";
}
//Checking for existing emails
try{
$sql = "INSERT INTO users (fname, lname, email, pwd, phone, dateCreated, admin) VALUES (:fname, :lname, :email, :pwd, :phone, :dateCreated, :admin)";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(":fname", $formdata['fname']);
$stmt->bindValue(":lname", $formdata['lname']);
$stmt->bindValue(":email", $formdata['email']);
$stmt->bindValue(":pwd", $formdata['pwd']);
$stmt->bindValue(":phone", $formdata['phone']);
$stmt->bindValue(":dateCreated", $rightnow);
$stmt->bindValue(":admin", 0);
$stmt->execute();
$showform = 0;
echo "<p class='error'> Recorded!</p>";
}catch(PDOException $e){
$e->getMessage();
}
}
This may not be the best way to do it but this should get you what you want.
<?php
$formdata['fname'] = trim($_POST['fname']);
$formdata['lname'] = trim($_POST['lname']);
$formdata['email'] = trim($_POST['email']);
$formdata['pwd'] = trim($_POST['pwd']);
$formdata['pwd2'] = trim($_POST['pwd2']);
$formdata['phone'] = trim($_POST['phone']);
$formdata['date'] = $_POST['dateCreated'];
//Checking for empty form values
if (empty($formdata['fname'])) {
$err = 1;
$errfname = "First name is required";
} else if (empty($formdata['lname'])) {
$err = 1;
$errlname = "Last name is required";
} else if (empty($formdata['email'])) {
$err = 1;
$erremail = "Email is required";
} else if (empty($formdata['pwd'])) {
$err = 1;
$errpwd = "Please enter a password";
} else if (empty($formdata['pwd2'])) {
$err = 1;
$errpwd2 = "Please enter a password";
} else if (empty($formdata['phone'])) {
$formdata['phone'] = "N/A";
} else if ($formdata['pwd'] != $formdata['pwd2']) {
//Checking for matching password values
$err = 1;
$errpwd = "Passwords do not match";
$errpwd2 = "Passwords do not match";
} else {
$sql = "INSERT INTO users (fname, lname, email, pwd, phone, dateCreated, admin) VALUES (:fname, :lname, :email, :pwd, :phone, :dateCreated, :admin)";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(":fname", $formdata['fname']);
$stmt->bindValue(":lname", $formdata['lname']);
$stmt->bindValue(":email", $formdata['email']);
$stmt->bindValue(":pwd", $formdata['pwd']);
$stmt->bindValue(":phone", $formdata['phone']);
$stmt->bindValue(":dateCreated", $rightnow);
$stmt->bindValue(":admin", 0);
if ($stmt->execute()) {
$showform = 0;
echo "<p class='error'> Recorded!</p>";
} else {
echo "<p class='error'> Sorry, there was an error!</p>";
}
}
?>
Related
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?
I need a second pair of eyes to have a look at my code and tell me what I am missing, as I think I have identified the portion of code that doesn't work, I just don't know why.
Basically I am trying to register a user to a database, in a way that it prevents SQL injection. For the life of me however, it doesn't work. When I deconstruct the code and make it less secure, it works. Anyway, code is here:
//require_once 'sendEmails.php';
session_start();
$username = "";
$email = "";
$user_dob = "";
$user_fname = "";
$user_lname = "";
$user_telephone = "";
$errors = [];
$servername = '';
$login = '';
$password = '';
$DBname = '';
$rows = 0;
$query = "";
$conn = new mysqli($servername, $login, $password, $DBname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($conn) {
echo "Connected successfully";
}
// SIGN UP USER
if (isset($_POST['signup-btn'])) {
if (empty($_POST['username'])) {
$errors['username'] = 'Username required';
}
if (empty($_POST['email'])) {
$errors['email'] = 'Email required';
}
if (empty($_POST['password'])) {
$errors['password'] = 'Password required';
}
if (isset($_POST['password']) && $_POST['password'] !== $_POST['passwordConf']) {
$errors['passwordConf'] = 'The two passwords do not match';
}
if (empty($_POST['dob'])) {
$errors['dob'] = 'Date of birth required';
}
if (empty($_POST['fname'])) {
$errors['fname'] = 'First name required';
}
if (empty($_POST['lname'])) {
$errors['lname'] = 'Last name required';
}
if (empty($_POST['telephone'])) {
$errors['telephone'] = 'Telephone number required';
} //--checks input in browser
//I think it works untill this point...
$token = bin2hex(random_bytes(50)); // generate unique token
$username = $_POST['username'];
$password = password_hash($_POST['password'], PASSWORD_BCRYPT); //encrypt password
$user_dob = $_POST['dob'];
$user_fname = $_POST['fname'];
$user_lname = $_POST['lname'];
$user_telephone = $_POST['telephone'];
$email = $_POST['email'];
//Above assigns inputted values into variables declared at the start
//echo $token, $email; //-- this works
//nl2br() ; // -- line break in php
// Check if email already exists
//$result = $mysqli->query("SELECT * FROM User_tbl WHERE email='$email' LIMIT 1");
$sql = "SELECT * FROM User_tbl WHERE email='$email' LIMIT 1";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > $rows) {
$errors[] = $email;
echo "Email already exists";
}
$errorsInt = count($errors);
echo mysqli_num_rows($result);
echo count($errors);
echo $errorsInt;
if ($errorsInt === $rows) {
$query = "INSERT INTO User_tbl SET token=?, username=?, password=?, user_dob=?, user_fname=?, user_lname=?, user_telephone=?, email=?";
// "INSERT INTO User_tbl VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
echo $query;
//---------------------------------------------------------------------------
$stmt = $conn->prepare($query); //first
$stmt->bind_param('sssissis', $token, $username, $password, $user_dob, $user_fname, $user_lname, $user_telephone, $email);
$result = $stmt->execute();
echo $result;
if ($result) {
$user_id = $stmt->insert_id;
$stmt->close();
$_SESSION['id'] = $user_id;
$_SESSION['username'] = $username;
$_SESSION['email'] = $email;
$_SESSION['verified'] = false;
$_SESSION['message'] = 'You are logged in!';
$_SESSION['type'] = 'alert-success';
header('location: index.php');
} else {
$_SESSION['error_msg'] = "Database error: Could not register user";
}
}
}
The problem I believe starts here:
$stmt = $conn->prepare($query); //first
$stmt->bind_param('sssissis', $token, $username, $password, $user_dob, $user_fname, $user_lname, $user_telephone, $email);
$result = $stmt->execute();
We are using below code for "sign up". we have only password field , we want to add confirm password field.
signup.php
if(isset($_POST['btn-signup']))
{
$uname = trim($_POST['txtuname']);
$email = trim($_POST['txtemail']);
$upass = trim($_POST['txtpass']);
$code = md5(uniqid(rand()));
$stmt = $reg_user->runQuery("SELECT * FROM tbl_users WHERE userEmail=:email_id");
$stmt->execute(array(":email_id"=>$email));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0)
{
$msg = "
email allready exists
";
}
else
{
if($reg_user->register($uname,$email,$upass,$code))
{
$id = $reg_user->lasdID();
$key = base64_encode($id);
$id = $key;
$message = "
some message";
$subject = "Confirm Registration";
$reg_user->send_mail($email,$message,$subject);
$msg = "
some message
";
}
else
{
echo "sorry , Query could no execute...";
}
}
}
class.usr.php
public function register($uname,$email,$upass,$code)
{
try
{
$password = md5($upass);
$stmt = $this->conn->prepare("INSERT INTO tbl_users(userName,userEmail,userPass,tokenCode)
VALUES(:user_name, :user_mail, :user_pass, :active_code)");
$stmt->bindparam(":user_name",$uname);
$stmt->bindparam(":user_mail",$email);
$stmt->bindparam(":user_pass",$password);
$stmt->bindparam(":active_code",$code);
$stmt->execute();
return $stmt;
}
catch(PDOException $ex)
{
echo $ex->getMessage();
}
}
I tried adding below code, but it did't worked for me.
$cpass = trim($_POST['txtpass']);
/* Afer if statement */
elseif($pass != $cpass){
$msg = "passwords doesn't match";
}
also tried in class.usr.php file, but no luck.....
First of all you have not mentioned confirm password field.
Lets assume your confirm password field is "txtConfirmPass"
Before redirect to register function need to check password and confirm password like
$upass = trim($_POST['txtpass']);
$uConfirmPass = trim($_POST['txtConfirmPass']);
if($upass != $uConfirmPass){
// Password not match your code here
}else{
if($reg_user->register($uname,$email,$upass,$code)){
$id = $reg_user->lasdID();
$key = base64_encode($id);
$id = $key;
$message = "some message";
$subject = "Confirm Registration";
$reg_user->send_mail($email,$message,$subject);
$msg = "some message";
}
else
{
echo "sorry , Query could no execute...";
}
}
Hopefully it help you out.
Following is the PHP code
Database file working fine.
if(isset($_POST['submit']))
{
$error = array();
if(empty($_POST["fname"]))
{
$error[] = "Please Enter a name";
}
else
{
$fname = $_POST["fname"];
}
if(empty($_POST["lname"]))
{
$error[] = "Please Enter last name";
}
else
{
$lname = $_POST["lname"];
}
if(empty($_POST["email"]))
{
$error = "Enter email Id";
}
else
{
if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA-Z0- 9\._-]+)+$/", $_POST["email"]))
{
$email = $_POST["email"];
}
else
{
$error = "Enter a vaild Email Id";
}
}
if(empty($_POST["password"]))
{
$error = "Enter a password";
}
else
{
$password = $_POST["password"];
}
if(!empty($error))
{
$sql = "SELECT * FROM form (id, 'FirstName', 'LastName', 'Email', 'Password') VALUES('', '$fname', '$lname', '$email', '$password')";
$result = mysql_query($sql);
echo "Successfully Register";
}
else
{
foreach($error as $key => $values)
{
echo ' <li>' . $values . '</li>';
}
echo '</ol>';
echo "Error";
}
}
?>
The above code is not displying any error messages... if i submit the form only blank page ll appear... I validate my form using above code but it is just a basic method I used and by using for each I'm displaying errors...
the following test is wrong :
if(!empty($error))
should be :
if(empty($error))
And your SQL is wrong too... should be :
$sql = "Insert into form (FirstName, LastName, Email, Password) VALUES('$fname', '$lname', '$email', '$password')";
supposing your id field is auto-incremented
You forget to push the errors to array. You have
$error = "Enter a password"; //$error is no more an array. It is a string
And must be in several places:
$error[] = "Enter a password";
Also, I recommend you using nested if statements:
if (!empty($_POST['submit'])){
$errors = array() ;
if (!isset($_POST['email'])
$errors['email'] = "No email" ;
//And so on.
//Then check for errors
if (!empty($errors)){
//proceed submission
}
}
Try This code, it will works fine for you.
<?php
if(isset($_POST['submit']))
{
$error = array();
if(empty($_POST["fname"]))
{
$error[] = "Please Enter a name";
}
else
{
$fname = $_POST["fname"];
}
if(empty($_POST["lname"]))
{
$error[] = "Please Enter last name";
}
else
{
$lname = $_POST["lname"];
}
if(empty($_POST["email"]))
{
$error[] = "Enter email Id";
}
else
{
if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA-Z0- 9\._-]+)+$/", $_POST["email"]))
{
$email = $_POST["email"];
}
else
{
$error[] = "Enter a vaild Email Id";
}
}
if(empty($_POST["password"]))
{
$error[] = "Enter a password";
}
else
{
$password = $_POST["password"];
}
if(count($error)<=0)
{
$sql = "SELECT * FROM form (id, 'FirstName', 'LastName', 'Email', 'Password') VALUES('', '$fname', '$lname', '$email', '$password')";
$result = mysql_query($sql);
echo "Successfully Register";
}
else
{
foreach($error as $key => $values)
{
echo ' <li>' . $values . '</li>';
}
echo '</ol>';
echo "Error";
}
}
?>
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...