Allow only queries of numbers in mysql

0

I'd like to know if you can prevent words, characters, and other things from being queried on a site. I'm developing a system for the history of a site, follow the script:

If possible I would also like to know how to give an else in while, pq is returning error.

$id = $_COOKIE["id"];
$novoId = "$cont[id]";

if (!preg_match("/\b{$novoId}\b/", $id)) {
    setcookie("id", $id .= "{$novoId},");
}
$historico = rtrim($id, ',') . '';

$beta = mysql_query("SELECT aid FROM 'lista' WHERE aid IN($historico)");
while (list($aid) = mysql_fetch_array($beta)) {
$devolver .= ' '.$aid.'  ';
}
    
asked by anonymous 18.02.2018 / 23:57

1 answer

0

Yes, it is possible. Just check if it is an integer or value number and if it is not, display an error message.

Using preg_match:

<?php

/* Verifica se a variável contém somente números */
if (preg_match("/^\d+$/", $id)) {
    /* Faz a busca */
}

Using is_numeric:

<?php

/* Verifica se a variável contém um valor número, independente da variável ser do tipo "int" ou "string" */
if (is_numeric($id)) {
    /* Faz a busca */
}

Using is_int or is_integer:

<?php

/* Verifica se a variável é do tipo "inteiro" */
if (is_int($id)) {
    /* Faz a busca */
}

You can also convert to integer.

<?php

$id = "4165";

var_dump( (int)"4165" );       // 4165
var_dump( (int)4165.7 );       // 4165
var_dump( (int)false );        // 0
var_dump( (int)true );         // 1
var_dump( (int)"valdeir" );    // 0

echo PHP_EOL;
echo "----------";
echo PHP_EOL;

var_dump( intval("4165") );     // 4165
var_dump( intval(4165.7) );     // 4165
var_dump( intval(false) );      // 0
var_dump( intval(true) );       // 1
var_dump( intval("valdeir") );  // 0

If you have multiple ID's , you can use the array_map function. Ex:

<?php

$ids = ["4165", 4165.7, false, true, "valdeir"];

$newIds = array_map(function($value) {
    return (int)$value;
}, $ids);


var_dump($newIds);

You can also filter only the numbers values.

<?php

$ids = "4165,4165.7,false,true,valdeir,12";
$ids = explode(",", $ids);

$newIds = array_filter($ids, function($value) {
    /* Retorna apenas os números inteiros */
    return is_numeric($value);
});


var_dump( implode(",", $newIds) );

// Output: 4165,4165,12
    
19.02.2018 / 00:05