Checkbox php mysql примеры

inserting checkbox values in mysql +PHP

I am new to PHP or just not good at it lol, I have been trying to insert checkbox elements into a mysql database. I have a table called Team with two collumns. Id int not null auto increment PK
team varchar 30 not null

 select team: :Argentina :Spain :Holland :France ?> 
  Parse error: syntax error, unexpected ' 
  • 4 Contributors
  • 66 Replies
  • 11K Views
  • 2 Weeks Discussion Span
  • Latest Post 15 Years Ago Latest Post by asadalim1

Recommended Answers Collapse Answers

 > ?>    Argentina 
Germany
Brazil

Hi, Sorry. I didn't get it. Could you please re-explain the whole thing to me ? Is it like this.
You have a textbox to enter the name, list of checkboxes to select the country and a submit button. You can add records to the table from this screen. You …

 if($operation=="delete") < $q="delete from table1 where counter='$id'"; mysql_query($q); >if(isset($_POST['update'])) < $name=$_POST['name']; $team=implode(",",$_POST['team']); $q="update table1 set name='$name', team='$team' where counter='$id'"; mysql_query($q); >?>   Enter name: …

are you want to do like this.

I guess you didn't read all the posts.

print the values of team before foreach.
print_r($_POST); If its an array, it ll print the whole array. else it ll print only 1 value.

All 66 Replies

 > ?>    Argentina 
Germany
Brazil

There! That will work 🙂 Cheers,
Naveen Edit: The error was because, you had opened php tag but you opened it again.

    Argentina 
Germany
Brazil
> ?>
Parse error: syntax error, unexpected $end in C:\wamp\www\examples\chk123.php on line 13 
$insert="INSERT INTO team('team') VALUES ('$value')"; echo $insert; mysql_query($insert);

Print your query. Execute the same in phpmyadmin or mysql. Check what's the error. Or you can give, mysql_query($insert) or die(mysql_error()); to know what is the error.

Hi, i have tried this but doesn't return anything. I'm Wondering whether my table design in mysql is incorrect. I have only two collumns, one to store the ID and one to store the team.

Table Team [U]id[/U] Int(11) Not Null auto_increment team varchar(30) Not Null if(isset($_POST['team'])) < foreach($_POST['team'] as $value)< $insert=mysql_query("INSERT INTO team('team') VALUES ('$value')"); >> echo $insert;mysql_query($insert); ?> 

Try this. It will print out the query. Execute it in phpmyadmin or mysql. I don't think your query or the table structure is wrong. Maybe the values of $_POST isn't being passed. Well, execute these queries and find out why its not inserting !

I tried the query it prints "INSERT INTO team ('team') VALUES ('BR')" correctly however it still doesnt store the value into the database, I even selected mysql_select_db("lastr", $con);$sql= the database still not working. thank you for all your responses by da way. $con = mysql_connect("localhost","root","talk21");
if (!$con)
die('Could not connect: ' . mysql_error());
>
if(isset($_POST))
< foreach($_POST as $value) mysql_select_db("lastr", $con);$sql= $insert ;echo $insert;mysql_query($insert);
>
> ?>

Источник

inserting checkbox values in mysql +PHP

I am new to PHP or just not good at it lol, I have been trying to insert checkbox elements into a mysql database. I have a table called Team with two collumns. Id int not null auto increment PK
team varchar 30 not null

 select team: :Argentina :Spain :Holland :France ?> 
  Parse error: syntax error, unexpected ' 
  • 4 Contributors
  • 66 Replies
  • 11K Views
  • 2 Weeks Discussion Span
  • Latest Post 15 Years Ago Latest Post by asadalim1

Recommended Answers Collapse Answers

 > ?>    Argentina 
Germany
Brazil

Hi, Sorry. I didn't get it. Could you please re-explain the whole thing to me ? Is it like this.
You have a textbox to enter the name, list of checkboxes to select the country and a submit button. You can add records to the table from this screen. You …

 if($operation=="delete") < $q="delete from table1 where counter='$id'"; mysql_query($q); >if(isset($_POST['update'])) < $name=$_POST['name']; $team=implode(",",$_POST['team']); $q="update table1 set name='$name', team='$team' where counter='$id'"; mysql_query($q); >?>   Enter name: …

are you want to do like this.

I guess you didn't read all the posts.

print the values of team before foreach.
print_r($_POST); If its an array, it ll print the whole array. else it ll print only 1 value.

All 66 Replies

 > ?>    Argentina 
Germany
Brazil

There! That will work 🙂 Cheers,
Naveen Edit: The error was because, you had opened php tag but you opened it again.

    Argentina 
Germany
Brazil
> ?>
Parse error: syntax error, unexpected $end in C:\wamp\www\examples\chk123.php on line 13 
$insert="INSERT INTO team('team') VALUES ('$value')"; echo $insert; mysql_query($insert);

Print your query. Execute the same in phpmyadmin or mysql. Check what's the error. Or you can give, mysql_query($insert) or die(mysql_error()); to know what is the error.

Hi, i have tried this but doesn't return anything. I'm Wondering whether my table design in mysql is incorrect. I have only two collumns, one to store the ID and one to store the team.

Table Team [U]id[/U] Int(11) Not Null auto_increment team varchar(30) Not Null if(isset($_POST['team'])) < foreach($_POST['team'] as $value)< $insert=mysql_query("INSERT INTO team('team') VALUES ('$value')"); >> echo $insert;mysql_query($insert); ?> 

Try this. It will print out the query. Execute it in phpmyadmin or mysql. I don't think your query or the table structure is wrong. Maybe the values of $_POST isn't being passed. Well, execute these queries and find out why its not inserting !

I tried the query it prints "INSERT INTO team ('team') VALUES ('BR')" correctly however it still doesnt store the value into the database, I even selected mysql_select_db("lastr", $con);$sql= the database still not working. thank you for all your responses by da way. $con = mysql_connect("localhost","root","talk21");
if (!$con)
die('Could not connect: ' . mysql_error());
>
if(isset($_POST))
< foreach($_POST as $value) mysql_select_db("lastr", $con);$sql= $insert ;echo $insert;mysql_query($insert);
>
> ?>

Источник

Mysql запрос для интернет магазина с использованием checkbox

Как бы вы подошли к решению такой задачи? На сайте есть фильтр для подбора по характеристикам. - бренд, цвет, стиль и .т.п. Характеристики для фильтрации отмечаются чекбоксами и затем Ajax передает на сервер перечень отмеченных и неотмеченных чекбоксов. Страница ( php ) на сервере, на основании ОТМЕЧЕННЫХ чекбоксов формирует запрос к БД ( MySql ) и получает количество (count) товаров, которые имеют отмеченные в чекбоксах характеристики. Результат возвращается в браузер и выводится окошко: найдено X товаров. Собственно как в Яндекс Маркете. Я написал код Checkbox(ы) (только пример. на самом деле групп с чекбоксами будет больше)

 
$brand = $_POST['brand']; $color = $_POST['color']; $style = $_POST['style']; $Query = "SELECT * FROM items WHERE brand IN ('" . implode("','", $brand) . "') AND color IN ('" . implode("','", $color) . "') AND style IN ('" . implode("','", $style) . "')"; $QueryResult = mysqli_query($connection , $Query); while($QueryRow = mysqli_fetch_assoc($QueryResult)) < ?> 
> ?>

Проблема в следующем. если выбираю хотя бы по одному параметру в каждой группе то всё работает, но если хотя бы одна группа будет без отмеченого чекбокса то выдаёт ошибку. Думал над использованием If но тогда нужно будет рассмотреть все возможные варианты отмеченных и не отмеченных чекбоксов,а это очень много.. так же попробовал впихнуть IF напрямую в sql запрос

$Query = "SELECT * FROM items WHERE brand IN ('" . implode("','", $brand) . "') ". if(!empty($color)) if(!empty($style)) ." "; 

Источник

Filter Data with Checkboxes in PHP & MySQL

If you need to filter data with checkboxes in PHP & MySQL for your web application. Then This tutorial will be very helpful for you.

In this tutorial, the checkbox filter data source code is shared with some simple steps that will be very easy to implement into the project.

Some categories will be displayed from the database with checkboxes. When you check a checkbox category then the data will display in tabular form based on that checked checkboxes. If you check multiple checkboxes, then also, data will be filtered for all checked checkboxes.

How to Filter Data with Checkbox using PHP, MySQL

Now, Let’s start the coding to filter data by category with the following simple steps –

Learn Also –

1. Create a Directory Structure

First of all, You should create the following directory structure to filter data by category.

source-code/ |__database.php |__index.php |__filter-data.php |__display-data.php |__get-category.php |

2. Create MySQL Table

Now, Create a MySQL database

CREATE DATABASE codingstatus;

Create a table with the name of the products

CREATE TABLE `products` ( `id` int(10) NOT NULL AUTO_INCREMENT, `productName` varchar(255) DEFAULT NOT NULL, `price` int(20) DEFAULT NOT NULL );

4. Insert Data into MySQL Table

Now, You should insert some records into the MySQL Table. This data will be used to display for the checkboxes and display in the HTML table.

INSERT INTO products(id, productName, category) VALUES (1', 'product-1','category1'), (2', 'product-2','category2'), (3', 'product-3', 'category2'), (4', 'product-4', 'category1'), (5', 'product-5', 'category3'), (6', 'product-6', 'category3'), (7', 'product-7', 'category1'), (8', 'product-8', 'category1'), (9', 'product-9', 'category4'), ('10', 'product-10', 'category3');

3. Setup MySQL Database Connection

Now, You have to connect your PHP to the MySQL database with the following PHP script –

In this script, we have declared the table name in the constant variable to use it globally on any page.

define('productTable', 'products');

Get Category From the Database

To display categories dynamically for the checkboxes from the database, You need to write the code according to the following points

  • Create a user-defined function getCategory() and write code within it according to the next all steps
  • make $conn global to use it anywhere in the file
  • create a variable $data with an empty array.
  • Write SQLi Query to fetch unique categories from the database
  • If the category rows are greater than zero then fetch the category with the $result->fetch_all(MYSQLI_ASSOC) and store it in the variable $data
  • At last return the $data to get categories based on filtered category

File Name – get-category.php

query($query); if($result->num_rows > 0) < $data = $result->fetch_all(MYSQLI_ASSOC);; > return $data; >

5. Create a Form to Filter Data

Now, You need to create the price filtering UI by using the following points –

  • Create a basic HTML structure/code
  • Include the database.php, filter-data.php & get-category.php files that will be explained in the next steps.
  • Make a form with the post method.
  • Call the function getCategory and store into the $getCategories
  • print the value of category for the checkbox by applying foreac loop on the $getCategories
  • Create a submit button with the name of filter
  • Include the file display-data.php just after the form.

6. Write Filtering data with a checkbox Script in PHP

To write filtering data with a checkbox, You need to follow the following steps –

  • Start writing code, If the form is submitted then call the function filterDataByCategory() and store in the $filterDataByCategory.
  • Create a user-defined function filterDataByCategory() and write the code according to the next steps.
  • Get the checkbox value using $_POST[‘category’] and store it in the $filterByCategory.
  • $filterByCategory stores an array of values. So, convert it into the string using implode()
  • Declare $conn with the keyword global to use it globally.
  • If $filterByCategory is not empty then write code according to the next points
  • Write MySQLi query to select productName & category
  • If te filtered rows are greater than zero then fetch it with the $result->fetch_all(MYSQLI_ASSOC) and store in the $data.
  • After that, return the value of $data to display records in the datable.
 function filterDataByCategory() < $filterByCategory = $_POST['category']; $categories = "'".implode("', '", $filterByCategory)."'"; global $conn; $data =[]; if(!empty($filterByCategory))< $query = "SELECT productName, category FROM ".productTable; $query .= " WHERE category IN ($categories)"; $result = $conn->query($query); if($result->num_rows > 0) < $data = $result->fetch_all(MYSQLI_ASSOC);; > > return $data; >

7. Display Filtered Data in Table

To display the filtered data in the HTML table, configure the following points –

  • If the $filterDataByCategory has values then write code within it from the next all points.
  • Create the first row of the table with three columns S.N, Product, & category
  • Then create other rows dynamically based on the filtered data with checkbox
  • print the value of columns ‘productName’ and ‘category’ respectively using foreach on the filterDataByCategory.

File Name – display-data.php

8. Test yourself to filter data by Category

After implementing all the given steps, Now you can test the PHP filtering data by checkbox to open in the web browser.

You will get a select input field with some categories options

  • When you select a category option and submit the form then the records will display in an HTML table related to the filtered category.

Hey there, Welcome to CodingStatus. My Name is Md Nurullah from Bihar, India. I'm a Software Engineer. I have been working in the Web Technology field for 4 years. Here, I blog about Web Development & Designing. Even I help developers to build the best Web Applications.

Источник

Читайте также:  Human readable duration format java
Оцените статью