0

我正在为一个没有 mysqlnd 的网络写作。所以我需要快速更改我的所有代码以不使用它。我以为我在那里有这个功能,但它重复了结果。

我非常感谢有关修复的任何帮助。

function getDBResults($sql, $params=array()) { // param 1 sql, param2 array of bind parameters
    $con=mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_DATABASE);
    if (!is_array($params)) {
        $params = array($params);
    }

    $query = $con->stmt_init(); // $this->connection is the mysqli connection instance

    // Start stmt
    if($query->prepare($sql)) {

        if (count($params)>0) { // Skip of there are no paremeters
            // This will loop through params, and generate types. e.g. 'ss'
            $types = '';                        
            foreach($params as $param) {        
                if(is_int($param)) {
                    $types .= 'i';              //integer
                } elseif (is_float($param)) {
                    $types .= 'd';              //double
                } elseif (is_string($param)) {
                    $types .= 's';              //string
                } else {
                    $types .= 'b';              //blob and unknown
                }
            }
            array_unshift($params, $types);
            // Bind Params
            $bpArray = array($query,'bind_param');
            $bpArray = 'mysqli_stmt_bind_param';

            array_unshift($params, $query);

            $tmp = array();
            foreach($params as $key => $value) {
                $tmp[$key] = &$params[$key];
            };

            call_user_func_array($bpArray, $tmp); 
        }

        $query->execute(); 

        // Get metadata for field names
        $meta = $query->result_metadata();

        // initialise some empty arrays
        $fields = $results = array();

        // This is the tricky bit dynamically creating an array of variables to use
        // to bind the results
        while ($field = $meta->fetch_field()) { 
            $var = $field->name; 
            $$var = null; 
            $fields[$var] = &$$var; 
        }

        // Bind Results
        call_user_func_array(array($query,'bind_result'),$fields);

        // Fetch Results
        while (mysqli_stmt_fetch($query)) { 
            call_user_func_array(array($query,'bind_result'),$fields);
            $results[] = $fields; 
        }
        $query->close();
        // And now we have a beautiful
        // array of results, just like
        //fetch_assoc
        return $results;
    }
}
4

1 回答 1

1
function getDBResults($sql, $params=array()) {
    global $pdo; // you should NEVER connect in a function! But use already opened.
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    return $stmt->fetchAll();
}

看 - 三个简单的行。

是您需要的所有信息。请记住,每个应用程序只需连接一次并一直使用此连接。

于 2014-03-15T20:19:32.673 回答