Needs to be $dsn = 'mysql:dbname=dev;host=127.0.0.1';
Don’t replace dbname
because that is how you connect to your database. It’s equivalent to procedural mysqli_*'s prepare($db, ..)
where $db
is the database you want to use.
Also, you should take note that square bracket arrays []
are available only from PHP 5.4 +. So don’t use square bracket arrays []
if you have PHP 5.3. You’ll get an error. Use array();
as an alternative if you have PHP 5.3 and below.
The reason why they are passing the $pdo
/db variable is because in PHP, you don’t really want to create a new database connection every time you do a query. It’s easier to re-use the connection then closing it and re-opening it. In a way, it’s kind of like how system admins are with up-time.
You don’t need to. You can still use OOP mysqli_*.
<?php
// Connect to MySQL
$host = '127.0.0.1';
$username = 'dev';
$password = 'dev.dev';
$db = 'dev';
$mysqli = new mysqli($host, $username, $password, $db);
if($mysqli->connect_errno) {
die('Do not display any errors here. You should NEVER display errors to the user.');
}
$sql = 'SELECT 1 FROM flags WHERE flagname = ? AND ? BETWEEN MIN(flagvalue) AND MAX(flagvalue) LIMIT 1';
$prepare = $mysqli->prepare($sql);
$prepare->bind_param('ss', $flagname, $flagname2);
$prepare->execute();
$prepare->store_result();
if($prepare->num_rows) {
$prepare->bind_result($first_flag);
while($prepare->fetch()) {
print($first_flag);
}
} else {
print('No record with that information');
}
Also take note, you should always be using num_rows
and rowCount()
as it helps prevent white pages (nothing is displayed, no errors, no warning, nothing) and prevents error warning. It is also helps better user experience.