English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

tutorial básico PHP

tutorial avançado PHP

PHP & MySQL

manual de referência PHP

Uso e exemplo da função PHP mysqli_stmt_fetch()

PHP MySQLi Manual

A função mysqli_stmt_fetch() extrairá os resultados da sentença pré-preparada para as variáveis vinculadas.

definição e uso

Você pode usar a função mysqli_prepare() para criar uma sentença preparada que tenha marcadores de parâmetros (“?”) (se houver valores). Após a sentença preparada, é necessário usarmysqli_stmt_bind_param()A função vincula valores aos parâmetros da sentença criada.

Da mesma forma, você pode usar a função mysqli_stmt_bind_result() para vincular as colunas do conjunto de resultados da sentença aos variáveis necessários.

Se for chamadamysqli_stmt_fetch();A função, após o vínculo das colunas, extrairá as colunas dos resultados da sentença para as variáveis especificadas.

sintaxe

mysqli_stmt_fetch($stmt);

parâmetro

número de ordemparâmetros e descrição
1

stmt(obrigatório)

Isso representa o objeto da sentença pronta.

valor de retorno

Se obter dados, a função PHP mysqli_stmt_fetch() retornaráTRUE;; se houver um erro, retornaFALSE; se não houver mais linhas no resultado, retornaNULL.

Versão do PHP

Essa função foi introduzida na versão do PHP5introduzido e pode ser usado em todas as versões mais recentes.

Online example

A seguir é um exemplo que demonstramysqli_stmt_fetch();Uso da função (estilo procedimental), usando declarações preparadas para vincular valores do resultado a variáveis:

<?php
   $con = mysqli_connect("localhost", "root", "password", "mydb");
   mysqli_query($con, "CREATE TABLE myplayers(ID INT, Primeiro_Nome VARCHAR(255), Sobrenome VARCHAR(255), Local_de_Nascimento VARCHAR(255), País VARCHAR(255))");
   print("Criando tabela.....\n");
   mysqli_query($con, "INSERT INTO myplayers values(1, 'Sikhar', 'Dhawan', 'Delhi', 'India')");
   mysqli_query($con, "INSERT INTO myplayers values(2, 'Jonathan', 'Trott', 'CapeTown', 'SouthAfrica')");
   print("Inserir registro.....\n");
   //Recuperar conteúdo da tabela
   $stmt = mysqli_prepare($con, "SELECT * FROM myplayers");
   //Execute statement
   mysqli_stmt_execute($stmt);
   //Bind the values in the result to the variables
   mysqli_stmt_bind_result($stmt, $id, $fname, $lname, $pob, $country);
   while (mysqli_stmt_fetch($stmt)) {
      print("Id: ".$id."\n");
      print("fname: ".$fname."\n");
      print("lname: ".$lname."\n");
      print("pob: ".$pob."\n");
      print("country: ".$country."\n");
      print("\n");
   }
   //End statement
   mysqli_stmt_close($stmt);
   //Close connection
   mysqli_close($con);
?>

Output result

Create table.....
Inserir registro.....
Id: 1
fname: Sikhar
lname: Dhawan
pob: Delhi
country: India
Id: 2
fname: Jonathan
lname: Trott
pob: CapeTown
country: SouthAfrica

Online example

No estilo orientado a objetos, a sintaxe dessa função é$stmt->fetch();。A seguir está um exemplo de estilo orientado a objetos para essa função, usando declarações preparadas para vincular variáveis ao conjunto de resultados:

<?php
   //Construir conexão
   $con = new mysqli("localhost", "root", "password", "mydb");
   $con ->query("CREATE TABLE Test(Name VARCHAR(255), AGE INT");
   $con ->query("insert into Test values('Raju', 25),('Rahman', 30),('Sarmista', 27))");
   print("Criando tabela.....\n");
   $stmt = $con -> prepare("SELECT * FROM Test WHERE Nome in(?, ?)");
   $stmt -> bind_param("ss", $name1, $name2);
   $name1 = 'Raju';
   $name2 = 'Rahman';
   print("Registro excluído.....\n");
   //Execute statement
   $stmt->execute();
   //Vincular variáveis ao conjunto de resultados
   $stmt->bind_result($name, $age);
   while ($stmt->fetch()) {
      print("Nome: "+$name+"\n");
      print("Idade: "+$age+"\n");
   }
   //End statement
   $stmt->close();
   //Close connection
   $con->close();
?>

Output result

Create table.....
Registro excluído.....
Nome: Raju
Idade: 25
Nome: Rahman
Idade: 30

Online example

A seguir, um exemplo de uso das funções mysqli_stmt_bind_result() e mysqli_stmt_fetch() para obter os resultados da consulta DESCRIBE-

<?php
   $con = mysqli_connect("localhost", "root", "password", "mydb");
   mysqli_query($con, "CREATE TABLE myplayers(ID INT, Primeiro_Nome VARCHAR(255), Sobrenome VARCHAR(255), Local_de_Nascimento VARCHAR(255), País VARCHAR(255))");
   print("Criando tabela.....\n");
   //Descrição da tabela
   $stmt = mysqli_prepare($con, "DESC myplayers");
   //Execute statement
   mysqli_stmt_execute($stmt);
   //Bind the values in the result to the variables
   mysqli_stmt_bind_result($stmt, $field, $type, $null, $key, $default, $extra);
   while (mysqli_stmt_fetch($stmt)) {
      print("Field: "+$field+"\n");
      print("Type: "+$type+"\n");
      print("Null: "+$null+"\n");
      print("Key: "+$key+"\n");
      print("Default: ",$default,"\n");
      print("Extra: ",$extra,"\n");
      print("\n");
   }
   //End statement
   mysqli_stmt_close($stmt);
   //Close connection
   mysqli_close($con);
?>

Output result

Create table.....
Field: ID
Type: int(11)
Null: YES
Key:
Default:
Extra:
Field: First_Name
Type: varchar(255)
Null: YES
Key:
Default:
Extra:
Field: Last_Name
Type: varchar(255)
Null: YES
Key:
Default:
Extra:
Field: Place_Of_Birth
Type: varchar(255)
Null: YES
Key:
Default:
Extra:
Field: Country
Type: varchar(255)
Null: YES
Key:
Default:
Extra:

Online example

The following example uses the mysqli_stmt_bind_result() and mysqli_stmt_fetch() functions to retrieve the results of the SHOW TABLES query, returning all tables in the current database:

<?php
   $con = mysqli_connect("localhost", "root", "password");
   //Select database
   mysqli_query($con, "CREATE DATABASE NewDatabase");
   mysqli_select_db($con, "NewDatabase");
   //Create table
   mysqli_query($con, "CREATE TABLE test1(Name VARCHAR(255), Age INT)");
   mysqli_query($con, "CREATE TABLE test2(Name VARCHAR(255), Age INT)");
   mysqli_query($con, "CREATE TABLE test3(Name VARCHAR(255), Age INT)");
   print("Created tables.....\n");
   //Show tables
   $stmt = mysqli_prepare($con, "SHOW TABLES");
   //Execute statement
   mysqli_stmt_execute($stmt);
   //Bind the values in the result to the variables
   mysqli_stmt_bind_result($stmt, $table_name);
   print("All tables in the current database: \n");
   while (mysqli_stmt_fetch($stmt)) {
      print($table_name."\n");
   }
   //End statement
   mysqli_stmt_close($stmt);
   //Close connection
   mysqli_close($con);
?>

Output result

Created tables.....
All tables in the current database:
test1
test2
test3

PHP MySQLi Manual