Search code examples
phpmysqlpdomodx

ModX and PDO: querying with PHP variables


I am new to PDO and have the follow code which recieves 2 PHP vars from a form and uses them in a query:

$loginemail = $_REQUEST['loginemail'] ;
$loginpassword = $_REQUEST['loginpassword'] ;

$logincheck = "SELECT * FROM `ft_gameusers` WHERE `email` = '$loginemail' AND `password` = '$loginpassword'";

$query = $modx->query($logincheck);

if ($query) {
    while ($row = $query->fetch(PDO::FETCH_ASSOC)) {

 echo $row['email'];

    }
}

The thing is if I hard code the email and password variables into the MySQL query it works fine - its just doesnt seem to like them as PHP variables.

Does anyone know what Im doing wrong? (PS: this is a snippet within ModX Revo)

EDIT: form tag:

<form id="loginform" action="mysite.com/formprocess" method="post">

Email:
<input type="text" id="loginemail" name="loginemail">
Password:
<input type="password" id="loginpassword" name="loginpassword">
<button type="submit">Login</button>
</form>

Solution

  • This is how you can bind your parameters using PDO/xPDO:

    $loginemail = $_REQUEST['loginemail'] ;
    $loginpassword = $_REQUEST['loginpassword'] ;
    
    $logincheck = "SELECT * FROM `ft_gameusers` WHERE `email` = :loginemail AND `password` = :loginpassword";
    
    $credentials = array(
        ':loginemail' => $loginemail,
        ':loginpassword' => $loginpassword,
    );
    
    $query = new xPDOCriteria($modx,$logincheck,$credentials);
    if ($query->stmt && $query->stmt->execute()) {
        while ($row = $query->stmt->fetch(PDO::FETCH_ASSOC)) {
            echo $row['email'];
        }
    }
    

    http://php.net/manual/en/pdostatement.bindparam.php