I cannot concatenate variable in a query

Asked

Viewed 1,308 times

3

I have a URL and in it a code that will vary all the time (Ex: usuario/perfil/39).

I used the following code to get this URL value:

$valor_id =  $_SERVER['REQUEST_URI'];
$cod =  explode("/",$valor_id);
$codigo = $cod[4];

So I need to use this code in a SELECT. I did so:

$sql = "SELECT tipo FROM users WHERE ID = " . $codigo;

And I made the following mistake:

Fatal error: Error executing query: SELECT type FROM users WHERE ID = - You have an error in your SQL syntax; check the manual that Corresponds to your Mysql server version for the right syntax to use near '' at line 1 in C: xampp htdocs festas Registry mysqldb.class.php on line 243

When I do that:

$sql ="SELECT tipo FROM users WHERE ID = 36";

It works right, so I believe the problem lies in concatenating the variable in the query. Note: in BD, the type field is integer.

Part of the code that says the error occurs:

public function executeQuery( $queryStr )
{
    if( !$result = $this->connections[$this->activeConnection]->query( $queryStr ) )
    {
        trigger_error('Error executing query: ' . $queryStr .' - '.$this->connections[$this->activeConnection]->error, E_USER_ERROR); //LINHA 243
    }
    else
    {
        $this->last = $result;
    }

}
  • 2

    Why did you use 4? You really want the 5th item separated by the bars? [0]/[1]usuario/[2]perfil/[3]39

4 answers

5

Probably your code just needs this setting:

$codigo = $cod[3];


Reason: if you have a URL in the format

http://exemplo.com/usuario/perfil/39

the variable $_SERVER['REQUEST_URI']; will contain /usuario/perfil/39, therefore, after the explode you will have the following structure:

0 => ''          (valor antes da 1a barra)
1 => 'usuario'   (valor entre a 1a barra e a 2a)
2 => 'perfil'    (valor entre a 2a barra e a 3a)
3 => '39'        (valor após a 3a barra)
  • A good one to avoid 0 => '' would use a trim

  • @Papacharlie in this case would be one too many operation, no benefit, no?

  • I use it precisely to avoid the confusion of having an empty index. In my case it’s more because it’s autonomous - my router takes care of it, so I clean the zero index.

  • In that case the trim if the url is /usuario/perfil/39

  • The cat jump to know the size of the resulting array is to count the number of occurrences of the explode in the string plus 1. Example: explode('/', '/usuario/perfil/39/url/muito/grande//com/erros/') - 10 / + 1. Array with 11 positions

3

Checks whether the value of $Cod[4] is really the value you need. But if the ID is the last value of the URL, do it this way:

$valor_id =  $_SERVER['REQUEST_URI'];
$cod =  explode("/",$valor_id);
$codigo = array_pop($cod);

3

This url certainly uses Apache’s Rewrite engine, so it’s easier and more reliable to edit htaccess and do things like this:

RewriteRule ^([a-zA-Z]+)/([a-zA-Z]+)/([0-9]+)$ page.php?usuario=$1&perfil=$2&id=$3

Then in the file php just get the $_GET['id']. There will be no mistake.

If you do not have access to htaccess and know that id is always the last element of the url

$valor_id =  $_SERVER['REQUEST_URI'];
$cod =  explode("/",$valor_id);

$ultimo = count($cod) - 1;

$codigo = $cod[$ultimo];

$limit = array("options" => array("min_range" => 1));

$id = (!empty($codigo)) ? filter_var($codigo, FILTER_VALIDATE_INT, $limit) : FALSE

if($id)
{
   //executa pesquisa
}
else
{
   echo "ERRO";
}
  • Your rule is wrong. Creating segments will not work with ((.*)+).

  • @Papacharlie, I could explain better why it’s wrong. So it gets a little shallow.

  • To segment in HTACCESS and create multiple formats, it’s best to create a set ([a-zA-Z]+).... When you use ((.*)+) does not allow to divide, because it will consider the / as a character. You will have the GET["usuario"] = usuario/perfil/39.

  • 1

    You’re right @Papacharlie. Correction made. Thanks.

3


You can check the output of your array this way:

var_dump($cod);

This should give you a clear notion of what is being returned by the URL. Since the URL can be changed by the user I recommend to always test if the value actually exists.

$valor_id =  $_SERVER['REQUEST_URI'];
$cod =  explode("/",$valor_id);
$codigo = '-1';
if (count($cod) >= 3) {
  $codigo = end($cod); // Pega o ultimo valor do array
}

I also recommend to clean the variable before using it in the query:

$codigo = is_numeric($codigo) ? intval($codigo) : -1;

Finally, try the use of preparedStatements. In addition to making life much easier, they prevent a number of problems, such as SQL-Injection;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.