Problems when performing INSERT (PDO)

Asked

Viewed 37 times

0

Good afternoon!

I’m encountering problems to perform the following insert:

function cadastro($usuario,$senha,$status){
    $pdo = con();

    $usuario = "Matheus";
    $senha = "123";
    $status = 3;

    $inf = [
        'usuario' => $usuario,
        'senha' => $senha,
        'status' => $status,
    ];

    $sql = "SELECT id FROM usuarios WHERE usuario = :usuario";
    $stmt= $pdo->prepare($sql);
    $stmt->execute($inf);

Error message:

Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens

Thanks in advance!

2 answers

1

Dude, the error most likely is in your query. You are trying to replace the :usuario by an array that should actually be a string.

Example:

$inf = [
    'usuario' => 'Matheus'
];

the prepare will replace the :usuario by 'Matheus'. The way you are doing, he tries to replace :usuario by an array.

I believe this way it should work:

function cadastro($usuario, $senha, $status)
{
    $pdo = con();
    $inf = [
        'usuario' => 'Matheus',
        'senha' => '123',
        'status' => 3
    ];
    $sql = "SELECT id FROM usuarios WHERE usuario = :usuario AND senha = :senha AND status = :status";
    $stmt= $pdo->prepare($sql);
    $stmt->execute($inf);
}

1

Matheus, as I put in the comment, if your doubt is registration, below a suggestion to change your function.

function cadastro($usuario, $senha, $status) {
    $pdo = con();

    $usuario = "Matheus";
    $senha = "123";
    $status = 3;

    $inf = [
        'usuario' => $usuario,
        'senha' => $senha,
        'status' => $status,
    ];

    $sql = "INSERT INTO usuarios (usuario, senha, status) VALUES(:usuario,:senha,:status)";
    $stmt = $pdo->prepare($sql);        
    $stmt->execute($inf);
} 
  • Thanks for the answer, actually my mistake was not having put the whole function, there is a part of the function that makes exactly this INSERT that you commented, but before doing this INSERT I need to do this SELECT only with the user name to know if there is already an equal user.

Browser other questions tagged

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