1

I'm trying to do a CRUD with Codeigniter 4, it's my first time using this framework. I created the Database in Mysql and I have already done the register and login ( they work at the moment) So on the landing page, I created a button to edit the user data. But it doesn't work.... only shows me the last error which means that the save function isn't working properly. Someone can help me? I'm super lost at this moment!

This is my edit controller

<?php

namespace App\Controllers;

use App\Models\UserModel;
use CodeIgniter\Controller;

class Edit extends BaseController
{
    public function index()
    {
        if (!$this->session->has('user_id')) {
            return redirect()->to('/login');
        }

        $user = session()->get('user_data');

        if ($user === null) {
            return redirect()->to('/landing')->with('error', 'No se pudieron obtener los datos del usuario.');
        }

        return view('edit', ['user' => $user]);
    }

    public function save()
    {
        if (!$this->session->has('user_id')) {
            return redirect()->to('/login');
        }

        if ($this->request->getMethod() === 'post') {
            $userData = [
                'name' => $this->request->getPost('name'),
                'email' => $this->request->getPost('email'),
                // Puedes agregar el campo password si es necesario, pero ten en cuenta que no es seguro almacenar contraseñas en texto plano.
                // 'password' => $this->request->getPost('password'),
            ];

            if (empty($userData['name']) || empty($userData['email'])) {
                return redirect()->to('/edit')->with('error', 'Por favor, complete todos los campos.');
            }

            $userModel = new UserModel();
            $updateStatus = $userModel->update(session()->get('user_id'), $userData);

            echo $userData;

            if ($updateStatus) {
                session()->set('user_data', $userData);
                return redirect()->to('/edit')->with('success', 'Perfil actualizado con éxito');
            } else {
                return redirect()->to('/home')->with('error', 'No se pudo actualizar el perfil.');
            }
        }

        return redirect()->to('/edit')->with('error', 'Método de solicitud no permitido.');
    }
}

This is my view

<!DOCTYPE html>
<html lang="es">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Editar Perfil</title>
    <link href="<?= base_url('node_modules/bootstrap/dist/css/bootstrap.min.css') ?>" rel="stylesheet">
</head>

<body>
    <div class="container mt-5">
        <h1 class="text-center">Editar Perfil</h1>

        <!-- Mensajes de éxito o error -->
        <?php if (session()->getFlashdata('success')) : ?>
            <div class="alert alert-success" role="alert">
                <?= session()->getFlashdata('success') ?>
            </div>
        <?php endif; ?>

        <?php if (session()->getFlashdata('error')) : ?>
            <div class="alert alert-danger" role="alert">
                <?= session()->getFlashdata('error') ?>
            </div>
        <?php endif; ?>

        <?php if (isset($user) && $user !== null) : ?>
            <form action="<?= base_url('edit-users') ?>" method="post">
                <div class="mb-3">
                    <label for="name" class="form-label">Nombre</label>
                    <input type="text" class="form-control" id="name" name="name" value="<?= esc($user['name']) ?>" required>
                </div>
                <div class="mb-3">
                    <label for="email" class="form-label">Correo Electrónico</label>
                    <input type="email" class="form-control" id="email" name="email" value="<?= esc($user['email']) ?>" required>
                </div>
                <!-- Si necesitas manejar contraseñas, añade el campo de contraseña, pero ten en cuenta la seguridad -->
                <!-- <div class="mb-3">
                    <label for="password" class="form-label">Contraseña</label>
                    <input type="password" class="form-control" id="password" name="password">
                </div> -->
                <button type="submit" class="btn btn-primary">Guardar Cambios</button>
            </form>
        <?php else : ?>
            <div class="alert alert-danger" role="alert">
                No se pudieron cargar los datos del usuario.
            </div>
        <?php endif; ?>

        <a href="<?= base_url('landing') ?>" class="btn btn-secondary mt-3">Cancelar</a>
    </div>
    <script src="<?= base_url('node_modules/bootstrap/dist/js/bootstrap.bundle.min.js') ?>"></script>
</body>

</html>

And this is my model that works with the register

<?php

namespace App\Models;

use CodeIgniter\Model;

class UserModel extends Model
{
    protected $table = 'user';
    protected $primaryKey = 'id';
    protected $allowedFields = ['name', 'email', 'password'];


    protected $beforeInsert = ['hashPassword'];
    protected $beforeUpdate = ['hashPassword'];


    protected function hashPassword(array $data)
    {
        if (isset($data['data']['password'])) {
            $data['data']['password'] = password_hash($data['data']['password'], PASSWORD_DEFAULT);
        }
        return $data;
    }

    /**
     * Método para obtener un usuario por su correo electrónico.
     *
     * @param string $email
     * @return array|null
     */


    public function getUserByEmail($email)
    {
        return $this->where('email', $email)->first();
    }

    /**
     * Método para guardar un nuevo usuario en la base de datos.
     *
     * @param array $data
     * @return int|false ID del usuario insertado o false si falla
     */



    public function saveUser($data)
    {
        try {
            return $this->insert($data);
        } catch (\Exception $e) {

            if ($this->db->error()['code'] == 1062) {
                return false;
            } else {
                throw $e;
            }
        }
    }

    public function updateUser($id, $data)
    {
        return $this->where('id', $id)->set($data)->update();
    }
}

And my routes

$routes->get('/', 'Home::index');

$routes->get('/register', 'Register::index');
$routes->post('/register-users', 'Register::save');


$routes->get('/login', 'Login::index');
$routes->post('/login-users', 'Login::process');

$routes->get('/edit', 'Edit::index');
$routes->post('/edit-users', 'Edit::save');

$routes->get('/landing', 'Landing::index');
$routes->post('/logout', 'Landing::logout');

It's difficult to catch the error with tthe console in php

11
  • There is an echo after $updateStatus declaration. Not sure if that would prevent the correct encoding of the redirection Commented Jul 19, 2024 at 22:46
  • 1
    As an aside, if (isset($user) && $user !== null) doesn't make sense if you know what isset() does. Commented Jul 20, 2024 at 1:48
  • 1
    I tried using the echo to see what it returned, but I removed it, and it still doesn't work. And I didn't know what isset(), it's my first time using Codeigniter. I have replaced it to if (isset($user)) : Commented Jul 20, 2024 at 10:43
  • This is the actual error _ci_last_regenerate|i:1721471637;_ci_previous_url|s:61:"localhost/formulario/version2/myproject/index.php/…:{s:2:"id";s:2:"36";s:4:"name";s:6:"Alvaro";s:5:"email";s:16:"[email protected]";s:8:"password";s:60:"$2y$10$w0W8h/olPk8ZH9XKZMA6c.ZV1fnxcwptZIV2/rzzaSV6UeYUe3F.O";s:5:"cover";N;s:4:"role";s:7:"Usuario";}error|s:34:"Método de solicitud no permitido.";__ci_vars|a:1:{s:5:"error";s:3:"old";} I don't know if it is related to CSRF Commented Jul 20, 2024 at 10:43
  • 1
    Take care when you post log information that contains data. Change your gmail password now. And it is not related to CSRF. Read the error message therein. It pays to look closely. Commented Jul 20, 2024 at 16:24

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.