Column count doesn't match value count at row 1? [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
/*formularen er ikke blevet postet endnu, vis den.
bemærke, at action = "" vil medføre, at formularen til at sende til den samme side det er på */
echo '<form method="post" action="">
<table border="0" >
<tr><td> Dit navn: </td><td> <input type="text" class="ed" name="bruger_navn" />
<tr><td> Din adresse: </td><td> <input type="text" class="ed" name="bruger_adresse" />
<tr><td> Din email: </td><td> <input type="email" class="ed" name="bruger_email" />
<tr><td> Vælg password: </td><td> <input type="password" class="ed" name="bruger_kode"/>
<tr><td> Bekræft password: </td><td> <input type="password" class="ed" name="bruger_kode_check"/>
<br> <tr><td>
<div class="check">
<label for="checkbox">Jeg har læst og er acceptere centrets regler</label>
<input type="checkbox" class="checkbox" name="check" required />
<input type="submit" value="Send" id="button1" />
</form></td><td>';
}
else
{
/* Formularen er blevet postet. Dataen bliver behandlet i tre trin:
1. Tjek dataen
2. Lad brugeren udfylde de tomme felter, hvis det er nødvendigt
3. Gem dataen
*/
$errors = array(); /* erklære arrayet til senere brug */
if(isset($_POST['bruger_navn']))
{
//Brugernavnet findes ctype_alnum betyder at den skal indholder kun tal og bogstaver "Ingen Mellemrum".
if(!ctype_alnum($_POST['bruger_navn']))
{
$errors[] = 'Brugernavnet kan kun indeholde bogstaver og tal.';
}
if(strlen($_POST['bruger_navn']) > 30)
{
$errors[] = 'Brugernavnet må ikke være længere end 30 tegn.';
}
}
else
{
$errors[] = 'Du skal udfylde et brugernavn.';
}
if(isset($_POST['bruger_kode']))
{
if($_POST['bruger_kode'] != $_POST['bruger_kode_check'])
{
$errors[] = 'Adgangskoden matcher ikke.';
}
}
else
{
$errors[] = 'Du skal udfylde en adgangskode.';
}
if(!empty($errors)) /*kontrollere, om der er et tomt array, hvis der er fejl, hvis der er, er de i dette array*/
{
echo 'Du mangler at udfylde nogle felter.<br /><br />';
echo '<ul>';
foreach($errors as $key => $value) /* går gennem arrayet, så alle fejl bliver vist */
{
echo '<li>' . $value . '</li>'; /* Her laves en liste med fejlene */
}
echo '</ul>';
}
else
{
// formularen er nu postet uden fejl, så det bliver gemt
// bemærk brug af mysql_real_escape_string, holder alt sikkert!
// SHA1 funktionen, hasher adgangskoden
$sql = "INSERT INTO
bruger(bruger_navn, bruger_adresse, bruger_email, bruger_kode, fk_roller_id)
VALUES('" . mysql_real_escape_string($_POST['bruger_navn']) . "',
'" . mysql_real_escape_string($_POST['bruger_email']) . "',
'" . mysql_real_escape_string($_POST['bruger_adresse']) . "',
'" . sha1($_POST['bruger_kode']) . "',
NOW(),
1)";

you have a 5 fields in your query and you insert 6 values into it.
INSERT INTO
bruger(bruger_navn, bruger_adresse, bruger_email, bruger_kode, fk_roller_id)
VALUES('" . mysql_real_escape_string($_POST['bruger_navn']) . "',
'" . mysql_real_escape_string($_POST['bruger_adresse']) . "',
'" . mysql_real_escape_string($_POST['bruger_email']) . "',
'" . sha1($_POST['bruger_kode']) . "',
1)
so remove unused value.(according to me you have a no field of time so i remove now() from your query) or if you have a time related field into database then add into your query.
note: i adjust the order of your values.

Related

inserting multiple checkboxes into MySQL (PDO)

I'm currently working on a school project and i'm trying to upload a "post" of a recipe. this includes image, title, instructions,ingredients and also 1 or multiple categories.
all of them insert fine and well. the only issue is with the categories. It only inserts 1 category even if I select multiple checkboxes.
It's supossed to insert every checkbox into a new row in the database.
My DAO
public function insertCategory($data, $title) {
if (empty($errors)) {
$sql = "INSERT INTO `recipes_categories` (`category_id`, `recipe_id`) VALUES(:category_id,:recipe_id);";
$stmt = $this->pdo->prepare($sql);
$stmt->bindValue(':category_id', $data['category_id']);
$stmt->bindValue(':recipe_id', $title['id']);
if ($stmt->execute()) {
return $this->selectcategoryById($this->pdo->lastInsertId());
}
}
return false;
}
My Controller (relevant parts)
public function upload() {
// variabele om foutmelding bij te houden
$error = '';
// controleer of er iets in de $_POST zit
if(!empty($_POST['action'])){
// controleer of het wel om het juiste formulier gaat
if($_POST['action'] == 'add-image') {
// controleren of er een bestand werd geselecteerd
if (empty($_FILES['image']) || !empty($_FILES['image']['error'])) {
$error = 'Gelieve een bestand te selecteren';
}
if(empty($error)){
// controleer of het een afbeelding is van het type jpg, png of gif
$whitelist_type = array('image/jpeg', 'image/png','image/gif');
if(!in_array($_FILES['image']['type'], $whitelist_type)){
$error = 'Gelieve een jpeg, png of gif te selecteren';
}
}
if(empty($error)){
// controleer de afmetingen van het bestand: pas deze gerust aan voor je eigen project
// width: 270
// height: 480
$size = getimagesize($_FILES['image']['tmp_name']);
if ($size[0] < 100 || $size[1] < 100) {
$error = 'De afbeelding moet minimum 100x100 pixels groot zijn';
}
}
if(empty($error)){
// map met een random naam aanmaken voor de upload: redelijk zeker dat er geen conflict is met andere uploads
$projectFolder = realpath(__DIR__);
$targetFolder = $projectFolder . '/../assets/ads';
$targetFolder = tempnam($targetFolder, '');
unlink($targetFolder);
mkdir($targetFolder, 0777, true);
$targetFileName = $targetFolder . '/' . $_FILES['image']['name'];
// via de functie _resizeAndCrop() de afbeelding croppen en resizen tot de gevraagde afmeting
// pas gerust aan in je eigen project
$this->_resizeAndCrop($_FILES['image']['tmp_name'], $targetFileName, 100, 100);
$relativeFileName = substr($targetFileName, 1 + strlen($projectFolder));
$data = array(
'image' => $relativeFileName,
'title' => $_POST['title'],
'instructions' => $_POST['stappenplan'],
'description' => $_POST['ingredienten'],
'category_id' => $_POST['category'],
);
// TODO: schrijf de afbeelding weg naar de database op basis van de array $data
if (!empty($_POST['action'])) {
if ($_POST['action'] == 'add-image') {
// array met data invullen
$data = array(
'path' => '/' . $relativeFileName,
'title' => $_POST['title'],
'instructions' => $_POST['stappenplan'],
'description' => $_POST['ingredienten'],
'category_id' => $_POST['category'],
);
// aanspreken van de DAO
$insertImage = $this->uploadDAO->insertImage($data);
$title = $this->uploadDAO->ImageInsterId($data);
$this->set('title', $title);
$ingredientsArray = explode( ',', $data['description'] );
foreach($ingredientsArray as $ingredient){
$insertIngredient = $this->uploadDAO->insertIngredients($ingredient , $title);
}
$insertCategory = $this->uploadDAO->insertCategory($data, $title);
// TODO 2: zorg dat de variabele $error getoond wordt indien er iets fout gegaan is
if (!$insertImage) {
$errors = $this->uploadDAO->validate($data);
$this->set('errors', $errors);
} else {
$_SESSION['info'] = 'Thank you for adding a Post!';
header('Location: index.php?page=detail&id='. $title['id']);
exit();
}
}
}
}
}
}
There is some code here for the image upload too, but it isn't relevant since that is working.
My HTML
<span class="error"><?php if(!empty($error)){ echo $error;} ?></span>
<section class="upload_box">
<h1 class="hidden">upload-form</h1>
<form method="post" action="index.php?page=upload" enctype="multipart/form-data" class="form__box">
<input type="hidden" name="action" value="add-image" />
<div class="form-field">
<label class="upload__title form_container">Kies een afbeelding
<span class="error"><?php if(!empty($errors['title'])){ echo $errors['title'];}?></span>
<input type="file" name="image" accept="image/png, image/jpeg, image/gif" required class="upload__button filter__submit input">
</label>
</div>
<div class="form-field">
<label class="upload__title form_container">Titel
<span class="error"><?php
if(!empty($errors['title'])){
echo $errors['title'];} ?></span>
<input type="text" name="title" required class="upload__title form_field input">
</label>
</div>
<div class="form-field">
<label class="upload__title form_container">Stappenplan
<span class="error"><?php if(!empty($errors['instructions'])){ echo $errors['instructions'];} ?></span>
<textarea name="stappenplan" id="stappenplan" cols="50" rows="5" required class="form_field upload__title input"></textarea>
</label>
</div>
<div class="form-field">
<label class="upload__title form_container">Ingredienten
<span class="error"><?php if(!empty($errors['description'])){ echo $errors['description '];} ?></span>
<input type="text" TextMode="MultiLine" name="ingredienten" maxlength="255" required class="form_field upload__title input" id="ingredienten">
</label>
</div>
<div class="category_container">
<label class="category_label filter__button">
<input class="category_input" type="checkbox" id="pasta" name="category" value="1">
Pasta</label>
<label class="category_label filter__button">
<input class="category_input" type="checkbox" id="veggie" name="category" value="2">
Veggie</label>
<label class="category_label filter__button">
<input class="category_input" type="checkbox" id="vlees" name="category" value="3">
Vlees</label>
</div>
<div class="form-field">
<input type="submit" value="uploaden" class="filter__button filter__submit">
<input type="reset" value="wissen" class="filter__button filter__submit">
</div>
</form>
</section>
<script src="js/validate.js"></script>
What I do know:
I know the recipe_id isn't an issue. I use the same for other SQL inserts.
I don't want an explode() or implode() as they don't work in this case.
Tried several foreaches but haven't gotten it to work, just yet.
it's also nothing to do with brackets or comma's or whatever.
It's just the insert only doing it once while I have 2 checkbox values. and I don't know how to make it loop over both or all 3 when all 3 are selected
<div class="category_container">
<label class="category_label filter__button">
<input class="category_input" type="checkbox" id="pasta" name="category[]" value="1">
Pasta</label>
<label class="category_label filter__button">
<input class="category_input" type="checkbox" id="veggie" name="category[]" value="2">
Veggie</label>
<label class="category_label filter__button">
<input class="category_input" type="checkbox" id="vlees" name="category[]" value="3">
Vlees</label>
</div>
You need to use category[], rather than just category to send multiple values in form submit.
Now, you can fetch the values of categories
$categories = (is_array($_POST['category'])) ? $_POST['category'] : [];
I have assigned categories a default value if there is no checkbox selected.
Then use implode function of php:
$categories_string = implode(',', $categories);
or use a foreach loop based on how you want to save in your database table:
foreach ($category as $category)
{
//use each category
}

Update mysqli database by filling in only one of many input fields

I am making a very simple movie database, with the possibility to update the movies that are in it. All you have to do is fill in the fields underneath the table. However, when you fill in the id and only one other field, like film_id, the description etc. are erased from the table. How do i make sure that it's possible to change only one thing?
The code for the page:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<?php
session_start(); //Start sessie.
function is_logged() {
if (isset($_SESSION['username'])) return true;
return false; //De gebruikersnaam wordt gecontroleerd
}
if(!is_logged()){
header("Location: sign-in.php"); //Als de gebruiker naar overzichtlogin.php
gaat, zonder dat hij of zij is ingelogd, worden ze doorgestuurd naar de
login pagina.
}
require_once('db_const.php'); //De gegevens voor het maken van de verbinding
met de database staan in dit bestand gedeclareerd.
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if (!$mysqli){
die("Connection failed: ".mysqli_connect_error()); //Als de verbinding niet
lukt zal deze niet werken.
}
?>
<?php $current = 'secured'; ?> <!-- Om aan te geven dat men zich op de
beveiligde overzichtspagina bevindt, wordt gebruik gemaakt van deze
variabele. Current krijgt nu de waarde 'secured', waardoor de button waar
'secured' staat een kleur krijgt. -->
<div class="header">
<?php
if(isset($_SESSION['username'])){
require_once("headersecured.php"); //Indien de gebruiker ingelogd is, wordt
'headersecured.php' gebruikt als header.
}else{
require_once("header.php"); //Indien de gebruiker niet is ingelogd, wordt
header.php gebruikt als header.
}
?>
</div>
<h1>Filmoverzicht</h1>
<?php
$sql = "SELECT film_id, title, description, release_year, rating FROM
films"; //De gewenste gegevens uit de database worden geselecteerd.
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
echo "<table style='border: solid 1px grey; margin-left: auto; margin-right:
auto; margin-top:50px;'><tr><th>ID</th> <th>Titel</th> <th>Beschrijving</th>
<th>Jaar</th> <th>Rating</th> <th> </th></tr>";
while($row = $result->fetch_assoc()) {
echo "<tr><td>" .$row["film_id"] . "<td>" .$row["title"] . "<td>" .
$row["description"] . "<td>" . $row["release_year"]. "<td> " .
$row["rating"]. "<td> " . '<td><a class="alert" href="deletemovie.php?
id='.$row['film_id'].'" >
</i>'?> VERWIJDER <?php '</a></td>';
} //De beschikbare gegevens worden weergegeven.
echo "</table>";
} else {
echo "0 results";
}
?>
<br><br>
<form method="post" action="<?php $_SERVER["PHP_SELF"]; ?>"> <!--De
bewerkfunctie wordt op dezelfde pagina uitgevoerd.-->
<h2>Films bewerken</h2>
<input name="film_id" required="required" placeholder="ID">
<input name="title" placeholder="Titel film">
<textarea id="textarea" name="description" cols="20" rows="5"
placeholder="Beschrijving"></textarea>
<input name="release_year" placeholder="Uitkomstjaar">
<input name="rating" placeholder="Beoordeling">
<input id="submit" name="submit" type="submit" value="Wijzigen"> <!-- In
deze
invulvelden kunnen nieuwe gegevens worden ingevoerd, zodat de films worden
aangepast. -->
<?php
if (isset($_POST['submit'])) {
$film = $_POST["film_id"]; //Slaat de gegevens voor het ingevoerde ID op in
een
variabele.
$title = $_POST["title"]; //Slaat de gegevens voor de ingevoerde titel op in
een
variabele.
$description = $_POST["description"]; //Slaat de gegevens voor de ingevoerde
beschrijving op in een variabele.
$year = $_POST["release_year"]; //Slaat de gegevens voor het ingevoerde jaar
op
in een variabele.
$rating = $_POST["rating"]; //Slaat de gegevens voor de ingevoerde rating op
in een variabele.
$sql = "UPDATE films SET film_id = '$film', title = '$title', description =
'$description', release_year = '$year', rating = '$rating' WHERE film_id =
$film"; //De tabel 'films' in MySQL wordt geselecteerd, de gegevens die in
de
variabelen zijn opgeslagen worden gewijzigd in de database.
if (mysqli_query($mysqli, $sql)) { // Voert de actie uit
echo "<br>"; // Wit ruimte
echo "<br>"; // Wit ruimte
echo "<br>"; // Wit ruimte
echo "Succesvol aangepast!"; // Geeft aan dat het aangepast is
echo "<br>"; // Wit ruimte
echo "<a href='overzichtspagina.php'>Terug naar de vorige pagina.</a>"; //
een link waar de gebruiker terug kan gaan naar de vorige pagina
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($mysqli); // geef fout
melding aan de gebruiker als het mis gaat
}
}
?>
</form>
<?php
$mysqli->close(); //Verbinding wordt verbroken.
?>
<div class="footer">
<?php include 'footer.php';?> <!-- De footer wordt opgehaald. -->
</div>
</body>
</html>
The problem is when the $_POST["description"] is not defined the value of $description is taken as NUll. In order to avoid this the Update query has to be constructed dynamicaly.
$sql = "UPDATE films SET film_id = '$film', title = '$title'";
if(isset($_POST["description"])) {
$description = $_POST["description"];
$sql .= ", description = $description"
}
$sql .= ", release_year = '$year', rating = '$rating' WHERE film_id = $film";
In this case when the $_POST["description"] is not set the query becomes "UPDATE films SET film_id = '$film', title = '$title', release_year = '$year', rating = '$rating' WHERE film_id = $film";
or else the query becomes "UPDATE films SET film_id = '$film', title = '$title', description = $description, release_year = '$year', rating = '$rating' WHERE film_id = $film";
You have to check on multiple values for validation, because you want that at least one field (other than film ID) is completed. If none provided, than notify the user. This validation should be made on client-side (with js, jquery, validation plugins, etc).
Then, you must dynamically build your sql statement. Use sprintf()
function for such "complex" constructs. It's very elegant. In it, the %s parts are placeholders for the variables.
Please notice the UPDATE statement: you don't want to update the
film_id field! You must use it ONLY to select the one record which
you want to update (e.g. just in WHERE clause). If you want to
change film_id, you must reinsert a record with the new id.
You are missing the <body> tag.
I was bringing last php code UNDER the </form> tag.
As a general rule: separate display logic from server processing.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>My films</title>
</head>
<body>
<?php
$mysqli = new mysqli('localhost', 'root', 'root', 'tests');
if (!$mysqli) {
die("Connection failed: " . mysqli_connect_error());
}
?>
<!-- ... -->
<form method="post" action="<?php $_SERVER["PHP_SELF"]; ?>">
<h2>Films bewerken</h2>
<input name="film_id" required="required" placeholder="ID">
<input name="title" placeholder="Titel film">
<textarea id="textarea" name="description" cols="20" rows="5" placeholder="Beschrijving"></textarea>
<input name="release_year" placeholder="Uitkomstjaar">
<input name="rating" placeholder="Beoordeling">
<input id="submit" name="submit" type="submit" value="Wijzigen">
</form>
<?php
if (isset($_POST['submit'])) {
$film = $_POST["film_id"];
$title = $_POST["title"];
$description = $_POST["description"];
$year = $_POST["release_year"];
$rating = $_POST["rating"];
$message = '<br/><br/><br/>';
if (!isset($film)) {
$message .= 'You must provide the film ID!';
} elseif (
(!isset($title) || empty($title)) &&
(!isset($description) || empty($description)) &&
(!isset($year) || empty($year)) &&
(!isset($rating) || empty($rating))
) {
$message .= 'You must provide at least one field for the selected film ID!';
} else {
$sql = sprintf(
"UPDATE films SET %s%s%s%s WHERE film_id = %s"
, isset($title) ? "title = '$title'" : ""
, isset($description) ? ", description = '$description'" : ""
, isset($year) ? ", release_year = '$year'" : ""
, isset($rating) ? ", rating = '$rating'" : ""
, $film
);
if (mysqli_query($mysqli, $sql)) {
$message .= "Succesvol aangepast!";
$message .= "<br>";
$message .= "<a href='overzichtspagina.php'>Terug naar de vorige pagina.</a>";
} else {
$message .= "Error: " . $sql . "<br>" . mysqli_error($mysqli);
}
}
echo $message;
}
$mysqli->close();
?>
</body>
</html>
EDIT 1:
I recommend you to use exception handling. Here is an example:
try {
// Connect to db.
$mysqli = new mysqli('localhost', 'root', 'root', 'tests');
if (!isset($mysqli) || !$mysqli) {
throw new Exception("Connection failed: " . mysqli_connect_error());
}
// Run query on db.
$query = mysqli_query($mysqli, $sql);
if (!$query) {
throw new Exception('The statement can not be executed!');
}
$mysqli->close();
} catch (Exception $exception) {
echo $exception->getMessage();
/*
* OR display the whole error information.
* But only in the development stage!
*/
// echo '<pre>' . print_r($exception, true) . '</pre>';
exit();
}
Don't forget to add a <title> tag to your page.

PHP&html: emailing form's checkboxes

I'm trying to make a simple form that sends the user input to my email. I don't know PHP so I'm having some trouble here. I can't make the form include the checkboxes' results in the mail. I tried several times but I can't make it work. It's in spanish, sorry for that!
Here is the code:
contactoformescritorio.php:
<?php
$where_form_is = "contacto.html".$_SERVER['SERVER_NAME'].strrev(strstr(strrev($_SERVER['PHP_SELF']),"/"));
mail("MY#MAIL.com","Formulario de pedido de copias","Form data:
Nombre: " . $_POST['cd-name'] . "
Email: " . $_POST['cd-email'] . "
Tamanio: " . $_POST['tamanio'] . "
Acabado: " . $_POST['acabado'] . "
Incluir en la cotizacion: " .implode(',',$_POST['agregados'])."\n" . "
Foto elegida e información adicional: " . $_POST['cd-textarea'] . "
.
");
include("confirm.html");
/*
* Procesar el formulario unicamente si el usuario lo envió. En cambio,
* si se accede directamente a esta página, redirigir al formulario.
*/
if ($_SERVER['REQUEST_METHOD'] == "POST") {
function check_input_value($input_value) {
// Remove extra spaces of strings (beginning and end)
$input_value = trim($input_value);
// Prevent XSS
$input_value = htmlspecialchars($input_value);
return $input_value;
}
// Obtenemos los valores que el usuario ingresó
$tamanio = $_POST['tamanio'];
$acabado = $_POST['acabado'];
$tamanio = check_input_value($tamanio);
$acabado = check_input_value($acabado);
if (empty($tamanio) || (empty($acabado)) || (empty($agregados))) {
echo "Error: sin completar";
exit;
}
echo $tamanio . "<br />";
echo $acabado . "<br />";
// Muestra los checkbox seleccionados por el usuario
if (!empty($_POST['agregados'])) {
foreach ($_POST['agregados'] as $agregados) {
echo $agregados . "<br />";
}
}
} else {
header("Location: formulario.php");
}
?>
A friend helped me with the form so it may be a little messy as I copied and pasted some parts.
contacto.html
<form class="cd-form floating-labels" name="htmlform" method="post" action="contactoformescritorio.php">
<fieldset>
<legend>Información personal</legend>
<div class="error-message">
<p>Por favor ingresa un email valido</p>
</div>
<div class="icon">
<label class="cd-label" name="cd-name" for="cd-name">Nombre</label>
<input class="user" type="text" name="cd-name" id="cd-name" required>
</div>
<div class="icon">
<label class="cd-label" name="cd-email" for="cd-email">Email</label>
<input class="email error" type="email" name="cd-email" id="cd-email" required>
</div>
</fieldset>
<fieldset>
<legend>Informacion de la impresion</legend>
<div>
<h4>Tamaño</h4>
<p class="cd-select icon">
<select class="size" name="tamanio" id="cd-size">
<option value="0">Seleccionar Tamaño</option>
<option value="1">Impresion 20x30</option>
<option value="2">Iman de 6 fotos 5x5</option>
<option value="3">Tamaño 3</option>
</select>
</p>
</div>
<div>
<h4>Acabado</h4>
<ul class="cd-form-list">
<li>
<input type="radio" name="acabado" value="mate" id="mate" checked="checked"/><label for="mate">Mate</label>
</li>
<li>
<input type="radio" name="acabado" value="brillo" id="brillo"/><label for="brillo">Brillo</label>
</li>
</ul>
</div>
<div>
<h4>Agregar a la cotización</h4>
<ul class="cd-form-list">
<li><input type="checkbox" name="agregados[]" value="marco" id="marco"><label for="marco">Marco</label></li>
<li><input type="checkbox" name="agregados[]" value="envio" id="envio"><label for="envio">Envio (indicar direccion)</label></li>
</ul>
</div>
<div class="icon">
<label class="cd-label" for="cd-textarea">Foto elegida e información adicional</label>
<textarea class="message" name="cd-textarea" id="cd-textarea" required></textarea>
</div>
<div>
<input type="submit" value="Enviar mensaje">
</div>
</fieldset>
</form>
Your checkboxes are both of the name agregados[], which makes them an array. You currently handle them via implode, then later with a foreach.
Before your mail, run a foreach like this
if (!empty($_POST['agregados'])) {
foreach ($_POST['agregados'] as $key=>$value) {
if ($key > 0) {
$agregados .= ", $value";
} else {
$agregados .= "$value";
}
}
} else {
$agregados .= "(nothing selected)";
}
This will set the variable $agregados with the values that was selected from the checkboxes, and if nothing is selected, display such a message instead.
Then, in your mail, replace the line that handles the checkboxes with the variables.
Replace:
Incluir en la cotizacion: " .implode(',',$_POST['agregados'])."\n" . "
with
$agregados
Also, please know that your mail will be sent regardless when you enter contactoformescritorio.php, as there is no checking if a form has been sent to it. The check you are performing (if ($_SERVER['REQUEST_METHOD'] == "POST")) comes after that.
As a final note, not one that's related to your question directly, your select has no require-attribute, so your PHP script exits if nothing is selected (where you are checking of one of the three statements are empty). Just put a required attribute in your select, such as this
<select class="size" name="tamanio" id="cd-size" required>
Then your Seleccionar Tamaño can be set to a line like this
<option value="" selected style="display:none;">Seleccionar Tamaño</option>
This will make your form more "user-friendly", and not make the user fill in the form all over again if they forget to select something from the dropdown. Just a tip, nothing you really have to do.

creating an array from database

I'm using a array to get a range between 1011-2371 but I'didnt need all digits. It's a long list thats why I import the CSV to the database.
I want to create a array from a database table.
But I can't get it.
Here's a rough mockup of the old php:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']?>">
<input type="text" placeholder="1234AB" name="postcode" />
<input type="submit" value="verstuur" />
</form>
<?php
if($_SERVER['REQUEST_METHOD'] == "POST") {
$postcode = range(1011,2371);
if(preg_match('/^[1-9][0-9]{3} ?[a-zA-Z]{2}$/', $_POST['postcode'])) {
if(in_array($_POST['postcode'],$postcode)) {
echo 'FreshFoods is beschikbaar bij jou in de buurt.';
} else {
echo 'FreshFoods is nog niet beschikbaar bij u in de buurt.';
}
} else {
echo 'Voer 4 cijfers en 2 letters in als postcode. Voorbeeld 1234AB';
}
}
?>
and this is what I try do get the array from the database:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']?>">
<input type="text" placeholder="1234AB" name="postcode" />
<input type="submit" value="verstuur" />
</form>
<?php
require_once 'db_config.php';
if($_SERVER['REQUEST_METHOD'] == "POST") {
$postcode = array();
$result = mysql_query("SELECT postcode FROM postcode_check");
if(preg_match('/^[1-9][0-9]{3} ?[a-zA-Z]{2}$/', $_POST['postcode'])) {
if(in_array($_POST['postcode'],$postcode)) {
echo 'FreshFoods is beschikbaar bij jou in de buurt.';
} else {
echo 'FreshFoods is nog niet beschikbaar bij u in de buurt.';
}
} else {
echo 'Voer 4 cijfers en 2 letters in als postcode. Voorbeeld 1234AB';
}
}
?>
the db_config.php file looks like:
<?php
$db = array (
'host' => 'localhost',
'user' => 'root',
'pass' => 'root',
'dbname' => 'testzip'
);
if(!mysql_connect($db['host'], $db['user'], $db['pass']))
{
trigger_error('Fout bij verbinden: '.mysql_error());
}
elseif(!mysql_select_db($db['dbname']))
{
trigger_error('Fout bij selecteren database: '.mysql_error());
}
else
{
$sql = "SET SESSION sql_mode = 'ANSI,ONLY_FULL_GROUP_BY'";
if(!mysql_query($sql))
{
trigger_error('MySQL in ANSI niet mogelijk');
}
}
?>
you have to use mysql_fetch_array or mysql_fetch_assoc to fetch the result from database.
<form method="post" action="<?php echo $_SERVER['PHP_SELF']?>">
<input type="text" placeholder="1234AB" name="postcode" />
<input type="submit" value="verstuur" />
</form>
<?php
require_once 'db_config.php';
if($_SERVER['REQUEST_METHOD'] == "POST") {
$postcode = array();
$result = mysql_query("SELECT postcode FROM postcode_check");
while ($row = mysql_fetch_array($result)) {
$postcode[] = $row['postcode'];
}
if(preg_match('/^[1-9][0-9]{3} ?[a-zA-Z]{2}$/', $_POST['postcode'])) {
if(in_array($_POST['postcode'],$postcode)) {
echo 'FreshFoods is beschikbaar bij jou in de buurt.';
} else {
echo 'FreshFoods is nog niet beschikbaar bij u in de buurt.';
}
} else {
echo 'Voer 4 cijfers en 2 letters in als postcode. Voorbeeld 1234AB';
}
}
?>
Try this code.
You need to fetch the result. Your regex will never match your sample data from the db though so you will always get the nog niet message. or voorbeeld. Never 'FreshFoods is beschikbaar bij jou in de buurt'
<form method="post" action="<?php echo $_SERVER['PHP_SELF']?>">
<input type="text" placeholder="1234AB" name="postcode" />
<input type="submit" value="verstuur" />
</form>
<?php
require_once 'db_config.php';
if($_SERVER['REQUEST_METHOD'] == "POST") {
$postcode = array();
$result = mysql_query("SELECT postcode FROM postcode_check");
while($row = mysql_fetch_assoc($result)){
$postcode[] = $row['postcode'];
}
if(preg_match('/^[1-9][0-9]{3} ?[a-zA-Z]{2}$/', $_POST['postcode'])) {
if(in_array($_POST['postcode'],$postcode)) {
echo 'FreshFoods is beschikbaar bij jou in de buurt.';
} else {
echo 'FreshFoods is nog niet beschikbaar bij u in de buurt.';
}
} else {
echo 'Voer 4 cijfers en 2 letters in als postcode. Voorbeeld 1234AB';
}
}
?>

Fill in form in PHP

So I've had to make a simple phonebook in PHP, but right now it simply echos the text beneath the form, I however, want it to fill it in the form which says: Phonenumber (When you type in the exact name of someone you it echos their phonenumber)
Here's the Form:
<form action="" method="post">
Naam: <br><input type="text" name="name" /><br>
Telefoonnummer: <br><input type="text" name="phonenumber" disabled />
<input type="submit" value="submit" />
</form>
and here's the PHP (I'm Dutch btw so some of the text is in Dutch):
<?php
if(isset($_POST['name'])) {
$formNaam = $_POST['name'];
$naamPersoon = array ("Ilja Clabbers","Piet Paulusma","Gerrit Zalm");
$telefoonNummer = array ("038-4699776","0568-121212","010-2311512");
if(empty($formNaam)) {
echo 'Vul een veld in.';
} else if ($formNaam == $naamPersoon[0]){
echo "Het telefoonnummer van " . $naamPersoon[0] . " is " .$telefoonNummer[0];
} else if ($formNaam == $naamPersoon[1]){
echo "Het telefoonnummer van " . $naamPersoon[1] . " is " .$telefoonNummer[1];
} else if ($formNaam == $naamPersoon[2]){
echo "Het telefoonnummer van " . $naamPersoon[2] . " is " .$telefoonNummer[2];
} else {
echo "Deze naam staat niet in het archief";
}
}
?>
So basically what I'd like to know is; How do you get the phonenumber belonging to a persons name to be shown in the Form where it says 'Telefoonnummer:'?
A neater solution would be to make a single associative array with key => value pairs:
$naamPersoon = array (
"Ilja Clabbers" => "038-4699776",
"Piet Paulusma" => "0568-121212",
"Gerrit Zalm" => "010-2311512",
);
Then your code would be:
$phonenumber = '';
if (array_key_exists($formNaam, $naamPersoon)) {
echo "Het telefoonnummer van " . $formNaam . " is " . $naamPersoon[$formNaam];
$phonenumber = $naamPersoon[$formNaam];
} else {
echo "Deze naam staat niet in het archief";
}
Alternatively you could keep your two arrays as they are and use array_search to find the index of the name in the first array, then use it as the index you check in the second array
$phonenumber = '';
$index = array_search($formNaam, $naamPersoon);
if ($index === false) {
echo "Deze naam staat niet in het archief";
} else {
echo "Het telefoonnummer van " . $formNaam . " is " . $telefoonNummer[$index];
$phonenumber = $telefoonNummer[$index];
}
Either way you can then use the assigned variable $phonenumber to add the number to the form by echoing it out as the input's value. At which point you can take out the echos if you wish.
<form action="" method="post">
Naam: <br><input type="text" name="name" /><br>
Telefoonnummer: <br><input type="text" name="phonenumber" value="<?=htmlspecialchars($phonenumber)?>" disabled />
<input type="submit" value="submit" />
</form>

Categories