Create checkboxes in php that correspond to MySQL data - php

I have a php script that pulls information out from my database.
$result = mysqli_query($con,"SELECT * FROM menuitem WHERE id='$id' LIMIT 1");
if (!$result) {
printf("Error: %s\n", mysqli_error($con));// Displays the error that mysql will generate if syntax is not correct.
exit();
}
//DYNAMIC PHP PULLING IN THE DATA AND SPITTING OUT THE RESULTS
while($row = mysqli_fetch_array($result))
{
$id = $row['id'];
$description = $row['description'];
$picturepath = $row['picturepath'];
$name = $row['name'];
$price = $row['price'];
$keywords = $row['keywords'];
$dynamiclist = '<table align="center" width="60%" border="0" cellspacing="5" cellpadding="8">
<tr height="150"></tr>
<tr>
<td width="30% valign="top" align="center"><img style="border: #66cc33 5px solid;" src=" ' .$picturepath . '" height="200" width="200" border="1"/></td>
<td width="70%" valign="top" align="left"> <br />' . $name . ' <br /><br />$' . $price . '<br /><br /><font>Description:</font><br /> ' . $description . ' <br /><br /><br />
<form id="form1" name="form1" method="post" action="cart.php">
<input type="hidden" name="keywords" id="keywords" value=" '. $keywords .'"/>
<input type="hidden" name="pid" id="pid" value=" ' . $name . ' - $' . $price . ' "/>
<input type="submit" name="button" id="button" value="Add to Order"/>
</form>
</td>
</tr>
<tr align="center"><td>View Your Order</td></tr>
</table>';
echo $dynamiclist;
}
mysqli_close($con); //close the db connection
?>
And then I have another page where I want checkboxes created for each keyword listed. I'm not sure if I have my db colum set up correctly, but I have a column set up with multiple keywords: first, second, fifty, none, and more.
I've tried creating this, but it only displays actual "checkboxes" with no text next to any of them.
<?php
require("database.php"); //connect to the database
if(isset($_POST['keywords'])){
$pid = $_POST['keywords'];
}
$result = mysqli_query($con,"SELECT * FROM menuitem ");
if (!$result) {
printf("Error: %s\n", mysqli_error($con));// Displays the error that mysql will generate if syntax is not correct.
exit();
}
//DYNAMIC PHP PULLING IN THE DATA AND SPITTING OUT THE RESULTS
$option = '';
while($row = mysqli_fetch_array($result))
{
$id = $row['id'];
$description = $row['description'];
$picturepath = $row['picturepath'];
$name = $row['name'];
$price = $row['price'];
$keywords = $row['keywords'];
$dynamiclist ="<input type='checkbox' name='checkbox' value='". $keywords ."'>";
echo $dynamiclist;
}
The goal is to have a user select an item from the first page, and on the second page, list several checkbox options for that specific item. Any help would be greatly appreciated.

If you want text next to the checkbox, you have to put it in the HTML. And if the column contains a comma-separated list, you need to split it up.
foreach(explode(',', $keywords) as $keyword) {
$keyword = trim($keyword);
echo "<input type='checkbox' name='checkbox' value='$keyword'>$keyword ";
}

Try this:
<?php
$keywords = explode(',', $keywords);
if(!empty($keywords))
{
foreach($keywords as $keyword) {
$keyword = trim($keyword);
echo "<input type='checkbox' name='checkbox' value='$keyword'>$keyword ";
}
}
?>
Thanks!

Related

i want to search filter my database values using checkboxes php mysql

by using this code i can now fetch pro_price table but i need multiple column saerch. this is my working code for an solo column, but i need to fetch two column more from that table. How i can i do that. please help
Database name: auction
Table name : addproduct
Column names : pro_price, pro_code, hsn_code
This is my code,
if(isset($_REQUEST['search'])){
$pro_price = $_REQUEST['pro_price'];
foreach ($_REQUEST['pro_price'] as $pro_price) {
$statearray[] = mysql_real_escape_string($pro_price);
}
$states = implode ("','", $statearray);
$sql = "SELECT * FROM addproduct WHERE pro_price IN ('$states'))";
$result = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($result) == 0)
{
echo "Sorry, but we can not find an entry to match your query...<br><br>";
}
else
{
echo "<table border='1' width='900' class='srchrslt'>
<tr class='head'>
<td>pro_name</td>
<td>pro_brand</td>
<td>hsn_code</td>
<td>pro_tax2</td>
<td>pro_tax3</td>
</tr>";
while($row = mysql_fetch_assoc( $result ))
{
echo "<tr>";
echo "<td>" . $row['pro_name'] . " </td>";
echo "<td>" . $row['pro_brand'] . " </td>";
echo "<td>" . $row['hsn_code'] . " </td>";
echo "<td>" . $row['pro_tax2'] . " </td>";
echo "<td>" . $row['pro_tax3'] . " </td>";
echo "</tr>";
}
echo "</table>";
}
}
please help...and thank you
You do a SELECT *, which returns all columns in a table. In your case, it seems there's only a single column, so either you need to add additional columns to the table, or alternatively, you need to figure out whether perhaps you have not been granted permissions to see all columns in the table.
UPDATE:
It seems what you really want to do is add additional search criteria. This would mean your query would become something like the following:
SELECT * FROM addproduct WHERE pro_price IN ('$states') OR pro_code IN ('$codes')
For that to work, you would have to do what you already with the selected prices (i.e. store them i a variable called $states). In the SQL line above, I assume you store the selected values of the codes in a similar variable called $codes.
The full code with this addition would be something like tis:
if(isset($_REQUEST['search'])){
$pro_price = $_REQUEST['pro_price'];
$pro_code = $_REQUEST['pro_code'];
foreach ($_REQUEST['pro_price'] as $pro_price) {
$statearray[] = mysql_real_escape_string($pro_price);
}
foreach ($_REQUEST['pro_code'] as $pro_code) {
$codesarray[] = mysql_real_escape_string($pro_code);
}
$states = implode ("','", $statearray);
$codes = implode ("','", $codesarray);
$sql = "SELECT * FROM addproduct WHERE pro_price IN ('$states') OR pro_code IN ('$codes')";
Note that I'm not a PHP coder, so it is entirely possible the code can be optimized. I just wanted to show you what I think would work.
At last I got the solutions to my question. Thanks to #SchmitzIT who had supported me. Iam posting the code for further candidates.
index.php
<form name="search" method="post" action="searchplant">
<table width="900" border="1" class="srch">
<tr class="head"><td>Pro Price</td></tr>
<tr>
<td>
<input type="checkbox" value="250" name="pro_price[]">250<br />
<input type="checkbox" value="80" name="pro_price[]">80<br />
<input type="checkbox" value="50" name="pro_price[]">50<br />
<input type="checkbox" value="40" name="pro_price[]">40<br />
<input type="checkbox" value="299" name="pro_price[]">299<br />
<td>
</tr>
<tr class="head"><td>hsncode</td></tr>
<tr>
<td>
<input type="checkbox" value="101101" name="hsn_code[]">101101<br />
<input type="checkbox" value="101102" name="hsn_code[]">101102<br />
<input type="checkbox" value="101103" name="hsn_code[]">101103<br />
<input type="checkbox" value="101104" name="hsn_code[]">101104<br />
<input type="checkbox" value="101105" name="hsn_code[]">101105<br />
<td>
</tr>
<tr class="head"><td>procode</td></tr>
<tr>
<td>
<input type="checkbox" value="101" name="pro_code[]">101<br />
<input type="checkbox" value="102" name="pro_code[]">102<br />
<input type="checkbox" value="103" name="pro_code[]">103<br />
<input type="checkbox" value="104" name="pro_code[]">104<br />
<input type="checkbox" value="105" name="pro_code[]">105<br />
<td>
</tr>
<tr><td colspan="3" align="Right">
<input type="submit" name="search" value="Search" /></td></tr>
</table>
</form>
</div><!-- end service-->
<div id="media" class="group">
search.php
if(isset($_REQUEST['search']))
{
$pro_price = $_REQUEST['pro_price'];
$pro_code = $_REQUEST['pro_code'];
$hsn_code = $_REQUEST['hsn_code'];
foreach ($_REQUEST['pro_price'] as $pro_price) {
$statearray[] = mysql_real_escape_string($pro_price);
}
foreach ($_REQUEST['pro_code'] as $pro_code) {
$codesarray[] = mysql_real_escape_string($pro_code);
}
foreach ($_REQUEST['hsn_code'] as $hsn_code) {
$hsnarray[] = mysql_real_escape_string($hsn_code);
}
$states = implode ("','", $statearray);
$codes = implode ("','", $codesarray);
$hsn = implode ("','", $hsnarray);
$sql = "SELECT * FROM addproduct WHERE pro_price IN ('$states') OR pro_code IN ('$codes') OR hsn_code IN ('$hsn')";
//Now we search for our search term, in the field the user specified
$result = mysql_query($sql) or die(mysql_error());
//This counts the number or results - and if there wasn't any it gives them a little message explaining that
if (mysql_num_rows($result) == 0)
{
echo "Sorry, but we can not find an entry to match your query...<br><br>";
}
else
{
echo "<table border='1' width='900' class='srchrslt'>
<tr class='head'>
<td>pro_name</td>
<td>pro_brand</td>
<td>hsn_code</td>
<td>pro_price</td>
<td>pro_code</td>
</tr>";
//And we display the results
while($row = mysql_fetch_assoc( $result ))
{
echo "<tr>";
echo "<td>" . $row['pro_name'] . " </td>";
echo "<td>" . $row['pro_brand'] . " </td>";
echo "<td>" . $row['hsn_code'] . " </td>";
echo "<td>" . $row['pro_price'] . " </td>";
echo "<td>" . $row['pro_code'] . " </td>";
echo "</tr>";
}
echo "</table>";
}
}
Just change the database name, table name, column name and values according to your data.
Hope you find this useful

PHP submit buttons/structure?

here is a bit of code im working on. Everything works expect that part where i enter ID, then it shows me information in that ID row and also 2 boxes pop where i can write new value of variable. There is also 2 buttons, one which comfirms the edit which has been written into boxes and second one to delete that row from database.
Im still at kinda basics at programming as you can see and im quessing there is something wrong with structure in this part of code?
Can anyone help me to make these 2 submit buttons work as they should.
Thanks you all. :)
if(isset($_POST['idnumber'])) {
$idnumber = protect($_POST['idnumber']);
global $idnumber;
if($idnumber == ""){
echo "Please supply all fields!";
}
else{
?>
<table cellpadding="2" cellspacing="2">
<br />
<tr>
<td width="50px"><b>ID</b></td>
<td width="150px"><b>Current name</b></td>
<td width="200px"><b>Current description</b></td>
<td width="100px"><b>Time added</b></td>
<td width="100px"><b>Current status</b></td>
</tr>
<?php
$get_tasks = mysqli_query($con, "SELECT id FROM task WHERE id='$idnumber'") or die(mysql_error());
while($row = mysqli_fetch_assoc($get_tasks)){
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
$get_taskname = mysqli_query($con, "SELECT taskname FROM task WHERE id='$idnumber'") or die(mysql_error());
$task_name = mysqli_fetch_assoc($get_taskname);
echo "<td>" . $task_name['taskname'] . "</td>";
$get_description = mysqli_query($con, "SELECT description FROM task WHERE id='$idnumber'") or die(mysql_error());
$description_text = mysqli_fetch_assoc($get_description);
echo "<td>" . $description_text['description'] . "</td>";
$get_dateadded = mysqli_query($con, "SELECT dateadded FROM task WHERE id='$idnumber'") or die(mysql_error());
$date_added = mysqli_fetch_assoc($get_dateadded);
echo "<td>" . $date_added['dateadded'] . "</td>";
$get_status = mysqli_query($con, "SELECT status FROM task WHERE id='$idnumber'") or die(mysql_error());
$cur_status = mysqli_fetch_assoc($get_status);
if($cur_status['status'] == 1) {
echo "<td>" . "Unfinished" . "</td>";
}
else{
echo "<td>" . "Finished" . "</td>";
}
echo "</tr>";
}
if(isset($_POST['edittask'])) {
$editname = protect($_POST['editname']);
mysqli_query($con, "UPDATE task SET taskname=$editname WHERE id='$idnumber'") or die(mysql_error());
}
elseif(isset($_POST['deletetask'])) {
mysqli_query($con, "DELETE FROM task WHERE id='$idnumber'") or die(mysql_error());
}
?>
<form action="test2.php" method="POST" >
<td width="50px"><b></b></td>
<td width="150px"><b>New name: <input type="text" name="editname"/></b></td>
<td width="200px"><b>New desc: <input type="text" name="editdesc"/></b></td>
<td width="100px"><b></b></td>
<td width="100px"><b>D</b></td>
<input type="submit" name="edittask" value="Edit task"/> <br />
<input type="submit" name="deletetask" value="Delete task"/> <br />
</form>
<?php
}
}
?>
</table>
<br /><br />
<form action="test2.php" method="POST" >
Insert ID of task to edit: <input type="text" name="idnumber"/>
<input type="submit" name="ids" value="Find task"/> <br />
</form>

HTML PHP check box

How can I style my code so that the check box can be aligned beside the table.
All of the check boxes are appearing above the table, but not beside it.
Consider the following snippet of code as well as the picture attached at the end.
<html>
<head>
<title> Furni checker </title>
</head>
<body>
<h1>Furniture Lookup / Furniture Checker</h1> <br />
<br /><p>This tool is used for removal or check furniture on a user account.</p> <br />
<h2> Instructions : </h2> <br />
<p> Lookup User ID and Lookup for the Furniture! </p>
<?php
require_once "global.php";
echo '<h1>Furniture Lookup / Furniture Checker</h1>
<br /><p>This tool is used for removal or check furniture on a user account.</p>';
echo '<br />
<form method="post">
Username:
<input type="text" name="user">
<input type="submit" value="Lookup">
</form>';
if (isset($_POST['user'])) {
$user = filter($_POST['user']);
$getUser = dbquery("SELECT * FROM users WHERE users.username = '" . $user . "' ");
while($show1 = mysql_fetch_array($getUser)) {
echo ''. $show1['id']. '';
}
}
?>
<br />
<?php
echo '
<form method="post">
ID:
<input type="text" name="id">
<input type="submit" value="Lookup">
</form>';
if (isset($_POST['id'])) {
$id = filter($_POST['id']);
$getFurniture = dbquery("SELECT public_name FROM furniture JOIN items ON items.base_item = furniture.id WHERE items.user_id = '" . $id . "' ORDER BY public_name ASC ");
echo '<table border=1 cellpadding=1 width="10%">';
while($show = mysql_fetch_array($getFurniture)) {
//echo ''. $show['public_name'].'' ;
echo '<tr class="t_row">';
echo '<input type="checkbox"> <td>' .$show['public_name']. '</td>';
echo '</tr>';
}
echo '</input>';
echo '</table>';
}
?>
Image:
Try this:
<?php
if (isset($_POST['submit']))
{
$id = filter($_POST['id']);
$getFurniture = dbquery("SELECT public_name FROM furniture JOIN items ON items.base_item = furniture.id WHERE items.user_id = '" . $id . "' ORDER BY public_name ASC ");
echo '<table border=1 cellpadding=1 width="10%">';
while($show = mysql_fetch_array($getFurniture)){
//echo ''. $show['public_name'].'' ;
echo '<tr class="t_row">';
echo '<td>' .$show['public_name']. '</td><td><input type="checkbox" /> </td>';
echo '</tr>';
}
echo '</table>';
}
?>
Let me know if it's not working.

Use Delete Button to Delete Record from Database

I have a database containing books. On a page, I have loop that prints each record in the database which each book's title, author, publisher, date, and rating. I want to use a delete button at the bottom of each record in order to delete it.
When I click on the delete button, the page is updated, but the record is not deleted.
I have tried to find solutions to this problem, but have yet to. I tried to use the book_id category in my database table as my index, in order to identify each record and delete it but it does not work.
Here is the code for my button form, as it appears with html code:
while ($row = mysqli_fetch_array($result))
{
echo '<div id="forminput">';
$timestamp = strtotime($row['date']);
echo '<div id = "bookpicture">';
echo '<img src="images/Book Cover 8crop.jpg" alt="Book Cover">';
echo '</div>';
echo '<div id = "bookinfo">';
echo '<div id = "titleauthor">';
echo '<h3>' . htmlspecialchars($row['title'], ENT_QUOTES, 'UTF-8') . '</h3>';
echo '<p>' . htmlspecialchars($row['author'], ENT_QUOTES, 'UTF-8') . '</p>';
echo '</div>';
echo '</div>';
$id = htmlspecialchars($row['book_id'], ENT_QUOTES, 'UTF-8');
echo '</div>' ;
echo '<div id = "publisher">' ;
echo '<p>' . 'Published on' . " " . htmlspecialchars(date('F j, Y,', $timestamp),
ENT_QUOTES, 'UTF-8') .
" " . 'by' . " " . htmlspecialchars($row['publisher'], ENT_QUOTES, 'UTF-8') . '</p>';
echo '</div>';
echo '<div id = "formDelete">';
echo '<form name="deleteForm" method="post" id="deleteForm" action="index.php">';
echo '<input type="submit" value="Update" name="myAdd" id="myAdd" style = "width:
100px" required>';
echo '<input type="submit" value="Delete" name="myDelete" id="$id" style = "width:
100px" required>';
echo '</form>';
echo '</div>';
echo '</div>';
echo '<hr>' ;
echo '</div>';
}
?>
Here is the code from my index.php file.
else if (isset($_POST['myDelete']))
{
$ids = mysqli_real_escape_string($link, $_POST['$id']);
$sql="DELETE FROM readbooks WHERE book_id = '$ids'";
if (!mysqli_query($link, $sql))
{
$error = 'Error with submission: ' . mysqli_error($link);
include 'php/error.html.php';
exit();
}
}
Here is the updated code.
The Problem is you are not trying to send the row ID from the form.
In Form try sending row id from the form
echo '<input type="hidden" name="id" value="$id">'
try receiving that parameter
$id = $_POST['id'];
$con = mysql_connect("host address","mysql_user","mysql_pwd");
$query = "DELETE FROM readbooks WHERE id = $id";
mysql_query($query,$con);
Moving from comment, you're not actually getting the $id anywhere. Add a field to your form:
<input type='hidden' name='id' value='$id'>
and then refer to it in your php:
$ids = mysqli_real_escape_string($link, $_POST['id']);
Since your using mysqli now, use prepared statements. Do not directly use your user input to the query! Example:
$books = array();
// connection
$con = new mysqli('localhost', 'your_username', 'password_of_username', 'your_database');
if(isset($_POST['myDelete'])) {
$book_id = $_POST['myDelete']; // get the variable id
$stmt = $con->prepare('DELETE FROM readbooks WHERE book_id = ?');
$stmt->bind_param('i', $book_id);
$stmt->execute();
}
$result = mysqli_query($con, 'SELECT * FROM readbooks');
while($row = $result->fetch_assoc()) {
$books[] = $row;
}
?>
<form method="POST">
<table border="1" cellpadding="10">
<tr>
<th>Title</th>
<th>Author</th>
<th>Publisher</th>
<th></th>
</tr>
<?php foreach($books as $book): ?>
<tr>
<td><?php echo $book['title']; ?></td>
<td><?php echo $book['author']; ?></td>
<td><?php echo $book['publisher']; ?></td>
<td><button type="submit" name="myDelete" value="<?php echo $book['book_id']; ?>">Delete</button></td>
</tr>
<?php endforeach; ?>
</table>
</form>
I think you're having problem with the id that you are passing to your PHP code. Try to use var_dump($_POST) to see what is the content of your $_POST variable. As I can see, the index of $_POST is wrong.
<input type="submit" value="Delete" name="myDelete" id="$id" style = "width:100px" required>';
Try to change this to
<input type="submit" name="book_id" value="$id" style = "width:100px" required>';
In your php use this $_POST["book_id"] to get the value of book_id you posted.
Note : The attribute "name" of the input tags will be the index of your $_POST variable
I understand that you want to have a delete and update button at the same time. The problem is your logic behind the situation. You need to have a hidden field and put the id inside it. Try to use this.
echo '<form name="deleteForm" method="post" id="deleteForm" action="index.php">';
echo '<input type="hidden" value="$id" name="book_id" id="myAdd" required>';
echo '<input type="submit" value="Update" name="action" id="myAdd" required>';
echo '<input type="submit" value="Delete" name="action" id="$id" required>';
echo '</form>';
In your php code use try to have a condition like this :
$book_id = $_POST["book_id"];
if($_POST["action"] == "delete")
{
//do your deletion code here. use the variable $book_id
}
else{
//do your update code here.use the variable $book_id
}

Saving data from a checkbox using PHP and MySQL

Here is my code:
while($row = mysqli_fetch_array($result))
{
$id = $row['id'];
$description = $row['description'];
$picturepath = $row['picturepath'];
$name = $row['name'];
$price = $row['price'];
$keywords = $row['keywords'];
$dynamiclist = '<table align="center" width="60%" border="0" cellspacing="5" cellpadding="8">
<tr height="20"></tr>
<tr>
<td width="70%" valign="top" align="left"> <br />' . $name . ' <br /><br />$' . $price . '<br /><br />
<form id="form1" name="form1" method="post" action="cart.php">
<input type="hidden" name="pid" id="pid" value=" ' . $name . ' - $' . $price . ' - "checkbox"/>';
echo $dynamiclist;
foreach(explode(',', $keywords) as $keyword) {
$keyword = trim($keyword);
echo "<input type='checkbox' name='checkbox' value='$keyword'>$keyword <br /><br />";
}
echo '<input type="submit" name="button" id="button" value="Add to Order"/> </form> </td></tr></table>';
}
mysqli_close($con); //close the db connection
The code pulls in an item using the items id, and then creates checkboxes and keywords for that item. A user is to click on the checkbox options they want and then submit the form which sends the information to the shopping cart. The problem is that when the form is submitted, only the name and price of the item is sent over, but not the checkbox options that were clicked. Can you help me identify why? Side note. In my database I have a column "keywords" where multiple keywords are stored. // medium, well, rare, milk, apple juice, fries. Also, on the cart.php the I have:
if(isset($_POST['pid'])){
$pid = $_POST['pid'];
which posts the data from the script using the checkboxes. I'm just stuck and can't get any further.
You should have different name for your checkbox:
while($row = mysqli_fetch_array($result))
{
$id = $row['id'];
$description = $row['description'];
$picturepath = $row['picturepath'];
$name = $row['name'];
$price = $row['price'];
$keywords = $row['keywords'];
$dynamiclist = '<table align="center" width="60%" border="0" cellspacing="5" cellpadding="8">
<tr height="20"></tr>
<tr>
<td width="70%" valign="top" align="left"> <br />' . $name . ' <br /><br />$' . $price . '<br /><br />
<form id="form1" name="form1" method="post" action="cart.php">
<input type="hidden" name="pid" id="pid" value=" ' . $name . ' - $' . $price . ' - "checkbox"/>';
echo $dynamiclist;
$i=0;
foreach(explode(',', $keywords) as $keyword) {
$keyword = trim($keyword);
$chkname = "checkbox{$i}";
$i = $i+1;
echo "<input type='checkbox' name='$chkname' value='$keyword'>$keyword <br /><br />";
}
echo '<input type="submit" name="button" id="button" value="Add to Order"/> </form> </td></tr></table>';
}
mysqli_close($con); //close the db connection
You need to get checkbox data in the cart.php like this:
if($_REQUEST['checkbox0']) echo $_REQUEST['checkbox0'];
if($_REQUEST['checkbox1']) echo $_REQUEST['checkbox1'];
//so on foreach checkbox
Your checkboxes need to have different names, otherwise the values are overwritten:
<input type="checkbox" name="keyword1" value="keyword1">Keyword1
<input type="checkbox" name="keyword2" value="keyword2">Keyword2
<input type="checkbox" name="keyword3" value="keyword3">Keyword3
You then access them in PHP like so:
if ( isset($_GET['keyword1']) ) {
}
if ( isset($_GET['keyword2']) ) {
}
if ( isset($_GET['keyword3']) ) {
}
A more logical way to manage the data is to pass the checkbox values as an array:
<input type="checkbox" name="keyword[]" value="keyword1">Keyword1
<input type="checkbox" name="keyword[]" value="keyword2">Keyword2
<input type="checkbox" name="keyword[]" value="keyword3">Keyword3
It then becomes much easier to work with the data in PHP;
if ( isset($_GET['keyword']) && is_array($_GET['keyword']) ) {
foreach ( $_GET['keyword'] as $v ) {
}
}

Categories