简体   繁体   English

mysql_result进入更高级的mysqli函数

[英]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. 我正在将小型项目从MYSQL数据库升级到MYSQLi ,仅剩下3个函数需要更新。

This is my function in MYSQL : 这是我在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. 我知道应该公开我尝试过的代码,但是问题是我真的不知道如何将MYSQLi迁移到该特定函数中,而且我知道如果可以这么说,代码在所有方面都是错误的。

Well you can try this one to migrate: 好吧,您可以尝试以下一种迁移:
https://github.com/colshrapnel/safemysql/blob/master/safemysql.class.php 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. 请注意,这不是纯mysqli,而是基于它构建的自定义库。
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. 例如,使用字符串$username字符串占位符( ?s )。

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 :) 这很简单,我仍然可以坚持自己的代码而无需集成其他脚本:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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