简体   繁体   中英

mysql_result into more advanceed mysqli function

I am upgrading my small project from MYSQL database into MYSQLi and I have only 3 functions left to update.

This is my function in MYSQL :

function id_from_username($username) {
    $username = sanitize ($username);
    return mysql_result(mysql_query("SELECT ´id´ FROM ´members´ WHERE ´username´ = '$username'"), 0, 'id');
}

I have this code which I tried to migrate into the function above but no use:

$result = "SELECT * FROM `settings`";
 if (!$row = $db_connect->query($result)) {
     die('Oops, something went wrong during loading data! Error x010');
 }

I know I am supposed to public the code I tried out, but the problem is I do not really know how to migrate the MYSQLi into just that specific function and I know that the code was wrong in all ways possible if so to say.

Well you can try this one to migrate:
https://github.com/colshrapnel/safemysql/blob/master/safemysql.class.php

First, connect somewhere earlier in the script:

include 'safemysql.class.php';
$opts = array(
    'user'    => 'user',
    'pass'    => 'pass',
    'db'      => 'db',
    'charset' => 'latin1',
);
$db = new SafeMySQL($opts);

then write your function this way

function id_from_username($username) 
{
    global $db;
    return $db->getOne("SELECT id FROM members WHERE username = ?s", $username);
}

note that this is not a pure mysqli but a custom library built upon it.
Most important difference is that every placeholder have to be marked with it's type, according to their role in the query. Eg for the string $username string placeholder ( ?s ) were used.

I found the right answer, the code should be following:

function id_from_username($username) {
    $username = sanitize($username);
    global $db_connect;

    $result = $db_connect->query("SELECT(id) FROM members WHERE username = '$username'");
    if (false === $result) {
        return false;
    }
    return ($result->num_rows === 1);
}

It's simple and I still can stick to my code without integrating other scripts :)

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