Ir para conteúdo

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

BrunoBit

anti sql injection

Recommended Posts

Fala pessoal, bom dia, tudo joia por aí?

Esses dias eu li uma matéria/aula de um site que o @Gabriel Heming compartilhou com a gente aqui no fórum sobre sql injection, acredito que seja um dos melhores conteúdos explicativos sobre sql injection, vou deixar o link aqui pra vcs caso queiram ler também pq vale à pena pra quem quer formatar bem seu sql e proteger seu banco de injeções: https://phpdelusions.net/sql_injection

 

Gostaria de saber, como vocês fazem pra bloquear sql injection? Digo com relações à verificações antes de inserir qualquer coisa no sql, pq pelo o que entendi no artigo basicamente a sql injection acontece por má formatação do sql e por verificações erradas do conteúdo das variáveis, aí a pessoa de má fé explora essas más formatações.

Hoje tava fazendo uma conexão ao banco de dados e parei pra pensar nisso, com relação à verificações, em um primeiro momento saiu isso

    $business_name  = $_POST['business'];
    $name_business  = $_POST['txtuname'];
    $email_business = $_POST['txtemail'];
    $upass          = $_POST['txtpass'];
    $active_invoice = $_POST['ativar_fatura'];
    $price_business = $_POST['business_price'];
    $verify_variables = array($business_name,$name_business,$email_business,$upass,$active_invoice,$price_business);
    for($i = 0;$i < count($verify_variables);$i++){
        $verify_variables[$i]  = str_replace("=", "", $verify_variables[$i]);
        $verify_variables[$i]  = str_replace("'", "", $verify_variables[$i]);
        $verify_variables[$i]  = str_replace("`", "", $verify_variables[$i]);
        $verify_variables[$i]  = str_replace(":", "", $verify_variables[$i]);
        $verify_variables[$i]  = str_replace(";", "", $verify_variables[$i]);
        $verify_variables[$i]  = str_replace(",", "", $verify_variables[$i]);
        $verify_variables[$i]  = str_replace("(", "", $verify_variables[$i]);
        $verify_variables[$i]  = str_replace(")", "", $verify_variables[$i]);
        $verify_variables[$i]  = str_replace("\"", "", $verify_variables[$i]);
        $verify_variables[$i]  = str_replace("INSERT INTO", "", $verify_variables[$i]);
        $verify_variables[$i]  = str_replace("DELETE FROM", "", $verify_variables[$i]);
        $verify_variables[$i]  = str_replace("SELECT FROM", "", $verify_variables[$i]);
        $verify_variables[$i]  = str_replace("SELECT * FROM", "", $verify_variables[$i]);
        $verify_variables[$i]  = str_replace("SELECT *", "", $verify_variables[$i]);
        $verify_variables[$i]  = str_replace("DELETE * FROM", "", $verify_variables[$i]);
        $verify_variables[$i]  = str_replace("DELETE *", "", $verify_variables[$i]);
    }

Existe bastante discussão com relação às aspas simples ', como no caso de alguém com nome de Hanna O'hara, bastante comum nos estados unidos esse estilo de nome, mas aqui no Brasil acredito que quase ninguém tenha esse nome com aspas simples, a não ser se um gringo for utilizar.

Eu sinceramente ainda não sei utilizar 100% o htmlentities(), htmlspecialchars(), mysql_real_string_escape() e derivados pra fazer uma boa verificação assim que receber a variável, como os $_POST[''] lá em cima que estão tudo "pelado" sem nenhuma pré verificação com htmlentities, htmlspecialchar ou mysql_real_string_escape.

 

Como vocês fazem? O que vocês adicionariam ou removeriam nesse código que dei de exemplo? Ou se fariam completamente diferente.

 

Valeu rapaziada, abração pra vocês e fiquem com Deus.

Compartilhar este post


Link para o post
Compartilhar em outros sites

Cara, muitos ORMs, que são camadas de abstrações de banco de dados, realizam essa proteção de forma bastante eficaz. Você pode encontrar vários projetos, como o Doctrine, Eloquent, TORM etc ou você pode utilizar a PDO que é nativa do PHP.

 

Como você já entende quais são os possíveis problemas que pode ter se não tiver um certo cuidado, fica fácil de entender como essas camadas de abstrações se previnem desse tipo de ataque. Sugiro que você escolha um e estude/utilize/teste pra entender como são realizadas essas prevenções.

 

Nada melhor que fuçar o código e/ou documentação :P

Compartilhar este post


Link para o post
Compartilhar em outros sites

Cara, eu particularmente trabalho só com sistema interno, então essa não é um grande problema, mas pra previnir algum cara que se acha o hacker de fazer gracinha, ou algum operacional faça alguma coisa sem querer, eu uso duas ferramentas:

 

Classe GUMP -> Pra filtrar todos os inputs e integrar com meu framework de validação interno, essa classe aparentemente é muito boa e da pra extender facilmente.

 

PDO PHP -> para fazer as interações com o banco de dados.

 

Bem trabalhadas, elas devem oferecer uma segurança muito boa.

 

Ja a respeito do seu código, de forma mais básica eu importaria a classe GUMP e faria a sanitização:

 

<?php
$GUMP = new GUMP;
$post = $GUMP->sanitize($_POST);

$business_name  = $post['business'];
    $name_business  = $post['txtuname'];
    $email_business = $post['txtemail'];
    $upass          = $post['txtpass'];
    $active_invoice = $post['ativar_fatura'];
    $price_business = $post['business_price'];
  

 

 

Compartilhar este post


Link para o post
Compartilhar em outros sites

@Dorian Neto show de bola, vou estudar essas que você citou, PDO eu vejo uma boa galera usando também, ainda to na fase da conexão mais "comum" e aprendendo ela, depois vou partir pro PDO também, obrigadão Dorian.

@AnthraxisBR vou dar uma fuçada nesse GUMP, baixei ele aqui e vou fazer uns testes seguindo o exemplo que você deu.

 

Valeu mesmo rapaziiada, pq esse negócio de segurança com o banco de dados faz a gente coçar a cabeça.

 

Compartilhar este post


Link para o post
Compartilhar em outros sites

Muito simples, com infinidades de possibilidades....

 

expressão regular/ filtros/ tratamento de strings etc...

 

Mas só por dica deixar de usar SUPER-GLOBAL exemplo $_POST/$_GET etc... e principalmente $_SESSION

Compartilhar este post


Link para o post
Compartilhar em outros sites
13 minutos atrás, BrunoMs disse:

Bacana a dica @OmarF, no caso de deixar de usar as super global post, get e session, por qual função você substituiria elas?

 

Você não iria substituir, você iria passar por algum filtro, no exemplo que eu dei, foi o filtro do GUMP, mas existem muitos outros que também servem, da uma olhada:

 

https://www.w3schools.com/php/php_filter.asp

 

 

 

Compartilhar este post


Link para o post
Compartilhar em outros sites

@AnthraxisBR show de bola, agora entendi, ontem baixei o gump pra olhar e gostei bastante, vem com vários exemplos também. Preciso estudar classes agora pra compreender melhor a funcionalidade dele e adaptar nos meus códigos.

Compartilhar este post


Link para o post
Compartilhar em outros sites

Funções nativas do PHP para definir filtros:

Só com o uso desses filtros já se garante digamos 90% de segurança

Mais uma função de tratamento aqui e uma expressão regulá por alí digamos que se consegue 9% de segurança, sobrando 1%, porque nada é 100% seguro.

Spoiler

<?php

// Start of filter v.7.0.4-7ubuntu2

/**
 * (PHP 5 &gt;= 5.2.0, PHP 7)<br/>
 * Gets a specific external variable by name and optionally filters it
 * @link http://php.net/manual/en/function.filter-input.php
 * @param int $type <p>
 * One of <b>INPUT_GET</b>, <b>INPUT_POST</b>,
 * <b>INPUT_COOKIE</b>, <b>INPUT_SERVER</b>, or
 * <b>INPUT_ENV</b>.
 * </p>
 * @param string $variable_name <p>
 * Name of a variable to get.
 * </p>
 * @param int $filter [optional]
 * @param mixed $options [optional] <p>
 * Associative array of options or bitwise disjunction of flags. If filter
 * accepts options, flags can be provided in "flags" field of array.
 * </p>
 * @return mixed Value of the requested variable on success, <b>FALSE</b> if the filter fails,
 * or <b>NULL</b> if the <i>variable_name</i> variable is not set.
 * If the flag <b>FILTER_NULL_ON_FAILURE</b> is used, it
 * returns <b>FALSE</b> if the variable is not set and <b>NULL</b> if the filter fails.
 */
function filter_input(int $type, string $variable_name, int $filter = FILTER_DEFAULT, $options = null) {}

/**
 * (PHP 5 &gt;= 5.2.0, PHP 7)<br/>
 * Filters a variable with a specified filter
 * @link http://php.net/manual/en/function.filter-var.php
 * @param mixed $variable <p>
 * Value to filter.
 * </p>
 * @param int $filter [optional]
 * @param mixed $options [optional] <p>
 * Associative array of options or bitwise disjunction of flags. If filter
 * accepts options, flags can be provided in "flags" field of array. For
 * the "callback" filter, callable type should be passed. The
 * callback must accept one argument, the value to be filtered, and return
 * the value after filtering/sanitizing it.
 * </p>
 * <p>
 * <code>
 * // for filters that accept options, use this format
 * $options = array(
 * 'options' => array(
 * 'default' => 3, // value to return if the filter fails
 * // other options here
 * 'min_range' => 0
 * ),
 * 'flags' => FILTER_FLAG_ALLOW_OCTAL,
 * );
 * $var = filter_var('0755', FILTER_VALIDATE_INT, $options);
 * // for filter that only accept flags, you can pass them directly
 * $var = filter_var('oops', FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
 * // for filter that only accept flags, you can also pass as an array
 * $var = filter_var('oops', FILTER_VALIDATE_BOOLEAN,
 * array('flags' => FILTER_NULL_ON_FAILURE));
 * // callback validate filter
 * function foo($value)
 * {
 * // Expected format: Surname, GivenNames
 * if (strpos($value, ", ") === false) return false;
 * list($surname, $givennames) = explode(", ", $value, 2);
 * $empty = (empty($surname) || empty($givennames));
 * $notstrings = (!is_string($surname) || !is_string($givennames));
 * if ($empty || $notstrings) {
 * return false;
 * } else {
 * return $value;
 * }
 * }
 * $var = filter_var('Doe, Jane Sue', FILTER_CALLBACK, array('options' => 'foo'));
 * </code>
 * </p>
 * @return mixed the filtered data, or <b>FALSE</b> if the filter fails.
 */
function filter_var($variable, int $filter = FILTER_DEFAULT, $options = null) {}

/**
 * (PHP 5 &gt;= 5.2.0, PHP 7)<br/>
 * Gets external variables and optionally filters them
 * @link http://php.net/manual/en/function.filter-input-array.php
 * @param int $type <p>
 * One of <b>INPUT_GET</b>, <b>INPUT_POST</b>,
 * <b>INPUT_COOKIE</b>, <b>INPUT_SERVER</b>, or
 * <b>INPUT_ENV</b>.
 * </p>
 * @param mixed $definition [optional] <p>
 * An array defining the arguments. A valid key is a string
 * containing a variable name and a valid value is either a filter type, or an array
 * optionally specifying the filter, flags and options. If the value is an
 * array, valid keys are filter which specifies the
 * filter type,
 * flags which specifies any flags that apply to the
 * filter, and options which specifies any options that
 * apply to the filter. See the example below for a better understanding.
 * </p>
 * <p>
 * This parameter can be also an integer holding a filter constant. Then all values in the
 * input array are filtered by this filter.
 * </p>
 * @param bool $add_empty [optional] <p>
 * Add missing keys as <b>NULL</b> to the return value.
 * </p>
 * @return mixed An array containing the values of the requested variables on success, or <b>FALSE</b>
 * on failure. An array value will be <b>FALSE</b> if the filter fails, or <b>NULL</b> if
 * the variable is not set. Or if the flag <b>FILTER_NULL_ON_FAILURE</b>
 * is used, it returns <b>FALSE</b> if the variable is not set and <b>NULL</b> if the filter
 * fails.
 */
function filter_input_array(int $type, $definition = null, bool $add_empty = true) {}

/**
 * (PHP 5 &gt;= 5.2.0, PHP 7)<br/>
 * Gets multiple variables and optionally filters them
 * @link http://php.net/manual/en/function.filter-var-array.php
 * @param array $data <p>
 * An array with string keys containing the data to filter.
 * </p>
 * @param mixed $definition [optional] <p>
 * An array defining the arguments. A valid key is a string
 * containing a variable name and a valid value is either a
 * filter type, or an
 * array optionally specifying the filter, flags and options.
 * If the value is an array, valid keys are filter
 * which specifies the filter type,
 * flags which specifies any flags that apply to the
 * filter, and options which specifies any options that
 * apply to the filter. See the example below for a better understanding.
 * </p>
 * <p>
 * This parameter can be also an integer holding a filter constant. Then all values in the
 * input array are filtered by this filter.
 * </p>
 * @param bool $add_empty [optional] <p>
 * Add missing keys as <b>NULL</b> to the return value.
 * </p>
 * @return mixed An array containing the values of the requested variables on success, or <b>FALSE</b>
 * on failure. An array value will be <b>FALSE</b> if the filter fails, or <b>NULL</b> if
 * the variable is not set.
 */
function filter_var_array(array $data, $definition = null, bool $add_empty = true) {}

/**
 * (PHP 5 &gt;= 5.2.0, PHP 7)<br/>
 * Returns a list of all supported filters
 * @link http://php.net/manual/en/function.filter-list.php
 * @return array an array of names of all supported filters, empty array if there
 * are no such filters. Indexes of this array are not filter IDs, they can be
 * obtained with <b>filter_id</b> from a name instead.
 */
function filter_list(): array {}

/**
 * (PHP 5 &gt;= 5.2.0, PHP 7)<br/>
 * Checks if variable of specified type exists
 * @link http://php.net/manual/en/function.filter-has-var.php
 * @param int $type <p>
 * One of <b>INPUT_GET</b>, <b>INPUT_POST</b>,
 * <b>INPUT_COOKIE</b>, <b>INPUT_SERVER</b>, or
 * <b>INPUT_ENV</b>.
 * </p>
 * @param string $variable_name <p>
 * Name of a variable to check.
 * </p>
 * @return bool <b>TRUE</b> on success or <b>FALSE</b> on failure.
 */
function filter_has_var(int $type, string $variable_name): bool {}

/**
 * (PHP 5 &gt;= 5.2.0, PHP 7)<br/>
 * Returns the filter ID belonging to a named filter
 * @link http://php.net/manual/en/function.filter-id.php
 * @param string $filtername <p>
 * Name of a filter to get.
 * </p>
 * @return int ID of a filter on success or <b>FALSE</b> if filter doesn't exist.
 */
function filter_id(string $filtername): int {}


/**
 * POST variables.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('INPUT_POST', 0);

/**
 * GET variables.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('INPUT_GET', 1);

/**
 * COOKIE variables.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('INPUT_COOKIE', 2);

/**
 * ENV variables.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('INPUT_ENV', 4);

/**
 * SERVER variables.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('INPUT_SERVER', 5);

/**
 * SESSION variables.
 * (not implemented yet)
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('INPUT_SESSION', 6);

/**
 * REQUEST variables.
 * (not implemented yet)
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('INPUT_REQUEST', 99);

/**
 * No flags.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('FILTER_FLAG_NONE', 0);

/**
 * Flag used to require scalar as input
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('FILTER_REQUIRE_SCALAR', 33554432);

/**
 * Require an array as input.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('FILTER_REQUIRE_ARRAY', 16777216);

/**
 * Always returns an array.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('FILTER_FORCE_ARRAY', 67108864);

/**
 * Use NULL instead of FALSE on failure.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('FILTER_NULL_ON_FAILURE', 134217728);

/**
 * ID of "int" filter.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('FILTER_VALIDATE_INT', 257);

/**
 * ID of "boolean" filter.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('FILTER_VALIDATE_BOOLEAN', 258);

/**
 * ID of "float" filter.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('FILTER_VALIDATE_FLOAT', 259);

/**
 * ID of "validate_regexp" filter.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('FILTER_VALIDATE_REGEXP', 272);
define ('FILTER_VALIDATE_DOMAIN', 277);

/**
 * ID of "validate_url" filter.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('FILTER_VALIDATE_URL', 273);

/**
 * ID of "validate_email" filter.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('FILTER_VALIDATE_EMAIL', 274);

/**
 * ID of "validate_ip" filter.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('FILTER_VALIDATE_IP', 275);

/**
 * ID of "validate_mac_address" filter.
 * (Available as of PHP 5.5.0)
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('FILTER_VALIDATE_MAC', 276);

/**
 * ID of default ("unsafe_raw") filter. This is equivalent to
 * <b>FILTER_UNSAFE_RAW</b>.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('FILTER_DEFAULT', 516);

/**
 * ID of "unsafe_raw" filter.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('FILTER_UNSAFE_RAW', 516);

/**
 * ID of "string" filter.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('FILTER_SANITIZE_STRING', 513);

/**
 * ID of "stripped" filter.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('FILTER_SANITIZE_STRIPPED', 513);

/**
 * ID of "encoded" filter.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('FILTER_SANITIZE_ENCODED', 514);

/**
 * ID of "special_chars" filter.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('FILTER_SANITIZE_SPECIAL_CHARS', 515);
define ('FILTER_SANITIZE_FULL_SPECIAL_CHARS', 522);

/**
 * ID of "email" filter.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('FILTER_SANITIZE_EMAIL', 517);

/**
 * ID of "url" filter.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('FILTER_SANITIZE_URL', 518);

/**
 * ID of "number_int" filter.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('FILTER_SANITIZE_NUMBER_INT', 519);

/**
 * ID of "number_float" filter.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('FILTER_SANITIZE_NUMBER_FLOAT', 520);

/**
 * ID of "magic_quotes" filter.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('FILTER_SANITIZE_MAGIC_QUOTES', 521);

/**
 * ID of "callback" filter.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('FILTER_CALLBACK', 1024);

/**
 * Allow octal notation (0[0-7]+) in "int" filter.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('FILTER_FLAG_ALLOW_OCTAL', 1);

/**
 * Allow hex notation (0x[0-9a-fA-F]+) in "int" filter.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('FILTER_FLAG_ALLOW_HEX', 2);

/**
 * Strip characters with ASCII value less than 32.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('FILTER_FLAG_STRIP_LOW', 4);

/**
 * Strip characters with ASCII value greater than 127.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('FILTER_FLAG_STRIP_HIGH', 8);
define ('FILTER_FLAG_STRIP_BACKTICK', 512);

/**
 * Encode characters with ASCII value less than 32.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('FILTER_FLAG_ENCODE_LOW', 16);

/**
 * Encode characters with ASCII value greater than 127.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('FILTER_FLAG_ENCODE_HIGH', 32);

/**
 * Encode &#38;#38;.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('FILTER_FLAG_ENCODE_AMP', 64);

/**
 * Don't encode ' and ".
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('FILTER_FLAG_NO_ENCODE_QUOTES', 128);

/**
 * (No use for now.)
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('FILTER_FLAG_EMPTY_STRING_NULL', 256);

/**
 * Allow fractional part in "number_float" filter.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('FILTER_FLAG_ALLOW_FRACTION', 4096);

/**
 * Allow thousand separator (,) in "number_float" filter.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('FILTER_FLAG_ALLOW_THOUSAND', 8192);

/**
 * Allow scientific notation (e, E) in
 * "number_float" filter.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('FILTER_FLAG_ALLOW_SCIENTIFIC', 16384);
define ('FILTER_FLAG_SCHEME_REQUIRED', 65536);
define ('FILTER_FLAG_HOST_REQUIRED', 131072);

/**
 * Require path in "validate_url" filter.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('FILTER_FLAG_PATH_REQUIRED', 262144);

/**
 * Require query in "validate_url" filter.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('FILTER_FLAG_QUERY_REQUIRED', 524288);

/**
 * Allow only IPv4 address in "validate_ip" filter.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('FILTER_FLAG_IPV4', 1048576);

/**
 * Allow only IPv6 address in "validate_ip" filter.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('FILTER_FLAG_IPV6', 2097152);

/**
 * Deny reserved addresses in "validate_ip" filter.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('FILTER_FLAG_NO_RES_RANGE', 4194304);

/**
 * Deny private addresses in "validate_ip" filter.
 * @link http://php.net/manual/en/filter.constants.php
 */
define ('FILTER_FLAG_NO_PRIV_RANGE', 8388608);
define ('FILTER_FLAG_HOSTNAME', 1048576);

// End of filter v.7.0.4-7ubuntu2
?>

 

 

Compartilhar este post


Link para o post
Compartilhar em outros sites

  • Conteúdo Similar

    • Por landerbadi
      Boa tarde pessoal. Estou tentado fazer uma consulta no banco de dados porém estou tendo dificuldades. Tenho uma tabela chamada "itens" com os seguintes campos: id, item, ativo. Nela tem cadastrado vários itens. No campo ativo eu coloco a letra "S" para informar que este item está ativo no sistema. Por exemplo: 1, casa, S 2, mesa, S 3, cama, S 4, moto S 5, rádio O quinto registro "radio" não está ativo no sistema pois não tem um "S" no campo ativo. E outra tabela chamada "produtos" com os seguintes campos (id, item1, item2, item3) com os seguintes registros: 1, casa, mesa, moto 2, mesa, casa, cama 3, rádio, cama, mesa Eu preciso fazer uma busca na tabela produtos da seguinte maneira: Eu escolho um registro na tabela "itens", por exemplo "mesa". Preciso fazer com que o php me liste todos os registros da tabela "produtos" que contenham a palavra "mesa". Até aqui tudo bem eu consigo listar. Estou fazendo assim: <?php $item = "mesa" $sql = mysqli_query($conn, "SELECT * FROM produtos WHERE item1 LIKE '$item' OR item2 LIKE '$item' OR item3 LIKE '$item' LIMIT 10"); while($aux = mysqli_fetch_assoc($sql)) { $id = $aux["id"]; $item1 = $aux["item1"]; $item2 = $aux["item2"]; $item3 = $aux["item3"]; echo $id . " - " . $item1 . ", " . $item2 . ", " $item3 . "<br>"; } ?> O problema é que está listando todos os registros que contém o item mesa. Eu preciso que o php verifique os demais item e me liste somente os registro em que todos os registros estejam ativos no sistema. No exemplo acima ele não deveria listar o registro 3. pois nesse registro contém o item "radio" e este item não está ativo no sistema. Ou seja, o registro "radio" na tabela itens não possui um "S" na coluna "ativo". Alguém sabe como resolver isso?
    • Por ILR master
      Fala galera.
      Espero que todos estejam bem.
      Seguinte: Tenho um arquivo xml onde alguns campos estão com : (dois pontos), como o exemplo abaixo:
       
      <item>
      <title>
      d sa dsad sad sadasdas
      </title>
      <link>
      dsadas dsa sad asd as dsada
      </link>
      <pubDate>sadasdasdsa as</pubDate>
      <dc:creator>
      d sad sad sa ad as das
      </dc:creator>
      </item>
       
      Meu código:
       
      $link = "noticias.xml"; 
      $xml = simplexml_load_file($link); 
      foreach($xml -> channel as $ite) {     
           $titulo = $ite -> item->title;
           $urltitulo = $ite -> item->link;
           print $urltitulo = $ite -> item->dc:creator;
      } //fim do foreach
      ?>
       
      Esse campo dc:creator eu não consigo ler. Como faço?
       
      Agradeço quem puder me ajudar.
       
      Abs
       
       
    • Por First
      Olá a todos!
       
      Eu estou criando um sistema do zero mas estou encontnrando algumas dificuldades e não estou sabendo resolver, então vim recorrer ajuda de vocês.
      Aqui está todo o meu código: https://github.com/PauloJagata/aprendizado/
       
      Eu fiz um sistema de rotas mas só mostra o conteúdo da '/' não sei porque, quando eu tento acessar o register nada muda.
      E eu também quero que se não estiver liberado na rota mostra o erro de 404, mas quando eu tento acessar um link inválido, nada acontece.
      Alguém pode me ajudar com isso? E se tiver algumas sugestão para melhoria do código também estou aceitando.
       
       
      Desde já, obrigado.
    • Por landerbadi
      Olá pessoal, boa tarde
       
      Tenho uma tabela chamada "produtos" com os seguintes campos (id, produto) e outra tabela chamada "itens" com os seguintes campos (id, prod_01, prod_02, prod_03, prod_04).
       
      Na tabela produtos eu tenho cadastrado os seguintes produtos: laranja, maçã, uva, goiaba, arroz, feijão, macarrão, etc.
       
      Na tabela itens eu tenho cadastrado os itens da seguinte maneira:
       
      1, laranja, uva, arroz, feijão;
      2, maçã, macarrão, goiaba, uva;
      3, arroz, feijão, maçã, azeite
       
      Meu problema é o seguinte: 
      Eu escolho um produto da tabela "produtos", por exemplo "uva".  Preciso fazer uma consulta na tabela "itens" para ser listado todos os registros que contenham o produto "uva" e que todos os demais produtos estejam cadastrados na tabela "produtos".
       
      No exemplo acima seria listado apenas dois registros, pois o terceiro registro não contém o produto "uva". 
       
      Alguém pode me ajudar? Pois estou quebrando a cabeça a vários dias e não consigo achar uma solução.
    • Por landerbadi
      Boa tarde pessoal. Estou tentado fazer uma consulta no banco de dados porém estou tendo dificuldades. Tenho uma tabela chamada "itens" com os seguintes campos: id, item, plural, ativo. Nela tem cadastrado vários itens e seu respectivo plural. No campo ativo eu coloco a letra "S" para informar que esta palavra está ativa no sistema. Por exemplo: 1, casa, casas, S 2, mesa, mesas, S 3, cama, camas, S 4, moto, motos, S 5, rádio, rádios O quinto registro "radio" não está ativo no sistema pois não tem um "S" no campo ativo. E outra tabela chamada "variações" com os seguintes campos (id, item1, item2, item3) com os seguintes registros: 1, casa, camas, moto 2, mesas, casas, radio 3, rádio, cama, mesa Eu preciso fazer uma busca na tabela variações da seguinte maneira: Eu escolho um registro na tabela "itens", por exemplo "casa". Preciso fazer com que o php me liste todos os registros da tabela "variações" que contenham a palavra "casa". Porém se tiver algum registro com a palavra "casas" também tem que ser listado. Neste caso ele irá encontrar dois registros. Agora eu preciso que o php verifique os demais itens e faça a listagem apenas dos item que estão ativos (que contenham um "S" no campo ativo. Neste caso ele irá encontrar apenas um registro, pois o segundo registro contém a palavra "rádio". E "rádio" não está ativo na tabela itens. Como faço isso?
×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.