Skip to main content

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

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="/" class="logo-nav">Loran</a>
            <ul>
                <li><a href="/About">Over mij</a></li>
                <li class="dropdown">
                    <a href="/Work">Projecten</a>
                    <div class="dropdown-menu-content">
                        <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" class="current">Contact</a></li>
            </ul>
        </nav>
    </header>
    
    <main class="container">
        <div class="contactformulier">
            <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 class="form-container">
                    <label for="name">Uw naam</label>
                    <input type="text" id="name" name="name" value="<?php echo $name; ?>" class="input-text"/>
                    <span class="message error"><?php echo $msgName; ?></span>
                </div>

                <div class="form-container">
                    <label for="message">Uw bericht</label>
                    <textarea name="message" id="message" rows="5" cols="40"><?php echo $message; ?></textarea>
                    <span class="message error"><?php echo $msgMessage; ?></span>
                </div>
                
                <div class="form-container">
                    <fieldset>
                        <legend>Hoe heeft u mij gevonden?</legend>
                        <div class="fieldset-form">
                            <label for="vrienden">Vrienden</label>
                            <input type="checkbox" name="found[]" id="vrienden" value="vrienden">
                        </div>
                        <div class="fieldset-form">
                            <label for="socials">Sociale media</label>
                            <input type="checkbox" name="found[]" id="socials" value="social">
                        </div>
                        <div class="fieldset-form">
                            <label for="google">Google</label>
                            <input type="checkbox" name="found[]" id="google" value="google">
                        </div>
                        <div class="fieldset-form">
                            <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>


source https://stackoverflow.com/questions/70510884/how-do-i-pass-the-values-of-my-checkboxes-with-php-to-mysql-database

Comments

Popular posts from this blog

How to show number of registered users in Laravel based on usertype?

i'm trying to display data from the database in the admin dashboard i used this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count(); echo $users; ?> and i have successfully get the correct data from the database but what if i want to display a specific data for example in this user table there is "usertype" that specify if the user is normal user or admin i want to user the same code above but to display a specific usertype i tried this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count()->WHERE usertype =admin; echo $users; ?> but it didn't work, what am i doing wrong? source https://stackoverflow.com/questions/68199726/how-to-show-number-of-registered-users-in-laravel-based-on-usertype

Why is my reports service not connecting?

I am trying to pull some data from a Postgres database using Node.js and node-postures but I can't figure out why my service isn't connecting. my routes/index.js file: const express = require('express'); const router = express.Router(); const ordersCountController = require('../controllers/ordersCountController'); const ordersController = require('../controllers/ordersController'); const weeklyReportsController = require('../controllers/weeklyReportsController'); router.get('/orders_count', ordersCountController); router.get('/orders', ordersController); router.get('/weekly_reports', weeklyReportsController); module.exports = router; My controllers/weeklyReportsController.js file: const weeklyReportsService = require('../services/weeklyReportsService'); const weeklyReportsController = async (req, res) => { try { const data = await weeklyReportsService; res.json({data}) console...

ValueError: X has 10 features, but LinearRegression is expecting 1 features as input

So, I am trying to predict the model but its throwing error like it has 10 features but it expacts only 1. So I am confused can anyone help me with it? more importantly its not working for me when my friend runs it. It works perfectly fine dose anyone know the reason about it? cv = KFold(n_splits = 10) all_loss = [] for i in range(9): # 1st for loop over polynomial orders poly_order = i X_train = make_polynomial(x, poly_order) loss_at_order = [] # initiate a set to collect loss for CV for train_index, test_index in cv.split(X_train): print('TRAIN:', train_index, 'TEST:', test_index) X_train_cv, X_test_cv = X_train[train_index], X_test[test_index] t_train_cv, t_test_cv = t[train_index], t[test_index] reg.fit(X_train_cv, t_train_cv) loss_at_order.append(np.mean((t_test_cv - reg.predict(X_test_cv))**2)) # collect loss at fold all_loss.append(np.mean(loss_at_order)) # collect loss at order plt.plot(np.log(al...