Home > database >  How do I pass the values of my checkboxes with PHP to mySQL database?
How do I pass the values of my checkboxes with PHP to mySQL database?

Time:12-29

Now the value in my database is just "Array". Because, well it is an array. It can see whether I checked at least one thing, or no things at all. If I don't check any checkboxes it returns nothing, if I check at least one thing it returns "Array".

I haven't worked with PHP before, and we didn't get any classes about this, but after a few days of trying I couldn't figure it out. enter image description here

<?php

// Show all errors (for educational purposes)
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 0);

// Constanten (connectie-instellingen databank)
define('DB_HOST', '');
define('DB_USER', '');
define('DB_PASS', '');
define('DB_NAME', '');

date_default_timezone_set('Europe/Brussels');

// Verbinding maken met de databank
try {
    $db = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8mb4', DB_USER, DB_PASS);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo 'Verbindingsfout: ' . $e->getMessage();
    exit;
}

$name = isset($_POST['name']) ? (string)$_POST['name'] : '';
$message = isset($_POST['message']) ? (string)$_POST['message'] : '';
$found = isset($_POST['found']) ? (string)$_POST['found'] : '';
$msgName = '';
$msgMessage = '';

// form is sent: perform formchecking!
if (isset($_POST['btnSubmit'])) {

    $allOk = true;

    // name not empty
    if (trim($name) === '') {
        $msgName = 'Gelieve een naam in te voeren';
        $allOk = false;
    }

    if (trim($message) === '') {
        $msgMessage = 'Gelieve een boodschap in te voeren';
        $allOk = false;
    }

    // end of form check. If $allOk still is true, then the form was sent in correctly
    if ($allOk) {
        // build & execute prepared statement
        $stmt = $db->prepare('INSERT INTO messages (sender, message, found, added_on) VALUES (?, ?, ?, ?)');
        $stmt->execute(array($name, $message, $found, (new DateTime())->format('Y-m-d H:i:s')));

        // the query succeeded, redirect to this very same page
        if ($db->lastInsertId() !== 0) {
            header('Location: formchecking_thanks.php?name=' . urlencode($name));
            exit();
        } // the query failed
        else {
            echo 'Databankfout.';
            exit;
        }

    }

}

?><!DOCTYPE html>
<html lang="nl">
<head>
    <title>Testform</title>
    <meta charset="UTF-8"/>
    <link href="https://unpkg.com/@csstools/normalize.css" rel="stylesheet"/>
    <link rel="stylesheet" href="./css/contact.css">
    <link rel="stylesheet" href="/css-algemeen/stylesheet.css">
</head>
<body>
    <header>
        <nav>
            <a href="/" >Loran</a>
            <ul>
                <li><a href="/About">Over mij</a></li>
                <li >
                    <a href="/Work">Projecten</a>
                    <div >
                        <a href="/Work/Project1/">Project 1</a>
                        <a href="/Work/Project2/">Project 2</a>
                        <a href="/Work/Project3/">Project 3</a>
                        <a href="/Work/Project4/">Project 4</a>
                        <a href="/Work/Project5/">Project 5</a>
                        <a href="/Work/Project6">Project 6</a>
                        <a href="/Work/Project7/">Project 7</a>
                        <a href="/Work/Project8/">Project 8</a>
                    </div>
                </li>
                <li><a href="/Blog">Blog</a></li>
                <li><a href="/Contact" >Contact</a></li>
            </ul>
        </nav>
    </header>
    
    <main >
        <div >
            <h1>Contacteer mij</h1>
            <p>Heb je een vraag, of wil je samenwerken? Contacteer mij!</p>
            <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
                <div >
                    <label for="name">Uw naam</label>
                    <input type="text" id="name" name="name" value="<?php echo $name; ?>" />
                    <span ><?php echo $msgName; ?></span>
                </div>

                <div >
                    <label for="message">Uw bericht</label>
                    <textarea name="message" id="message" rows="5" cols="40"><?php echo $message; ?></textarea>
                    <span ><?php echo $msgMessage; ?></span>
                </div>
                
                <div >
                    <fieldset>
                        <legend>Hoe heeft u mij gevonden?</legend>
                        <div >
                            <label for="vrienden">Vrienden</label>
                            <input type="checkbox" name="found[]" id="vrienden" value="vrienden">
                        </div>
                        <div >
                            <label for="socials">Sociale media</label>
                            <input type="checkbox" name="found[]" id="socials" value="social">
                        </div>
                        <div >
                            <label for="google">Google</label>
                            <input type="checkbox" name="found[]" id="google" value="google">
                        </div>
                        <div >
                            <label for="andere">Andere</label>
                            <input type="checkbox" name="found[]" id="andere" value="andere">
                        </div>
                    </fieldset>
                </div>
                <input type="submit" id="btnSubmit" name="btnSubmit" value="Verstuur"/>
            </form>
        </div>
    </main>
    
    <footer>
        <p>Footer &copy; 2021 Loran Maes - <a href="https://www.linkedin.com/in/loran-maes-524a05160/" target="blank">LinkedIn</a> - <a
                href="https://www.instagram.com/loran_maes/" target="blank">Instagram</a>  - copyright - Dendermondesteenweg 809 9070 Destelbergen</p>
    </footer>
</body>
</html>

CodePudding user response:

Assuming found is supposed to contain a comma-delimited list of the checkbox values, use implode() to create that from the array.

$found = isset($_POST['found']) ? implode(',', $_POST['found']) : '';

However, this is generally poor design. See Is storing a delimited list in a database column really that bad?

  • Related