Conn2Flow
Docs navigation

Reference / Libraries

banco.php library

The Gestor database layer (MySQLi): connection, queries, structured SELECT, accumulated INSERT/UPDATE, unique identifiers and distributed mode.

Path in the Gestor bibliotecas/banco.php

banco.php is the data access layer of the whole Gestor. It is always loaded ($_GESTOR['bibliotecas']) and talks to MySQL/MariaDB through MySQLi, building SQL by string concatenation. There are no prepared statements: safety depends on escaping every value with banco_escape_field().

Configuration and connection

The connection uses $_BANCO, filled in gestor/config.php from .env:

Key .env variable Default
tipo DB_CONNECTION mysqli (the only implemented type)
host DB_HOST localhost
nome DB_DATABASE —
usuario / senha DB_USERNAME / DB_PASSWORD —
  • The connection is lazy. banco_query() and banco_escape_field() call banco_conectar() the first time; there is no need to connect by hand.

  • banco_conectar() enables MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT, opens the connection and sets the utf8 charset. If the connection fails, it ends the request with die(), printing the error and the stack built by banco_erro_debug() (HTML with file:line => function for each frame).

  • banco_fechar_conexao() closes and removes $_BANCO['conexao'].

  • banco_ping() tests the connection with mysqli_ping() and, when it is down, only increments $_BANCO['RECONECT']: it does not reconnect.

Running SQL

  • banco_query($query) runs any SQL. With $_BANCO['distribuido'] enabled, it does not use the local database: it forwards the statement to banco_distribuido_query() (distributed modules, req-005), which returns a BancoResultadoRemoto for SELECT or true/false for writes. Locally, a mysqli_sql_exception is caught, logged with error_log() (including the SQL) and becomes false. No error reaches the screen.

  • banco_sql($sql) runs and returns every row with numeric and named indexes (mysqli_fetch_array), or null without results.

  • banco_sql_names($sql, $campos) runs and returns associative rows using the names in $campos (comma-separated list, or *).

  • banco_linhas_afetadas() returns how many rows the last write changed (or null in distributed mode). It supports "only the first request claims the action": UPDATE … WHERE <not done yet> affects 1 row for whoever arrives first and 0 for the others.

  • banco_last_id() returns the AUTO_INCREMENT of the last INSERT (in distributed mode, the id reported by the remote installation).

Reading a raw result

The wrappers accept a mysqli_result or a BancoResultadoRemoto:

  • banco_num_rows($result) returns 0 for false. This avoids the PHP 8.1+ TypeError when the query failed;

  • banco_num_fields($result), banco_field_name($result, $i) and banco_fields_names($table): the last one runs SELECT * … LIMIT 1 and returns the column names, or null when there are no columns;

  • banco_row($result) returns an indexed row;

  • banco_row_array($result) returns an indexed and associative row;

  • banco_fetch_assoc($result) returns an associative row.

Structured SELECT: banco_select()

This is the recommended way to query:

$paginas = banco_select(Array(
    'tabela' => 'paginas',
    'campos' => Array('id', 'nome', 'caminho'),
    'extra'  => "WHERE status='A' AND language='".banco_escape_field($lang)."' ORDER BY nome",
));
// [ ['id' => 'x', 'nome' => 'X', 'caminho' => 'x/'], ... ]  or  null
  • campos is an array (joined with commas) or a string, or *.

  • extra receives everything after FROM (JOIN, WHERE, ORDER BY, LIMIT). The table may have an alias: 'tabela' => 'paginas AS p'.

  • unico returns only the first row as a flat array, instead of a list.

  • Without results the return is null, not an empty array.

Positional variants, used by legacy code:

  • banco_select_name($campos, $tabela, $extra) returns associative rows (non-numeric values cast to string);

  • banco_select_editar($campos, $tabela, $extra) returns only the first row and sets $_GESTOR['banco-resultado'] (true/false).

Keeping the "before" of an edit

The CRUD history pattern:

  1. banco_select_campos_antes_iniciar($campos, $tabela, $extra) reads the record and stores its first row in $_GESTOR['banco-antes'] (returns true/false).

  2. banco_select_campos_antes($campo) returns a field's old value (or null) to compare with $_REQUEST and build the history with interface_historico_incluir().

Writing

INSERT

The most common way is to accumulate fields and insert once:

banco_insert_name_campo('id', $id);                 // escapes and quotes
banco_insert_name_campo('versao', '1', true);       // no quotes (number, NOW(), NULL)
banco_insert_name_campo('html', $html, false, false); // no escaping (already escaped)
banco_insert_name(banco_insert_name_campos(), 'paginas');
  • banco_insert_name_campo($nome, $valor, $sem_aspas_simples = false, $escape_field = true) accumulates in $_BANCO['insert-name-campos'], escaping the value by default.

  • banco_insert_name_campos() returns the accumulated fields and clears the list.

  • banco_insert_name($dados, $tabela) takes [[name, value, no_quotes], …] and builds INSERT INTO t (…) VALUES (…). It does not escape: either the values came from banco_insert_name_campo() or you escape them first (as modules do with banco_escape_field($_REQUEST[...])). Items without a name or value are skipped.

  • banco_insert_name_varios(['tabela' => …, 'campos' => [['nome' => …, 'valores' => [...], 'sem_aspas_simples' => true], …]]) runs a multi-row INSERT, organized by column. null becomes NULL. It does not escape.

Legacy functions without callers in the core, which depend on the physical column order and escape nothing:

  • banco_insert($campos, $tabela): VALUES('0', …);

  • banco_insert_tudo($campos, $tabela) and banco_insert_id($campos, $tabela): VALUES(…);

  • banco_insert_varios($campos, $tabela) and banco_insert_varios_tudo($campos, $tabela): several rows. Both concatenate into an uninitialized variable (PHP 8 warning).

UPDATE

  • banco_update($campos, $tabela, $extra) runs UPDATE t SET <fields> <extra>. $campos is the ready string ("nome='x', versao=versao+1").

  • banco_update_campo($nome, $valor, $sem_aspas_simples = false, $escape_field = true) accumulates in $_BANCO['update-campos'], and banco_update_executar($tabela, $extra = '') runs and clears it. With nothing accumulated, it does nothing.

  • banco_update_varios($campos, $tabela, $campo_nome, $id_nome) updates many records with CASE id WHEN … THEN …, splitting into several queries above ~1 MB. Values are not escaped, and the function concatenates into an uninitialized $sql_fechar. No callers in the core.

Insert or update

banco_insert_update(['tabela' => ['nome' => …, 'id' => …, 'extra' => …], 'dados' => [...], 'dadosTipo' => [...]]) looks up the record by dados[<id>]: UPDATE if it exists, INSERT otherwise. With dadosTipo, bool stores 1/NULL and int stores the number unquoted (empty becomes NULL); everything else is escaped and quoted. It does not filter by language, neither when looking up nor when updating.

DELETE

  • banco_delete($tabela, $extra) runs DELETE FROM t <extra>. Without a WHERE in $extra, it empties the table.

  • banco_delete_varios($tabela, $campo_ids, $array_ids) builds DELETE … WHERE field IN (…).

Unique identifiers (slugs)

CRUDs generate the record's textual id from its name:

$id = banco_identificador(Array(
    'id' => $_REQUEST['nome'],
    'tabela' => Array(
        'nome' => 'paginas', 'campo' => 'id', 'id_nome' => 'id_paginas',
        'where' => "language='".$_GESTOR['linguagem-codigo']."'",
    ),
));
  1. banco_identificador() normalizes the text with banco_retirar_acentos(), cuts it at ~90 characters (by word) and, when the text already ends in -<number>, starts from that number.

  2. banco_identificador_unico() tries id, id-1, id-2… until it finds a free one, ignoring records with status='D'. tabela options:

    • id_valor excludes the record itself, when editing;

    • status sets another status column;

    • sem_status disables the status filter;

    • where adds a condition. With sem_traco, hyphens are removed from the result.

banco_retirar_acentos($var, $retirar_espaco = true) replaces accents with ASCII, strips punctuation, turns parentheses and brackets into hyphens and spaces into hyphens (optional), and collapses hyphens.

Utilities

  • banco_escape_field($field) escapes with mysqli_real_escape_string(), connecting if needed. Without an active MySQLi connection it throws LogicException instead of returning the value unescaped.

  • banco_campos_virgulas($campos) joins an array with commas ('' when empty).

  • banco_total_rows($tabela, $extra = null) runs SELECT count(*) and returns the total. No callers in the core.

  • banco_campos_nomes($tabela) runs SHOW COLUMNS and returns each column's metadata (Field, Type, Null, Key, Default, Extra).

  • banco_campo_existe($campo, $tabela) tells whether the column exists. Modules use it to work both before and after a migration (for example, css_source_hash).

  • banco_tabelas_lista() runs SHOW TABLES and returns the names.

  • banco_smartstripslashes($str) only casts to string. It is kept for compatibility; do not use it in new code.

See also

  • Gestor libraries

  • Skills c2f-database-operations, c2f-database-testing and c2f-mysql-utf8-emoji-encoding.

Functions (generated reference)

Generated from gestor/bibliotecas/banco.php · 47 functions

47 of 47

banco_escape_field

view source · line 30 ↗
banco_escape_field(string $field): string

Escapa um valor para uso seguro em queries SQL.

Parameters

$fieldstring
O valor a ser escapado.

Returns

string
O valor escapado e seguro para uso em queries SQL.

banco_query

view source · line 165 ↗
banco_query(string $query): mysqli_result|bool

Executa uma query SQL no banco de dados.

Parameters

$querystring
A query SQL a ser executada.

Returns

mysqli_result|bool
O resultado da query ou false em caso de erro.

banco_num_rows

view source · line 241 ↗
banco_num_rows(mixed $result): int

Retorna o número de linhas de um resultado de query.

Parameters

$resultmixed
Resultado mysqli, remoto ou valor inválido retornado pela query.

Returns

int
O número de linhas no resultado.

banco_num_fields

view source · line 268 ↗
banco_num_fields(mysqli_result $result): int

Retorna o número de campos/colunas em um resultado de query.

Parameters

$resultmysqli_result
O resultado da query.

Returns

int
O número de campos no resultado.

banco_field_name

view source · line 289 ↗
banco_field_name(mysqli_result $result, int $num_field): string

Retorna o nome de um campo específico do resultado.

Parameters

$resultmysqli_result
O resultado da query.
$num_fieldint
O índice do campo (começando em 0).

Returns

string
O nome do campo.

banco_fields_names

view source · line 312 ↗
banco_fields_names(string $table): array|null

Retorna um array com os nomes de todos os campos de uma tabela.

Parameters

$tablestring
Nome da tabela.

Returns

array|null
Array com os nomes dos campos ou NULL se a tabela estiver vazia.

banco_row

view source · line 343 ↗
banco_row(mysqli_result $result): array|null

Retorna uma linha do resultado como array indexado.

Parameters

$resultmysqli_result
O resultado da query.

Returns

array|null
Array com os valores da linha ou NULL se não houver mais linhas.

banco_row_array

view source · line 363 ↗
banco_row_array(mysqli_result $result): array|null

Retorna uma linha do resultado como array associativo e indexado.

Parameters

$resultmysqli_result
O resultado da query.

Returns

array|null
Array com os valores da linha ou NULL se não houver mais linhas.

banco_fetch_assoc

view source · line 383 ↗
banco_fetch_assoc(mysqli_result $result): array|null

Retorna a próxima linha como array associativo.

Parameters

$resultmysqli_result
O resultado da query.

Returns

array|null
Array associativo com os valores da linha ou NULL.

banco_sql

view source · line 404 ↗
banco_sql(string $sql): array|null

Executa uma query SQL e retorna todos os resultados.

Parameters

$sqlstring
A query SQL a ser executada.

Returns

array|null
Array com todas as linhas do resultado ou NULL se não houver resultados.

banco_sql_names

view source · line 432 ↗
banco_sql_names(string $sql, string $campos): array|null

Executa uma query SQL e retorna resultados com nomes de campos.

Parameters

$sqlstring
A query SQL a ser executada.
$camposstring
Lista de campos separados por vírgula ou '*' para todos.

Returns

array|null
Array de arrays associativos ou NULL se não houver resultados.

banco_select

view source · line 484 ↗
banco_select(array|false $params = false): array|null

Seleciona dados do banco de dados de forma estruturada.

Parameters

$paramsarray|false
Parâmetros da função.

Returns

array|null
Array com os resultados ou NULL se não houver dados.

banco_select_name

view source · line 555 ↗
banco_select_name(string $campos, string $tabela, string $extra): array|null

Seleciona dados do banco retornando arrays associativos.

Parameters

$camposstring
Lista de campos separados por vírgula ou '*'.
$tabelastring
Nome da tabela.
$extrastring
Condições extras da query (WHERE, ORDER BY, etc.).

Returns

array|null
Array com os resultados ou NULL se não houver dados.

banco_select_editar

view source · line 612 ↗
banco_select_editar(string $campos, string $tabela, string $extra): array|null

Seleciona um único registro para edição.

Parameters

$camposstring
Lista de campos separados por vírgula ou '*'.
$tabelastring
Nome da tabela.
$extrastring
Condições extras da query (WHERE, ORDER BY, etc.).

Returns

array|null
Array associativo com o registro ou NULL se não houver dados.

banco_select_campos_antes_iniciar

view source · line 677 ↗
banco_select_campos_antes_iniciar(string $campos, string $tabela, string $extra): bool

Seleciona e armazena campos anteriores para comparação.

Parameters

$camposstring
Lista de campos separados por vírgula ou '*'.
$tabelastring
Nome da tabela.
$extrastring
Condições extras da query (WHERE, etc.).

Returns

bool
True se encontrou e armazenou dados, false caso contrário.

banco_update

view source · line 763 ↗
banco_update(string $campos, string $tabela, string $extra): void

Executa query UPDATE no banco de dados.

Parameters

$camposstring
Lista de campos e valores no formato "campo='valor'".
$tabelastring
Nome da tabela.
$extrastring
Condições extras (WHERE, etc.).

Returns

void

banco_update_campo

view source · line 789 ↗
banco_update_campo(string $nome, string $valor, bool $sem_aspas_simples = false, bool $escape_field = true): void

Adiciona campo para atualização em lote.

Parameters

$nomestring
Nome do campo.
$valorstring
Valor a ser atribuído.
$sem_aspas_simplesbool
Se true, não envolve valor em aspas (padrão: false).
$escape_fieldbool
Se true, escapa o valor (padrão: true).

Returns

void

banco_update_executar

view source · line 819 ↗
banco_update_executar(string $tabela, string $extra = ''): void

Executa update em lote com campos acumulados.

Parameters

$tabelastring
Nome da tabela.
$extrastring
Condições extras como WHERE (padrão: '').

Returns

void

banco_update_varios

view source · line 858 ↗
banco_update_varios(array $campos, string $tabela, string $campo_nome, string $id_nome): void

Atualiza múltiplos registros em massa usando CASE.

Parameters

$camposarray
Array de arrays [id, valor] para atualizar.
$tabelastring
Nome da tabela.
$campo_nomestring
Nome do campo a ser atualizado.
$id_nomestring
Nome do campo ID usado na cláusula CASE.

Returns

void

banco_insert

view source · line 895 ↗
banco_insert(string $campos, string $tabela): void

Insere registro com ID auto-incrementado.

Parameters

$camposstring
Valores separados por vírgula.
$tabelastring
Nome da tabela.

Returns

void

banco_insert_name

view source · line 911 ↗
banco_insert_name(array $dados, string $tabela): void

Insere registro com nomes de campos especificados.

Parameters

$dadosarray
Array de arrays [nome, valor, sem_aspas_simples].
$tabelastring
Nome da tabela.

Returns

void

banco_insert_name_campo

view source · line 953 ↗
banco_insert_name_campo(string $nome, string $valor, bool $sem_aspas_simples = false, bool $escape_field = true): void

Adiciona campo para inserção em lote.

Parameters

$nomestring
Nome do campo.
$valorstring
Valor do campo.
$sem_aspas_simplesbool
Se true, não envolve em aspas (padrão: false).
$escape_fieldbool
Se true, escapa o valor (padrão: true).

Returns

void

banco_insert_varios

view source · line 1077 ↗
banco_insert_varios(array $campos, string $tabela): void

Insere vários registros com ID auto-increment.

Parameters

$camposarray
Array de strings com valores para cada registro.
$tabelastring
Nome da tabela.

Returns

void

banco_insert_varios_tudo

view source · line 1104 ↗
banco_insert_varios_tudo(array $campos, string $tabela): void

Insere vários registros com todos os valores especificados.

Parameters

$camposarray
Array de strings com valores para cada registro.
$tabelastring
Nome da tabela.

Returns

void

banco_insert_id

view source · line 1131 ↗
banco_insert_id(string $campos, string $tabela): void

Insere registro com ID especificado.

Parameters

$camposstring
Valores separados por vírgula.
$tabelastring
Nome da tabela.

Returns

void

banco_insert_tudo

view source · line 1146 ↗
banco_insert_tudo(string $campos, string $tabela): void

Insere registro com todos os valores especificados.

Parameters

$camposstring
Valores separados por vírgula.
$tabelastring
Nome da tabela.

Returns

void

banco_delete

view source · line 1179 ↗
banco_delete(string $tabela, string $extra): void

Executa DELETE no banco de dados.

Parameters

$tabelastring
Nome da tabela.
$extrastring
Condições WHERE e outras cláusulas.

Returns

void

banco_delete_varios

view source · line 1196 ↗
banco_delete_varios(string $tabela, array|string $campo_ids, array $array_ids): void

Deleta múltiplos registros usando IN.

Parameters

$tabelastring
Nome da tabela.
$campo_idsarray|string
Nome(s) do(s) campo(s) ID.
$array_idsarray
Array de IDs para deletar.

Returns

void

banco_total_rows

view source · line 1263 ↗
banco_total_rows(string $tabela, string|null $extra = null): int

Retorna total de linhas em uma tabela.

Parameters

$tabelastring
Nome da tabela.
$extrastring|null
Condições WHERE opcionais (padrão: null).

Returns

int
Número total de registros.

banco_campo_existe

view source · line 1318 ↗
banco_campo_existe(string $campo, string $tabela): bool

Verifica se um campo específico existe em uma tabela.

Parameters

$campostring
Nome do campo a ser verificado.
$tabelastring
Nome da tabela onde verificar o campo.

Returns

bool
True se o campo existir na tabela, false caso contrário.

banco_retirar_acentos

view source · line 1346 ↗
banco_retirar_acentos(string $var, bool $retirar_espaco = true): string

Remove acentos e caracteres especiais de uma string.

Parameters

$varstring
String a ser processada.
$retirar_espacobool
Se true, substitui espaços por hífens (padrão: true).

Returns

string
String normalizada.

banco_identificador

view source · line 1462 ↗
banco_identificador(array|false $params = false): string

Gera identificador único a partir de string.

Parameters

$paramsarray|false
Parâmetros da função.

Returns

string
ID único gerado e validado.

The Future is Hybrid: Human + AI.

Conn2Flow is the tool. If you need the Architect to design your company's strategy using this technology...

Hire Specialized Consulting