0

I'm new to PHP and keep running in to errors when trying to convert mysqli calls into PDO prepared statements. The database connection has been set up as PDO. It's literally changing around 3-4 but I cannot do this.

PHP Code:

//error_reporting(E_ALL);
//ini_set('display_errors', TRUE);

require 'vdb_includes/db.php';
require 'functions.php';

//Declaring variables as whitespace so nothing will be displayed below the form until submission.
$fe_firstName = " ";
$fe_lastName = " ";
$fe_email = " ";
$fe_emailconf = " ";
$fe_username = " ";
$fe_pw = " ";
$fe_pwconf = " ";
$fe_terms = " ";
$fe_usernameInvalid = " ";
$fe_emailInvalid = " ";
//Declaring verification variables to ensure duplicate users aren't created.
$verifyUsername = $_POST['username'];
$verifyEmail = $_POST['email'];

//Setting up array, if zero errors occur the array will stay empty.
$errors = array();


//The URL of the signup page.
//The full URL of the page the form was submitted from.
$current = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$referrer = $_SERVER['HTTP_REFERER'];

//Ensure form comes from VAL website.
if ( $referrer == $current ) {

if($_SERVER['REQUEST_METHOD'] == 'POST'){
 /**
  * Validate forms
    * Match regex
    * Ensure pass & email confirmations match
    */
    if(0 === preg_match("/^[a-z\-]{2,20}$/i", $_POST['firstName'])){
        $errors['e_firstName'] = "Your first name cannot be empty.";
        $fe_firstName = "Your first name cannot be empty.";
    }
    if(0 === preg_match("/^[a-z\-]{2,20}$/i", $_POST['lastName'])){
        $errors['e_lastName'] = "Your last name cannot be empty.";
        $fe_lastName = "Your last name cannot be empty.";
    }
    if(0 === preg_match("/^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/", $_POST['email'])){
        $errors['e_email'] = "Please enter a valid E-Mail address.";
        $fe_email = "Please enter a valid E-Mail address.";
    }
    if(0 !== strcmp($_POST['email'], $_POST['emailconf'])){
        $errors['e_emailconf'] = "Please ensure your E-Mail addresses match.";
        $fe_emailconf = "Please ensure your E-Mail addresses match.";
    }
    if(0 === preg_match("/^[a-z\d_]{3,20}$/i", $_POST['username'])){
        $errors['e_username'] = "Please enter a valid username.";
        $fe_username = "Please enter a valid username.";
    }
    if(0 === preg_match("/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,56}$/", $_POST['pw'])){
        $errors['e_pw'] = "Please follow the password instructions. You must have at least one number, one lower-case, and one upper-case letter.";
        $fe_pw = "Please follow the password instructions. You must have at least one number, one lower-case, and one upper-case letter.";
    }
    if(0 !== strcmp($_POST['pw'], $_POST['pwconf'])){
        $errors['e_pwconf'] = "Please ensure your passwords match.";
        $fe_pwconf = "Please ensure your passwords match.";
    }
    if(!isset($_POST['terms'])){
        $errors['e_terms'] = "You must accept the Terms and Conditions.";
        $fe_terms = "You must accept the Terms and Conditions.";
    }
 /**
    * Check if username and email address already exist.
    * If so, add error to validity array.
    */
$usernameCheck = mysqli_query($con, "SELECT * FROM users WHERE username='".$verifyUsername."'");
if($usernameCheck->num_rows){
    $errors['e_usernameInvalid'] = "Username already exists.";
    $fe_usernameInvalid = "Username already exists.";
}
$emailCheck = mysqli_query($con, "SELECT * FROM users WHERE email='".$verifyEmail."'");
if($emailCheck->num_rows){
    $errors['e_emailInvalid'] = "Email already exists.";
    $fe_emailInvalid = "Email already exists.";
}

    //If no validation errors
    if(0 === count($errors)){
        //HASH & ready password
        //
        // Instantiate new instance of class
        $hash_password = new Hash_Password();
        // Hash the password
        $hash = $hash_password->hash($password);
        $send_pw = $hash;
        //Autoset non-user-input values to 0
    $send_wins = 0;
    $send_losses = 0;
    $send_played = 0;
    $send_earnings = 0;
        //Obtain time of form submission = Time registered.
        $datum = new DateTime();
        $send_regDate = $datum->format('Y-m-d H:i:s');
        $send_lastLogin = $send_regDate;
        $send_rolePermissions = 0;

        //Insert query time.
    $sql = "
    INSERT INTO users (first_name, last_name, username, password, email, last_login, date_joined, wins, losses, played, earnings, permissions) VALUES
    (:firstName,:lastName,:username,:pw,:email,'{$send_lastLogin}','{$send_regDate}','{$send_wins}','{$send_losses}','{$send_played}','{$send_earnings}','{$send_rolePermissions}')
    ";
        $stmt = $con->prepare($sql);
    /***
        * Sanitize code
        * Clean dangerous chars for DB
        */
        $stmt->bindParam(':firstName, $_POST[firstName]');
        $stmt->bindParam(':lastName, $_POST[lastName]');
        $stmt->bindParam(':email, $_POST[email]');
        $stmt->bindParam(':username, $_POST[username]');
        $stmt->bindParam(':pw, $send_pw');

        //Redirecting based on the connection result.
    if(!$stmt->execute() ){
            if (!headers_sent()) {
                exit(header("Location: registration_fail.php"));
            } else{
                ?>
            <script> location.replace("registration_fail.php"); </script>
                <?php
            }
    } else{
            if (!headers_sent()) {
                exit(header("Location: registration_success.php"));
            } else{
                ?>
            <script> location.replace("registration_success.php"); </script>
                <?php
            }
            mysqli_close($con);
    }

    }

}
}

DP connection:

try{
    $con = new PDO("mysql:host=$server;dbname=$database;", $db_username, $db_password);
} catch(PDOException $e){
    die("Connection failed: " . $e->getMessage());
}

I'm fully aware the username and email check at the bottom of the validation need converting also, however ever with these removed from the code, the same error occurs.

The error is with the statement's execution. It redirects to the fail page, but I'm not sure what causes the execution fail?

Lewis
  • 29
  • 5
  • I've posted the coding issue before and no one helped. So I'd rather just pay to have it solved – Lewis Nov 25 '16 at 23:50
  • Code has been added – Lewis Nov 25 '16 at 23:54
  • Include the error(s). Where is the PDO connection set up, and what is it called? – chris85 Nov 25 '16 at 23:54
  • In db.php, it's being required – Lewis Nov 25 '16 at 23:58
  • Please show your connection set up, without credentials. It appears you are mixing PDO and mysqli. – chris85 Nov 25 '16 at 23:59
  • I'm aware of that, the connection is via PDO and works fine. However as stated in the question, when mysqli statements are removed, the PDO part still does not work. – Lewis Nov 26 '16 at 00:02
  • Please stop asking for off site help. If you want off site help you are off topic. Questions and answers should be here. – chris85 Nov 26 '16 at 00:02
  • Show that code, where just PDO is set up and failing. `$stmt->bindParam(` will not work because `$con` is a mysqli connection. Show the connection as well. – chris85 Nov 26 '16 at 00:03
  • Added the db con. As for where it's failing, I'm not sure. All I know is that removing the $emailCheck and $usernameCheck does nothing – Lewis Nov 26 '16 at 00:12
  • Your email validation regular expression is junk and will cause problems for people trying to use your site. gTLD names can be way longer than four characters. Keep your email verification *very* lax. If it has an `@` in it then it *might* be an email address. From there the only way to know for sure is to attempt delivery. `x@google` is a valid email address, as is `b@co`. The world is an ugly place as far as domains go and it's only going to get uglier. Have a look at the [list of top-level domains today](http://data.iana.org/TLD/tlds-alpha-by-domain.txt). – tadman Nov 26 '16 at 00:17
  • This is why I'd rather pay and get the issue sorted, no one can help as the error will take too long to find. Hence why I'd rather just pay to send someone the sqli code, and have them prepare it. – Lewis Nov 26 '16 at 00:32
  • The error is pretty straight forward. You are using a PDO connection as a mysqli connection (or vise versa). If you want to pay to have that told to you my hourly rate is 125, or negotiable on a project basis. – chris85 Nov 26 '16 at 05:51
  • I wouldn't have wanted it told to me, but done for me. Either way I've sorted it now and was a 5 minute fix as I'd assumed. The only problem was the fact I was adding non-bound variables to the prepare statement. Definitely not worth 125, sorry. Thanks for your help – Lewis Nov 26 '16 at 07:51
  • 1
    @chris85 125? I guess my clients are right when they tell me I don't charge enough *lol* – Funk Forty Niner Nov 26 '16 at 13:33
  • @Fred-ii- It's my rabbit hole rate. – chris85 Nov 26 '16 at 16:28
  • Ohhhh, I like that!! @chris85 Actually, mine's double the rate when I have to fix someone else's mess, sometimes even triple depending on how deep a hole I'd need to safely make my way out from. – Funk Forty Niner Nov 26 '16 at 16:34

1 Answers1

-2

I'd rather use mysqli to make prepared statements: So the code should be the following:

$link=//the statement you want prepared
$host=//whatever host;
$user=//user;
$pass=//pass;
$db=//your db;
$connect = new mysqli($host, $user, $pass, $db);
$prepared=$connect->prepare("SELECT column_name FROM table_name WHERE column_name=?");
$prepared->bind_param("s", $link); // "s" is for string
$prepared->execute();
$prepared->bind_result($result); // get results
$prepared->fetch(); // fetch them
$prepared->close();
$connect->close(); //close connection;
blackbear2014
  • 43
  • 1
  • 1
  • 5