I'm quite new to PHP and MySQL and I try to learn how to change a code from PDO to MySQLi. Its about a remember me function with a securitytoken and identifier for a login system that I found in the web. I would like to learn and understand how I can change the code from PDO to MySQLi. I know in MySQLi there is a statement create and prepare, also I have to bind parameters and execute. But in this case, I don't know how to start anyway.
$pdo = new PDO('mysql:host=localhost;dbname=dbname', 'root', '');
if (!isset($_SESSION['id']) && isset($_COOKIE['identifier']) &&
isset($_COOKIE['securitytoken'])) {
$identifier = $_COOKIE['identifier'];
$securitytoken = $_COOKIE['securitytoken'];
$statement = $pdo->prepare("SELECT * FROM securitytokens WHERE identifier = ?");
$result = $statement->execute(array($identifier));
$securitytoken_row = $statement->fetch();
if (sha1($securitytoken) !== $securitytoken_row['securitytoken']) {
die('Maybe a stolen securitytoken.');
} else {
//Token was correct
//Set an new token
$neuer_securitytoken = random_string();
$insert = $pdo->prepare("UPDATE securitytokens SET securitytoken = :securitytoken WHERE identifier = :identifier");
$insert->execute(array('securitytoken' => sha1($neuer_securitytoken), 'identifier' => $identifier));
setcookie("identifier", $identifier, time() + (3600 * 24 * 365)); //1 Year valid
setcookie("securitytoken", $neuer_securitytoken, time() + (3600 * 24 * 365)); //1 Year valid
//Loggin the user
$_SESSION['id'] = $securitytoken_row['id'];
}
}
Don't do it! PDO is simpler and offers more functionality.
If you want to do it just to learn MySQLi then you should keep these things in mind:
This is how you open the connection properly:
There is no bind-in-execute in MySQLi. In fact there is no bind by value at all! You can only bind by reference and you have to specify the type of the value.
MySQLi has no named placeholders, so you need to use positional ones only.
The
fetch
method in MySQLi works totally differently and it returns boolean. To get the same outcome as PDO'sfetch()
you would need toget_result()
and then usefetch_array()
orfetch_assoc()