2
respostas

[Dúvida] Erro ao listar alunos Argument #2 ($name) must be of type string / Null sendo gravado junto com os dados

Olá, antes de mais nada boa noite, me encontro travado tentando solucionar este problema, que sempre ao inserir um novo aluno, o banco recebe ou registra um novo ID como null (print do banco no final do post), segue o código :

PHP Fatal error: Uncaught TypeError: Alura\Pdo\Domain\Model\Student::__construct(): Argument #2 ($name) must be of type string, null given, called in *\lista-alunos.php on line 15 and defined in *\src\Domain\Model\Student.php:11 Stack trace:

#0 ***\lista-alunos.php(15): Alura\Pdo\Domain\Model\Student->__construct()

#1 {main} thrown in ***\src\Domain\Model\Student.php on line 11

-------------CONEXÃO BANCO ------------

<?php

$databasePath = __DIR__ . '/banco.sqlite';
$pdo = new PDO('sqlite:' . $databasePath);

echo 'Conectei';

$pdo->exec('CREATE TABLE students (id INTEGER PRIMARY KEY, name TEXT, birth_date TEXT);');

------------- CLASSE -------------

<?php

namespace Alura\Pdo\Domain\Model;

class Student
{
    private ?int $id;
    private string $name;
    private \DateTimeInterface $birthDate;

    public function __construct(?int $id, string $name, \DateTimeInterface $birthDate)
    {
        $this->id = $id;
        $this->name = $name;
        $this->birthDate = $birthDate;
    }

    public function id(): ?int
    {
        return $this->id;
    }

    public function name(): string
    {
        return $this->name;
    }

    public function birthDate(): \DateTimeInterface
    {
        return $this->birthDate;
    }

    public function age(): int
    {
        return $this->birthDate
            ->diff(new \DateTimeImmutable())
            ->y;
    }
}

---------- INSERE ALUNO ---------------------

<?php

use Alura\Pdo\Domain\Model\Student;

require 'vendor/autoload.php';

$databasePath = __DIR__ . '/banco.sqlite';
$pdo = new PDO('sqlite:' . $databasePath);


$student = new Student(
    null,
    'Jorge Miguel',
    new \DateTimeImmutable('1998-10-14')
);

$sqlInsert = "INSERT INTO students (name, birth_date) VALUES (:name, :birth_date);";

$statement = $pdo->prepare($sqlInsert);
$statement->bindValue(1, $student->name());
$statement->bindValue(2, $student->birthDate()->format('Y-m-d'));

if($statement->execute()){
    echo "Aluno incluído";
}

var_dump($pdo->exec($sqlInsert));

--------------------LISTA ALUNOS --------------------

<?php

use Alura\Pdo\Domain\Model\Student;

require_once 'vendor/autoload.php';

$databasePath = __DIR__ . '/banco.sqlite';
$pdo = new PDO('sqlite:' . $databasePath);

$statement = $pdo->query('SELECT * FROM students;');
$studentDataList = $statement->fetchAll(PDO::FETCH_ASSOC);
$studentList = [];

foreach ($studentDataList as $studentData) {
    $studentList[] = new Student(
        $studentData['id'],
        $studentData['name'],
        new \DateTimeImmutable($studentData['birth_date'])
    );
}

var_dump($statement);

Insira aqui a descrição dessa imagem para ajudar na acessibilidade

2 respostas

consigo excluir os Ids com registros nulos com a funcionalidade de remover aluno:

<?php


require_once 'vendor/autoload.php';

$databasePath = __DIR__ . '/banco.sqlite';
$pdo = new PDO('sqlite:' . $databasePath);

$preparedStatement = $pdo->prepare('DELETE FROM students WHERE id = ?;');
$preparedStatement->bindValue(1, 2, PDO::PARAM_INT);

var_dump($preparedStatement->execute());

Olá, Jaisson. Tudo bem?

No arquivo inserir-aluno.php no final você colocou assim:

var_dump($pdo->exec($sqlInsert));

Você pode remover esta linha, pois ela está executando uma outra instrução, que é esta:

$sqlInsert = "INSERT INTO students (name, birth_date) VALUES (:name, :birth_date);";

Espero ter ajudado, bons estudos :)

Caso este post tenha lhe ajudado, por favor, marcar como solucionado ✓