I am trying to select columns from a mysql table based on checkboxes (columns provided as check boxes). The following is a reproducible example.
<?php
require('connect.php');
?>
<!DOCTYPE html>
<head></head>
<body>
<div>
<form action="" method="POST">
<input type="checkbox" name="check_list[]" value="ZONE"><label>ZONE</label>
<input type="checkbox" name="check_list[]" value="STATE"><label>STATE</label>
<input type="submit" name="submit" Value="Submit"/>
</form>
</div>
<?php
if(isset($_POST['submit'])){
if(!empty($_POST['check_list'])) {
$checkboxes = isset($_POST['check_list']) ? $_POST['check_list'] : array();
foreach($checkboxes as $value) {
echo $value,','; //selected value
$sql = "SELECT $value,sum(RICEPDS) as 'CEREALS' from ck group by $value" ;
$result = mysqli_query($connection, $sql);
}}}
?>
<div>
<table>
<thead>
<tr>
<?php
if (!$result) {
die("Query to show fields from table failed");
}
$fields_num = mysqli_num_fields($result);
for($i=0; $i<$fields_num; $i++)
{
$field = mysqli_fetch_field($result);
echo "<th>{$field->name}</th>";
}
?>
</tr>
</thead>
<tbody>
<?php
while ($row = mysqli_fetch_assoc($result)) {
?>
<tr>
<?php
foreach($row as $cell)
echo "<td>$cell</td>";
?>
</tr>
<?php
}
mysqli_free_result($result);
?>
</tbody>
</table>
</div>
</body>
</html>
Understandably when I select one checkbox the table gets returned. When I select both the checkboxes, I am getting the error message echoed from this: die("Query to show fields from table failed");.
I think I have to get the last trailing comma from the $value. How do I do it?
Refer this link PHP mysqli_multi_query() Function https://www.w3schools.com/php/func_mysqli_multi_query.asp
Taking inspiration from this post I resolved this issue. My working code is as follows:
if(isset($_POST['submit'])){
if(!empty($_POST['check_list'])) {
$my_values = implode(",", $_POST['check_list']);
$sql = "SELECT $my_values,sum(RICEPDS) as 'CEREALS' from ck group by $my_values" ;
$result = mysqli_query($connection, $sql);
}}
Related
Good day! I am having a problem in storing values in my database. The flow of the program is the user will input in how many subject he will get. For example, he/she can put 6 subjects. So it will release 6 input types with values equal to text. My problem is I don't get 6 rows in my database as the user take 6 inputs.
HTML/PHP
<form method="POST">
<table>
<tr>
<td>SUBJECT CODE/SUBJECT DESCRIPTION/SEMESTER</td>
</tr>
<?php $counter=1 ;
while($counter <= $subj){?>
<tr>
<td>
<select name="sub">
<?php $select=mysql_query("SELECT * FROM subject
WHERE course_code = '$course' AND semester = '$sem'");
while($rows=m ysql_fetch_assoc($select)){
$code=$rows['subj_code'];
$desc=$rows['subj_desc'];
$units=$rows['units'];
$yr=$rows[ 'year_level'];
?>
<**option value="<?php echo $codes[$code]; ?>">
<?php echo $code. " - ".$desc; ?>
</option>**
<?php } ?>
</select>
</td>
<td>
</td>
</tr>
<?php $counter++; } } ?>
<tr>
<td>
<input type="submit" name="add" value="add subjects">
</td>
</tr>
</table>
</form>
PHP/SQL
<?php
if (isset($_POST['add'])) {
$data = array();
$subject = $_POST['sub'];
$sem = $_SESSION['sem'];
for ($i = 0; $i < count($subject); $i++) {
$subject = mysql_real_escape_string($subject[$i]);
$sem = mysql_real_escape_string($sem[$i]);
$yr = mysql_real_escape_string($yr[$i]);
$fac = mysql_real_escape_string($fac[$i]);
$col = mysql_real_escape_string($col[$i]);
$set = mysql_query("SET foreign_key_checks = 0");
if (!$set) {
die("Foreign key SET failed");
} else {
$insertmid = mysql_query("INSERT INTO grade_midterm
(midterm_grade, semester, year_level, subj_code, stud_id, fac_id, col_code)
VALUES ('NA','$sem','$yr','$subject', '$user','$fac','$col')");
if (!$insertmid) {
die("Failed to insert midterm" . mysql_error());
} else {
$insertfinal = mysql_query("INSERT INTO grade_final
(final_grade, semester, year_level, subj_code, stud_id, fac_id, col_code)
VALUES ('NA','$sem','$yr','$subject','$user','$fac','$col')");
if (!$insertfinal) {
die("Failed to indert final");
} else {
$set2 = mysql_query("SET foreign_key_checks = 1");
echo "<script>alert('Success Adding Subject');</script>";
}
}
}
}
}
?>
You have a select box with name sub in your loop
<select name="sub">
this means every next selectbox will overwrite the previous one
use
<select name="sub[]">
to create a array in your $_POST variable
I have built a checkbox group using forums and everything works on the standalone script that a created but when i add it to my user system afte selecting more than one I get array echoed where the list is supposed to be below is the production script
<?php
session_start();
include 'dbconfig.php';
$chkbox = array('option1', 'option2', 'option3');
if (isset($_POST['submit']))
{
$chkbox = $_POST['chkbox'];
$chkNew = "";
foreach($chkbox as $chkNew1)
{
$chkNew .= $chkNew1 . ",";
}
$query = "INSERT INTO demo_table_5 (MultipleValue) VALUES ('$chkNew')";
mysqli_query($conn,$query) or die(mysqli_error());
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>PHP Insert/Store multiple selected checkbox values in MySQL database</title>
</head>
<body>
<h2>PHP Insert multiple checkbox values in MySQL database</h2>
<form method="post" action="">
<table>
<tr>
<td><input type="checkbox" name="chkbox[]" value="option1"><label>option1</label></td>
<td><input type="checkbox" name="chkbox[]" value="option2"><label>option2</label></td>
<td><input type="checkbox" name="chkbox[]" value="option3"><label>option3</label></td>
</tr>
<tr>
<td colspan="4"><input type="submit" name="submit" Value="submit"></td>
</tr>
</table>
</form>
<?php
$sql = "SELECT MultipleValue FROM demo_table_5";
$result = mysqli_query($conn, $sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>Interests</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["MultipleValue"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
</body>
</html>
so when I added it to script I put
<table>
<tr>
<td><input type="checkbox" name="chkbox[]" value="option1"><label>option1</label></td>
<td><input type="checkbox" name="chkbox[]" value="option2"><label>option2</label></td>
<td><input type="checkbox" name="chkbox[]" value="option3"><label>option3</label></td>
</tr>
in the register form its self
then I put the following in the php block at the top of the registration page
$chkbox = array('option1', 'option2', 'option3');
and I added a column to the existing userinfo table in database and named it multipleValue and added the following line to update database
MultipleValue = '".$_POST['chkbox']."',
then I added the following bit to the profile page
<?php
$sql = "SELECT MultipleValue FROM user_info";
$result = mysqli_query($conn, $sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>Interests</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["MultipleValue"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
Since your inputs have name="chkbox[]", this means that $_POST['chkbox'] is an array containing the values of all the checked boxes. In PHP, when you try to use an array as a string, as in
MultipleValue = '".$_POST['chkbox']."',
the array is converted to the string "Array". You need to use implode to convert it to a comma-separated list:
MultipleValue = '".implode(',', $_POST['chkbox'])."',
However, I recommend you change your table design. Comma-separated values in a table cell are a bad way to represent lists, because it's difficult to search and update them -- indexes can't be used to search for individual values in the list, for instance. You should use a many-to-many table where there's a row for each user+option combination.
You are inserting in the db a concatenated string such as "option1,option2,option3".
Retrieving data by the SQL select statement will return one row containing the concatenation
My goal to my code is to show the count query for the number of batchcode in table batchcodes to my textbox and if i click the button it will save to the batchcode table...my batchcode field is
'id','batchcode'
my current code:
<?php
ob_start();
?>
<html>
<head>
<title>test</title>
</head>
<body>
<?php
include('include/connect.php');
$query = "SELECT DISTINCT count(batchcode) FROM batchcodes";
while( $rows = mysql_fetch_array($query)) {
}
?>
<?php
if(isset($_POST['save'])){
$var = $query+1;
$sql = "INSERT INTO batchcodes(batchcode) VALUES ('$var')";
}
?>
<form method="post" action="index.php" >
<input type="text" value="batch<?php echo $query; ?>" />
<input type="submit" name"save" />
</form>
</body>
</html>
In my code im suffering from error like Undefined variable query and warning mysql_fetch_array expects parameter 1...I need your help guys.
Use mysql_query.
$query = mysql_query("SELECT DISTINCT count(batchcode) AS nb_batchcode FROM batchcode");
while($row= mysql_fetch_array($query)) {
$batchcode=$row['nb_batchcode'];
}
<input type="text" name="save" value="batch<?php echo $batchcode; ?>" />
You should use mysql_query function to execute the query
$query = mysql_query("SELECT DISTINCT count(batchcode) as batchcode FROM batchcodes");
$sql = mysql_query("INSERT INTO batchcodes(batchcode) VALUES (". $var .")");
Here's how I did it on PHP based on my SQL data
<li>
<label> OR #: </label>
<?php
include('php/connect-db.php');
$sql = mysql_query("SELECT MAX(or_num)+1 AS inc_or FROM tbl_admission");
while($row = mysql_fetch_array($sql)){
$nextOR=$row['inc_or'];
}
?>
<input type="text" name="asID" value="<?php echo $nextOR; ?>" disabled>
OR_num is my integer and auto-incremented key in my table "tbl_admission" :)
Use $row instead of $query to get result from query.Try below code can help you.
<?php
ob_start();
?>
<html>
<head>
<title>test</title>
</head>
<body>
<?php
include('include/connect.php');
$query = "SELECT DISTINCT count(batchcode) as batchcode FROM batchcodes";
while( $rows = mysql_fetch_array($query)) {
}
?>
<?php
if(isset($_POST['save'])){
$var = $row[0] + 1;
$sql = "INSERT INTO batchcodes(batchcode) VALUES (". $var .")";
}
?>
<form method="post" action="index.php" >
<input type="text" name="save" value="batch<?php echo $query; ?>" />
<input type="submit"
</form>
</body>
</html>
I have a loop of checkboxes from a MySql table "exercise" in a form as shown below:
<form id="form1" name="form1" method="POST" action="insertDrills.php">
<table width="100%" border="1" cellspacing="0" cellpadding="0">
<?php do { ?>
<tr>
<td>
<input type="checkbox" name="drillSelect[]" value="<?php echo $row_Recordset1['drillID']; ?>" id="drillSelect" />
<?php echo $row_Recordset1['rubrik']; ?>
</td>
</tr>
<?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
<tr>
<td colspan="2">
<input name="spelarID" type="hidden" id="spelarID" value="<?php echo $row_rsSpelare['id']; ?>" />
<input name="date" type="hidden" id="date" value="<? print date("Y-m-d h:i:s"); ?>" />
<input type="submit" name="submit" id="submit" value="Välj övningar" />
<input type="button" value="Avbryt" onclick="window.close();"></button>
</td>
</tr>
</table>
</form>
The value from the hidden fied "spelarID" along with the value from the checkbox array are inserted to a look-up table "exercise_spelare_ref" with this:
<?php
$id = $_POST['spelarID'];
$drills = $_POST['drillSelect'];
$date = $_POST['date'];
$inserts = array();
foreach ($drills as $drills)
$inserts[] = "('$id','$drills','','$date')";
$query = "REPLACE INTO exercise_spelare_ref VALUES ". implode(", ", $inserts);
//echo "query = $query"; // for debugging purposes, remove this once it is working
mysql_query($query) or die(mysql_error());
?>
How can I make values that are in the look-up table marked as "checked" in the form?
There are a solution here https://stackoverflow.com/a/4069477 written by Martin Bean but I cant get it to work?
I have been stuck here for ever, hope anyone can help me out here!
I tried Martin Beans script like:
$uid = $row_rsSpelare['id']; // your logged in user's ID
$exercise = array();
// get an array of exercise
$sql = "SELECT drillID FROM exercise";
$res = mysql_query($sql);
while ($row = mysql_fetch_object($res)) {
$exercise[$row->id] = $row->drillID;
}
// get an array of exercise user has checked
$sql = "SELECT DISTINCT drillID FROM exercise_spelare_ref WHERE id = '$uid'";
$res = mysql_query($sql);
while ($row = mysql_fetch_object($res)) {
$checked[] = $row->drillID;
}
// this would be templated in a real world situation
foreach ($exercise as $id => $drillID) {
$checked = "";
// check box if user has selected this exercise
if (in_array($checked, $id)) {
$checked = 'checked="checked" ';
}
echo '<input type="checkbox" name="drillSelect[]" value="'.$id.'" '.$checked.'/>';
}
But getting a warning:
Warning: in_array() expects parameter 2 to be array, string given in /customers/b/d/e/teeview.se/httpd.www/analys_kund/selectDrills.php on line 158
Line 158 is:
if (in_array($checked, $id)) {
Well, you will need to SELECT the items from the table, store them into an array, and if the current checkbox's ID matches something in the array, add the checked attribute to it in the HTML.
Below code !Gives me check boxes and a delete button, In input tag all check box have same name (check)!! There check box can be retreive from database with id .
Problem Is:: when I am selecting multiple checkbox for deletion...only last one checkbox is deleted ! means it can delete 1 data from a database.
url like -> http://localhost/demo/delete.php?check=10&check=13&check=14&submit=Delete
I need while I am selecting a checkbox more than 1 checkbox ,check box datas is deleted from database ! Any one help me to overcome this problem thanks
index.php
<?php
$sql = mysql_connect('localhost', 'root', '');
mysql_select_db('database_section', $sql);
?>
<form name="checkbox" method="get" action="delete.php">
<table>
<tr>
<?php
$sql = "select * from data";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
?>
<td><input type="checkbox" name="check" value="<?php echo $row['id']?>"><?php echo $row['data'];?>
</td>
<?php
}
?>
<tr>
<td><input type="submit" name="submit" value="Delete"></td>
</tr>
</table>
</form>
Now, In delete.php..code below...
<?php
$sql = mysql_connect('localhost', 'root', '');
mysql_select_db('database_section', $sql);
if ($_REQUEST['submit']) {
$abc = $_GET['check'];
$sql = "Delete from data where id=$abc";
$result = mysql_query($sql) or die(mysql_error());
if (isset($result)) {
echo "data deleted";
}
else
{
echo "not possible";
}
}
?>
Use check box as an array holder. name it as check[] to hold all selected values. And on post you will get the selected array list.
Now your $abc will be a array, use foreach in delete.php to get the checked ids.
Change name="check" to name="check[]"
See more here: http://www.kavoir.com/2009/01/php-checkbox-array-in-form-handling-multiple-checkbox-values-in-an-array.html
[...]
while ($row = mysql_fetch_array($result))
{
?>
<td>
<input type="checkbox" name="check[]" value="<?php echo $row['id']?>"><?php echo $row['data']; ?>
</td>
<?php
}
?>
[...]