Skip to main content

Converting MySQL to PDO



I've been advised a couple of times on here to start changing my code to PDO and I've finally got round to doing it. My problem is that I'm having incredible difficulty with converting my existing login script. For the last few lines of the code below (after the line $result = $query->fetchAll(); ) I haven't been able to find any resources online that could help me re-write it:







$username = $_POST['username'];

$password = $_POST['password'];



$db=getConnection();



$username = mysql_real_escape_string($username);



$query = $db->prepare( "SELECT password, salt, 'employer' as user_type

FROM JB_Employer

WHERE Username = '$username'



UNION

SELECT password, salt, 'jobseeker' as user_type

FROM JB_Jobseeker

WHERE User_Name = '$username'");



$result = $query->fetchAll();



$qData = mysql_fetch_array($result, MYSQL_ASSOC);

$hash = hash('sha256', $qData['salt'] . hash('sha256', $password) );



if ($result -> rowcount() <1 ;) { print “Fail, No such user”;}



if ($hash != $qData['password']) { header('Location: register.php?loginStatus=fail'); exit;}



else {$_SESSION['user'] = $username;

$_SESSION['permission'] = $qData['user_type'];}







Can anyone advise how I could go about acheiving this?


Comments

  1. You should consider renaming your variables to make more sense. In particular, $db->prepare() returns a statement, not a query. You pass it a query, and it prepares that query and returns a statement. It will save you headaches down the road if you follow this naming convention.

    That said, you should change this code:

    $result = $query->fetchAll();

    $qData = mysql_fetch_array($result, MYSQL_ASSOC);


    Into this:

    $qData = $query->fetch(\PDO::FETCH_ASSOC);


    And the rest should fall into line. PDOStatement::fetch(\PDO::FETCH_ASSOC) returns an associative array, just like mysql_fetch_array(..., MYSQL_ASSOC) or mysql_fetch_assoc().

    Edit: Also, you will need to change $result->rowCount() to $query->rowCount().

    ReplyDelete
  2. Take a look at this and please concider your code again especially regarding the XSS vulnerability! Also, for a good developers sake, refactor/rewrite your database. This is ALL but the way to go.

    Also, code is untested.

    <?php

    $db = getConnection(); //assuming you are returning a PDO object here!

    $username = getUsername(); //assuming you are NOT escaping the username!
    $password = getPassword(); //assuming your hashed password here!

    $query = "SELECT password, salt, 'emplyer' as user_type
    FROM JB_Employer
    WHERE Username = :username

    UNION

    SELECT password, salt, 'jobseeker' as user_type
    FROM JB_Jobseeker
    WHERE User_Name = :username";

    //$statement == PDOStatement
    $statement = $db->prepare($query);

    //bind the $username param to :username, this is the real power of PDO,
    //no more SQL Injections. Don't use mysql_real_escape-esque things!
    //they are not nececary with PDO
    $statement->bindParam(":username", $username);

    //execute the statement
    if($statement->execute()){
    $result = $statement->fetchAll();

    $rowCount = count($result);

    if($rowCount < 1){
    // redirect?
    die("No Such user");
    }else{
    // more than one user can be possible, this is not the correct way, but it appears to be your way so let's continue
    $firstRow = $result[0];

    if( isPasswordEqual($firstRow['salt'], $password) ){
    $_SESSION['user'] = $username; //security risk here. Vulnerable for XXS
    $_SESSION['permission'] = $firstRow['user_type'];
    }else{
    //Don't tell them this! It will give them knowledge of which accounts do exist.
    //Just say some general message like "login failed"
    die("wrong information");
    }
    }
    }

    ReplyDelete

Post a Comment

Popular posts from this blog

Why is this Javascript much *slower* than its jQuery equivalent?

I have a HTML list of about 500 items and a "filter" box above it. I started by using jQuery to filter the list when I typed a letter (timing code added later): $('#filter').keyup( function() { var jqStart = (new Date).getTime(); var search = $(this).val().toLowerCase(); var $list = $('ul.ablist > li'); $list.each( function() { if ( $(this).text().toLowerCase().indexOf(search) === -1 ) $(this).hide(); else $(this).show(); } ); console.log('Time: ' + ((new Date).getTime() - jqStart)); } ); However, there was a couple of seconds delay after typing each letter (particularly the first letter). So I thought it may be slightly quicker if I used plain Javascript (I read recently that jQuery's each function is particularly slow). Here's my JS equivalent: document.getElementById('filter').addEventListener( 'keyup', function () { var jsStart = (new Date).getTime()...

Is it possible to have IF statement in an Echo statement in PHP

Thanks in advance. I did look at the other questions/answers that were similar and didn't find exactly what I was looking for. I'm trying to do this, am I on the right path? echo " <div id='tabs-".$match."'> <textarea id='".$match."' name='".$match."'>". if ($COLUMN_NAME === $match) { echo $FIELD_WITH_COLUMN_NAME; } else { } ."</textarea> <script type='text/javascript'> CKEDITOR.replace( '".$match."' ); </script> </div>"; I am getting the following error message in the browser: Parse error: syntax error, unexpected T_IF Please let me know if this is the right way to go about nesting an IF statement inside an echo. Thank you.