PHP.mk документација

mysqli_stmt::fetch

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

mysqli-stmt.fetch.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека mysqli-stmt.fetch.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
mysqli_stmt::fetch

Референца за `mysqli-stmt.fetch.php` со подобрена типографија и навигација.

mysqli-stmt.fetch.php

mysqli_stmt::fetch

mysqli_stmt_fetch

класата mysqli_driver

mysqli_stmt::fetch -- mysqli_stmt_fetchПрезема резултати од подготвениот исказ во поврзаните променливи

= NULL

Напиши целосна ознака на елемент

public mysqli_stmt::fetch(): ?bool

Процедурален стил

mysqli_stmt_fetch(mysqli_stmt $statement): ?bool

Fetch the result from a prepared statement into the variables bound by mysqli_stmt_bind_result().

Забелешка:

Преземете го резултатот од подготвена изјава во променливите врзани од mysqli_stmt_fetch().

Забелешка:

Имајте предвид дека сите колони мора да бидат врзани од апликацијата пред да се повика mysqli_stmt_store_result() Податоците се пренесуваат без баферирање без повикување

Параметри

statement

објектот како свој прв аргумент. mysqli_stmt Само процедурален стил: А mysqli_stmt_init().

Вратени вредности

Вратени вредности
Име (константа) = NULL
true што може да ја намали перформансата (но ги намалува трошоците за меморија).
false Успех. Податоците се преземени
null Се појави грешка

Errors/Exceptions

Ако е овозможено известување за грешки на mysqli (MYSQLI_REPORT_ERROR) и бараната операција не успее, се генерира предупредување. Ако, дополнително, режимот е поставен на MYSQLI_REPORT_STRICT, а mysqli_sql_exception наместо тоа се фрла.

Примери

Пример #1 Обектно-ориентиран стил

<?php
$mysqli
= new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 150,5";

if (
$stmt = $mysqli->prepare($query)) {

/* execute statement */
$stmt->execute();

/* bind result variables */
$stmt->bind_result($name, $code);

/* fetch values */
while ($stmt->fetch()) {
printf ("%s (%s)\n", $name, $code);
}

/* close statement */
$stmt->close();
}

/* close connection */
$mysqli->close();
?>

Пример #2 Процедурален стил

<?php
$link
= mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 150,5";

if (
$stmt = mysqli_prepare($link, $query)) {

/* execute statement */
mysqli_stmt_execute($stmt);

/* bind result variables */
mysqli_stmt_bind_result($stmt, $name, $code);

/* fetch values */
while (mysqli_stmt_fetch($stmt)) {
printf ("%s (%s)\n", $name, $code);
}

/* close statement */
mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

Горните примери ќе дадат излез:

Rockford (USA)
Tallahassee (USA)
Salinas (USA)
Santa Clarita (USA)
Springfield (USA)

Види Исто така

  • mysqli_prepare() - Подготвува SQL израз за извршување
  • mysqli_stmt_errno() - Испраќање податоци во блокови
  • mysqli_stmt_error() - Враќа код за грешка за најновата изјава повик
  • mysqli_stmt_bind_result() - Поврзува променливи со подготвена изјава како параметри

Белешки од корисници 5 белешки

Нема повеќе редови/податоци или се случило скратување на податоци
пред 14 години
I was trying to use a generic select * from table statment and have the results returned in an array. I finally came up with this solution, others have similar solutions, but they where not working for me. 
<?php
    //Snip use normal methods to get to this point
    $stmt->execute();
    $metaResults = $stmt->result_metadata();
    $fields = $metaResults->fetch_fields();
    $statementParams='';
     //build the bind_results statement dynamically so I can get the results in an array
     foreach($fields as $field){
         if(empty($statementParams)){
             $statementParams.="\$column['".$field->name."']";
         }else{
             $statementParams.=", \$column['".$field->name."']";
         }
    }
    $statment="\$stmt->bind_result($statementParams);";
    eval($statment);
    while($stmt->fetch()){
        //Now the data is contained in the assoc array $column. Useful if you need to do a foreach, or 
        //if your lazy and didn't want to write out each param to bind.
    }
    // Continue on as usual.
?>
Брус Мартин
пред 18 години
The following function taken from PHP Cookbook 2, returns an associative array of a row in the resultset, place in while loop to iterate through whole result set.

<?php
public function fetchArray () {
   $data = mysqli_stmt_result_metadata($this->stmt);
        $fields = array();
        $out = array();

        $fields[0] = &$this->stmt;
        $count = 1;

        while($field = mysqli_fetch_field($data)) {
            $fields[$count] = &$out[$field->name];
            $count++;
        }
        
        call_user_func_array(mysqli_stmt_bind_result, $fields);
        mysqli_stmt_fetch($this->stmt);
        return (count($out) == 0) ? false : $out;

    }
?>
dan dot latter at gmail dot com
пред 17 години
I tried the mentioned stmt_bind_assoc() function, but somehow, very strangely it doesn't allow the values to be written in an array! In the while loop, the row is fetched correctly, but if I write $array[] = $row;, the array will be filled up with the last element of the dataset... Unfortunately I couldn't find a solution.
piedone at pyrocenter dot hu
пред 17 години
This function uses the same idea as the last, but instead binds the fields to a given array. 
<?php
function stmt_bind_assoc (&$stmt, &$out) {
    $data = mysqli_stmt_result_metadata($stmt);
    $fields = array();
    $out = array();

    $fields[0] = $stmt;
    $count = 1;

    while($field = mysqli_fetch_field($data)) {
        $fields[$count] = &$out[$field->name];
        $count++;
    }    
    call_user_func_array(mysqli_stmt_bind_result, $fields);
}

// example

$stmt = $mysqli->prepare("SELECT name, userid FROM somewhere");
$stmt->execute();

$row = array();
stmt_bind_assoc($stmt, $row);

// loop through all result rows
while ($stmt->fetch()) {
    print_r($row);
}
?>
davidm на marketo точка com
20 години пред
IMPORTANT note: Be careful when you use this function with big result sets or with BLOB/TEXT columns. When one or more columns are of type (MEDIUM|LONG)(BLOB|TEXT) and ::store_result() was not called mysqli_stmt_fetch() will try to allocate at least 16MB for every such column. It _doesn't_ matter that the longest value in the result set is for example 30 bytes, 16MB will be allocated. Therefore it is not the best idea ot use binding of parameters whenever fetching big data. Why? Because once the data is in the mysql result set stored in memory and then second time in the PHP variable.
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.