简体   繁体   中英

Trouble converting PDO query to MySQLi

I have a query that is working fine in PDO but I am needing to convert the query to MySQLi to be compatible with an older server.

Here is the PDO query:

$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "SELECT * FROM users WHERE username=:username";
$st = $conn->prepare( $sql );
$st->bindValue( ":username", $username, PDO::PARAM_STR );
$st->execute();

while ( $row = $st->fetch() ) {
  $db_username = $row['username'];
  $db_password = $row['password'];
}

Here is what I have to MySQLi, but it doesn't seem to be working:

$mysqli = new mysqli( 'localhost', DB_USERNAME, DB_PASSWORD, DB_NAME );
$username = mysqli_real_escape_string($mysqli, $username);
$query = "SELECT * FROM users WHERE username=$username";
if ($result = $mysqli->query($query)) {
while ($obj = $result->fetch_object()) {
  $db_username = $obj->username;
  $db_password = $obj->password;
}
mysqli_free_result($result);
}

Any help would be very much appreciated :)

Try using the mysqli prepared statement system

$mysqli = new mysqli( 'localhost', DB_USERNAME, DB_PASSWORD, DB_NAME );

$query = "SELECT username, password FROM users WHERE username=?";
$prep = $mysqli->prepare($query);
$prep->bind_param('s', $username);
$prep->execute();
$result = $prep->get_result(); // Make sure you have mysqlnd installed
if($result) {
    while ($obj = $result->fetch_object()) {
         $db_username = $obj->username;
         $db_password = $obj->password;
    }
mysqli_free_result($result);
}

If you don't have mysqlnd installed then the less intuitive way involves bind_param

$prep->execute();
$prep->bind_result($db_username, $db_password);
$prep->fetch();

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