Error in PHP Array to string conversion

0

I'm trying to get an id from a database but the following error has come up: Array to string conversion

My code is as follows:

<?php
require 'funciones.php';
$pwd=md5('pwd');
$respuesta = funciones::login('user', $pwd);
if ($respuesta) 
{
echo "$respuesta[0];";
}
else
{
echo "Ninguna coincidencia con la busqueda...";
}
?>

And the code of the 'login' function is:

    public static function login($user, $pwd)
    {
        $consultar = "SELECT * FROM login WHERE user = '$user' AND pwd = '$pwd'";
        $resultado = Database::getInstance()->getDb()->prepare($consultar);
        $resultado->execute();
        $tabla = $resultado->fetchAll(PDO::FETCH_ASSOC);
        return $tabla;
    }

NOTE: The configuration of the database is fine, because if you get a result, the error is in the line: echo "$ answer [0];";

    
asked by jose marquez 23.02.2018 в 22:04
source

2 answers

2

I think a problem may be that you are concatenating badly, it would be something like this

$consultar = "SELECT * FROM login WHERE user = '".$user."' AND pwd = '".$pwd."'";

That is, before and after the variables, for example: '". $ user."'

    
answered by 23.02.2018 / 22:08
source
0

Since the given answer has not indicated a serious vulnerability in the code, I allow myself to provide a response that would not only solve the current error, but also shield the code against the injection of malicious code.

It would be a question of using queries prepared in the following way:

   public static function login($user, $pwd)
    {
        $consultar = "SELECT * FROM login WHERE user = ? AND pwd = ?";
        $resultado = Database::getInstance()->getDb()->prepare($consultar);
        $arrParams=array($user,$pwd);
        $resultado->execute($arrParams);
        $tabla = $resultado->fetchAll(PDO::FETCH_ASSOC);
        return $tabla;
    }

As you can see, shielding the code against SQL Injection is very easy in PDO:

  • You write the SQL statement changing the variables by placeholders ( ? ). Name markers could also be used. This is the core of the Injection, since a malicious user could modify those values by changing them for malicious injectable code. By passing them in the query and executing it, you could be executing manipulated code that could be very very harmful. That's why you should not never send queries of this type: SELECT * FROM login WHERE user = '$user' AND pwd = '$pwd'
  • You create an array ( $arrParams ) with the values that come from external sources.
  • You pass that array with the values through the execute method.
  • With those three simple steps, you are shielding your code against attack by intruders.

    For more details you can consult these questions and their answers:

    I hope it's useful.

        
    answered by 24.02.2018 в 01:44