简体   繁体   中英

how to check the result of the mysql query in php

I have a html form for the user to login to the website but i want to check if the following query retun true or false, I am using the PDO so I cant use the method mysql_num_rows();

<?php


$view = new stdClass();
$view->login = 'Homepage';
if(isset($_POST['firstName']) && isset($_POST['password']) )
{
    $_firstName = $_POST['firstName'];
    $password= $_POST['password']; 
    $user = new UserPassword(); $user->getLogin($_firstName, $passWord);

}
require_once('Views/login.phtml');


  public function getLogin($userName,$passWord) {    

 $sqlQuerys = "SELECT `id`, `username`, `password`, `firstname`, `surename` FROM `sta177users` WHERE username = ' $userName' AND password = '$password'";
 echo $sqlQuerys;
 $statement = $this->_dbHandle->prepare($sqlQuerys);  
 $statement->execute();  
 }
}

You are not actually executing any query. You are setting a variable, but not executing the code.

Also, by building SQL statements with outside variables, you are leaving yourself open to SQL injection attacks. Also, any input data with single quotes in it, like a name of "O'Malley", will blow up your SQL query. Please learn about using parametrized queries, preferably with the PDO module, to protect your web app. My site http://bobby-tables.com/php has examples to get you started, and this question has many examples in detail.

You execute the query and you fetch a row. If the result of that fetch is not empty, you have a valid user.

Very important: You need to salt and hash your passwords and use prepared statements to avoid sql injection.

try this solution

$query="SELECT `id`, `username`, `password`, `firstname`, `surename` FROM `sta177users` WHERE username = ' $_firstName' AND password = '$password'";
$query->execute();
$rows = $query->fetchColumn();

if($rows == 1){
return true;
}else{
return false;
}

You wanna do something like this:

function emptyQuery($db) // assume $db is your PDO object
{
    // your prepared sql statement with PDO::prepare()
    $sql = $db->prepare("SELECT `id`, 
        `username`, 
        `password`, 
        `firstname`, 
        `surename` 
    FROM 
        `sta177users` 
    WHERE 
        username = ' $_firstName' 
        AND password = '$password'
        ");
    // execute it with PDO::execute()
    $sql->execute();
    // return all the rows with PDO::fetchAll(), and then see if the array is empty().
    return empty($sql->fetchAll());
}
?>

This should implement your specification. You can use count() for a count, etc.

Of course, do not forsake the documentation: http://us2.php.net/pdo

Hope that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM