Home » Php » How can I display content from MySQL in form input fields PHP HTML

How can I display content from MySQL in form input fields PHP HTML

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’m working on a Edit button and I’m trying to display userId, id, title, completed(from MySQL) in form input fields, everything works perfectly until $_GET is set. But when is !isset($_GET)of course it gives me error.
This is my PHP code for Edit button and how i connect to database:

<?php
session_start();

$user_id = '';
$id_id = '';
$titel_db = '';
$completed_db = '';

include 'header.php';

class Database
{
    private $db_host;
    private $db_name;
    private $db_username;
    private $db_password;

    public function dbConnection()
    {
        $this->db_host = 'localhost';
        $this->db_name = 'items';
        $this->db_username = 'root';
        $this->db_password = '';
        try {
            $conn = new PDO('mysql:host=' . $this->db_host . ';dbname=' . $this->db_name, $this->db_username, $this->db_password);
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            return $conn;
        } catch (PDOException $e) {
            echo "Connection error " . $e->getMessage();
            exit;
        }
    }
}


if (isset($_POST['save'])) {

    $userId = $_POST['userId'];
    $id = $_POST['id'];
    $title = $_POST['title'];
    $completed = $_POST['completed'];

    $database = new Database;
    $db = $database->dbConnection();
    $sql = "INSERT INTO posts (id, userId, title, completed) VALUES ('$userId', '$id', '$title', '$completed')";
    $stmt = $db->prepare($sql);
    $stmt->execute();

    $_SESSION['message'] = "Record has been saved!";
    $_SESSION['msg_type'] = "success";

    header("location: index.php");
}

if (isset($_GET['delete'])) {

    $id = $_GET['delete'];
    $database = new Database;
    $db = $database->dbConnection();
    $sql = "DELETE FROM posts WHERE id=$id";
    $stmt = $db->prepare($sql);
    $stmt->execute();

    $_SESSION['message'] = "Record has been deleted!";
    $_SESSION['msg_type'] = "danger";

    header("location: index.php");
}

if (isset($_GET['edit'])) {
    $id = $_GET['edit'];

    $database = new Database;
    $db = $database->dbConnection();
    $sql = "SELECT * FROM posts WHERE id = :id";
    $stmt = $db->prepare($sql);
    $stmt->execute([':id' => $id]);
    $item = $stmt->fetch(PDO::FETCH_OBJ);
    if ($item) {
        $user_id = $item->userId;
        $id_id = $item->id;
        $titel_db = $item->title;
        $completed_db = $item->completed;
    }
}

Here is HTML for index page :

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Documents</title>
    <link rel="stylesheet" href="./style.css">
    <script src="https://kit.fontawesome.com/12883fd222.js" crossorigin="anonymous"></script>
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>

<?php
require_once 'process.php';

if (isset($_SESSION['message'])) : ?>

    <div class="alert alert-<?= $_SESSION['msg_type'] ?>">
        <?php echo $_SESSION['message'];
        unset($_SESSION['message']); ?>
    </div>
<?php endif ?>



<body>
    <?php require_once 'process.php'; ?>
    <div class="row justify-content-center">
        <form action="process.php" method="post">
            <div class="form-grup">
                <label for="">User ID :</label>
                <input type="text" class="form-control" name="userId" value="<?php echo $item ? $item->userId : ''; ?>" placeholder="1" required>
            </div>
            <div class="form-grup">
                <label for="">ID :</label>
                <input type="text" class="form-control" name="id" value="<?php echo $item ? $item->id : ''; ?>" placeholder="1" required>
            </div>
            <div class="form-grup">
                <label for="">Title :</label>
                <input type="text" class="form-control" name="title" value="<?php echo $item ? $item->title : ''; ?>" placeholder="Enter title" required>
            </div>
            <div class="form-grup">
                <label for="">Completed :</label>
                <input type="text" class="form-control" name="completed" value="<?php echo $item ? $item->completed : ''; ?>" placeholder="Not/Completed" required>
            </div>
            <div class="form-grup">
                <hr>
                <button type="submit" class="btn btn-primary btn-block" name="save">Save</button>
                <hr>
            </div>
        </form>
    </div>


    <?php
    $database = new Database;
    $db = $database->dbConnection();
    $sql = "SELECT * FROM posts ";
    $result = $db->prepare($sql);
    $result->execute();
    $items = $result->fetchAll();
    ?>

    <div class="container">
        <table class="table table-hover"">
        <thead>
            <tr>
                <th>User ID</th>
                <th>ID</th>
                <th>Title</th>
                <th>Compiled</th>
                <th colspan=" 2">Action</th>
            </tr>
            </thead>
            <?php foreach ($items as $item) : ?>
                <tr>
                    <td><?php echo $item['userId'] ?> </td>
                    <td><?php echo $item['id'] ?> </td>
                    <td><?php echo $item['title'] ?> </td>
                    <td><?php echo $item['completed'] ? 'Compiled' : 'Not Compiled' ?></td>
                    <td><a href="index.php?edit=<?php echo $item['id']; ?>" class="btn btn-info">Edit</a></td>
                    <td><a href="process.php?delete=<?php echo $item['id']; ?>" class="btn btn-danger">Delete</a></td>
                </tr>
            <?php endforeach ?>
    </div>
</body>

</html>

Until $_GET is set, it works. But when I reload my index page it gives me this error *Notice: Trying to get property;**Undefined variable: item*

Errors

Any idea/ suggestion how to fix this ?
Thanks in advance!

How to&Answers:

You are getting the error because you are trying to get the value of variables that are not defined outside of $_GET code block. There are two to resolve this issue.

Solution #1

Define those variables before if (isset($_GET[‘edit’])) block with default value.

$user_id = '';
$id_id = '';
$titel_db = '';
$completed_db = '';
if (isset($_GET['edit'])) {
            $id = $_GET['edit'];

            $database = new Database;
            $db = $database->dbConnection();
            $sql = "SELECT * FROM posts WHERE id = '$id'";
            $stmt = $db->prepare($sql);
            $stmt->execute([':id' => $id]);
            $item = $stmt->fetch(PDO::FETCH_OBJ);

            $user_id = $item->userId;
            $id_id = $item->id;
            $titel_db = $item->title;
            $completed_db = $item->completed;

        }

Solution #2

Check for variable existence in the input element with isset(). Check the below code

<?php require_once 'process.php' ?>
    <div class="row justify-content-center">
        <form action="process.php" method="post">
            <div class="form-grup">
                <label for="">User ID :</label>
                <input type="text" class="form-control" name="userId" value="<?php echo isset($item->userId)? $item->userId : ''; ?>" placeholder="1" required>
            </div>
            <div class="form-grup">
                <label for="">ID :</label>
                <input type="text" class="form-control" name="id" value="<?php echo isset($item->id)? $item->id : ''; ?>" placeholder="1" required>
            </div>
            <div class="form-grup">
                <label for="">Title :</label>
                <input type="text" class="form-control" name="title" value="<?php echo isset($item->title)? $item->title : ''; ?>" placeholder="Enter title" required>
            </div>
            <div class="form-grup">
                <label for="">Completed :</label>
                <input type="text" class="form-control" name="completed" value="<?php echo isset($item->completed)? $item->completed : ''; ?>" placeholder="Not/Completed" required>
            </div>
            <div class="form-grup">
                <hr>
                <button type="submit" class="btn btn-primary btn-block" name="save">Save</button>
                <hr>
            </div>
        </form>
    </div>

Hope this helped you.

Answer:

Adjust here:

$sql = "SELECT * FROM posts WHERE id = '$id'";

to:

$sql = "SELECT * FROM posts WHERE id = :id";

Then, I’d recommend you to check if $item exists before trying to get data from it:

...
$item = $stmt->fetch(PDO::FETCH_OBJ);
if($item) {
    $user_id = $item->userId;
    $id_id = $item->id;
    $titel_db = $item->title;
    $completed_db = $item->completed; 
}

Finally, you should adjust your HTML form because if $item is null, you can’t echo it anywhere:

<?php require_once 'process.php'; ?>
    <div class="row justify-content-center">
        <form action="process.php" method="post">
            <div class="form-grup">
                <label for="">User ID :</label>
                <input type="text" class="form-control" name="userId" value="<?php echo isset($item) ? $item->userId : ''; ?>" placeholder="1" required>
            </div>
            <div class="form-grup">
                <label for="">ID :</label>
                <input type="text" class="form-control" name="id" value="<?php echo isset($item) ? $item->id : ''; ?>" placeholder="1" required>
            </div>
            <div class="form-grup">
                <label for="">Title :</label>
                <input type="text" class="form-control" name="title" value="<?php echo isset($item) ? $item->title : ''; ?>" placeholder="Enter title" required>
            </div>
            <div class="form-grup">
                <label for="">Completed :</label>
                <input type="text" class="form-control" name="completed" value="<?php echo isset($item) ? $item->completed : ''; ?>" placeholder="Not/Completed" required>
            </div>
            <div class="form-grup">
                <hr>
                <button type="submit" class="btn btn-primary btn-block" name="save">Save</button>
                <hr>
            </div>
        </form>
    </div>