php select multiple checkboxes - php

i have this code, which helps me to retrieve all table fields and associate a check button to them, but this code is generating the same name, i mean it shows me all the fields, but named the same... id
I need their particulatr name..
can you please see what's wrong?
Thanks..
<form action='report.php' method='post'>
<?php // Script 12.7 - sopping.php
$db = mysql_connect('localhost', 'root', '');
mysql_select_db('db_up', $db);
echo "<table border='1' class='tabtext'>";
$result = mysql_query("SELECT * FROM hostess");
$numrows = mysql_num_rows($result);
$numfields = mysql_num_fields($result);
// show headers
echo '<thead><tr>';
for ($field = 0; $field < $numfields; $field++) {
$field_name = mysql_field_name($result, $field); // instead of $i
echo '<th><label><input type="checkbox" name="checkbox[' . $field_name . ']" value="1"/> ' . $field_name . '</label></th>';
}
echo '</tr></thead>';
echo '<tbody>';
for ($row = 0; $row < $numrows; $row++) {
$data = mysql_fetch_assoc($result);
echo '<tr>';
for ($field = 0; $field < $numfields; $field++) {
$field_name = mysql_field_name($result, $field);
if (isset($_POST['checkbox'][$field_name])) {
echo '<td>' . $data[$field_name] . '</td>';
}
}
echo '</tr>';
}
echo '</tbody>';
echo '</table>';
?>
<input type='submit' value='Submit' />
</form>

The second argument of the mysql_field_name function isn't defined so I am pretty sure PHP is assuming you mean 0 and is returning the first fieldname only. Use the variable you defined ($field) as the index.
Should be:
for ($field = 0; $field < $numfields; $field++) {
$field_name = mysql_field_name($result, $field); // instead of $i
echo '<th><label><input type="checkbox" name="checkbox[' . $field_name . ']" value="1"/> ' . $field_name . '</label></th>';
}

You are using mysql_field_name and it always return the same name for you(for column 0), because $i is not defined.

Related

Setting up different options and getting their values

I'm using the following code to add various select elements to my page. However, as I'm doing this in a while loop, the value for all the elements is the same
function options($pos, $count) {
for ($i = 0; $i < $count; $i++) {
$options = '';
$STH = //code to get data from db
$STH->execute();
while($row2 = $STH->fetch()) {
$options .="<option>" . $row2['name'] . "</option>";
}
$menu= "<select name='filter' id='filter'>
" . $options . "
</select>";
echo $menu;
}
}
I then need to get the value of each of the select element after the user presses a button. But as the name for each select element is the same I don't know how to do this. Is there any way around this problem?
For eg, If the count is 5, five separate drop down lists will be created (even though the options in each of them are identical). The user then selects the options relevant to him and presses the submit button. I then need to get the values that he chose from the dropdown menus but I can't figure out how to do this as the name for all the dropdown menus is the same
Assuming you have many select tags with dynamic options
Solution is to make your name of select tag different(dynamic)
<form method="POST">
<?php
cust_options(5);
function cust_options($count) {
for ($i = 0; $i < $count; $i++) {
$options = '';
$j = 1;
while($j < 4) {
$options .="<option>" . 'option'.$j . "</option>";
$j++;
}
$ind = $i+1;
$temp = 'filter_'.$ind;
$menu= "<select name='$temp'>
" . $options . "
</select>";
echo $menu;
}
}
?>
<input type="submit">
<?php print_r($_POST); ?>
</form>
You should do something like this :
<select name='filter' id='filter'>
<?php
while($row2 = $STH->fetch()) {
$options .="<option>" . $row2['name'] . "</option>";
} ?>
</select>";

PHP: Show data from mysql database in table

I am new to php and trying to fetch data from database and trying to show it in html table. My issue is total number of returned record is 13 but in table it is just showing 12 record( it is skipping first record in html table) my code snippt is as below
$num_rows = mysql_num_rows($result);
echo $num_rows;
if ($num_rows > 0) {
$i = 0;
$dyn_table = '<table class="gridData">';
$dyn_table.= '<th>Mil Purchy</th><th>Next Mil Purchy</th><th>total Missing</th><th>Missing From-To</th>';
for ($x = 0; $x <= $num_rows; $x++) {
while ($row = mysql_fetch_array($result)) {
if ($i % 1 == 0) {
// if $i is divisible by our target number (in this case "3")
echo "<script> alert('$i') </script>";
$dyn_table.= '<tr><td>' . $row[0] . '</td>';
$dyn_table.= '<td>' . $row[1] . '</td>';
$dyn_table.= '<td>' . $row[2] . '</td>';
$dyn_table.= '<td>' . $row[3] . '</td>';
} else {
echo "<script> alert ('in else statement') </script>";
}
$i++;
}
$dyn_table.= '</tr></table>';
}
echo $dyn_table;
}
and on submit button I have written following code
<fieldset>
<?php
if ($_GET) {
if (ISSET($_GET['submit'])) {
// echo "<script> alert('waiting for function') </script>";
$From_Date = $_GET['DateFrom'];
$To_Date = $_GET['DateTo'];
Sequece($From_Date, $To_Date);
}
}
?>
</fieldset>
before anything it is important that you use mysqli() functions instead of mysql() because mysql() function series are being departed from php. Also you missed some <tr> and </tr>s. so here is your fixed code:
<?php $num_rows = mysqli_num_rows($result);
echo $num_rows;
if($num_rows > 0){
$i = 0;
$dyn_table = '<table class="gridData">';
$dyn_table .= '<tr><th>Mil Purchy</th><th>Next Mil Purchy</th><th>total Missing</th><th>Missing From-To</th>';
while($row = mysqli_fetch_array($result))
{
if ($i % 1 == 0) { // if $i is divisible by our target number (in this case "3")
echo "<script> alert('$i') </script>";
$dyn_table .= '</tr><tr><td>' .$row[0] . '</td>';
$dyn_table .= '<td>' .$row[1]. '</td>';
$dyn_table .= '<td>' .$row[2]. '</td>';
$dyn_table .= '<td>' .$row[3]. '</td>';
} else {
echo "<script> alert ('in else statement') </script>";
}
$i++;
}
$dyn_table .= '</tr></table>';
echo $dyn_table;
}?>
Also you are creating many <script> inside the <table> structure code, it is not wrong and it works but it is bad HTML so I recommend that you store all <script>s in an array and after creation of table, print out the array. any by the way, why sending many alerts? why not only print the alerts only?
Database is returning correct records that is 12.
You made a mistake in the following line of code:-
for ( $x = 0; $x<= $num_rows; $x++){
Simply replace above code block with the following one:-
for ( $x = 0; $x < $num_rows; $x++){
Here you are trying to get ($num_rows + 1) = 13 records from the database that's why you are not getting data for last record that is 13.
You do not need a for loop. Your while loop will stop when there are no more records. That's why it's there.
Remove for loop and check it may be work.
$num_rows = mysql_num_rows($result);
echo $num_rows;
if ($num_rows > 0)
{
$i = 0;
$dyn_table = '<table class="gridData">';
$dyn_table.= '<th>Mil Purchy</th><th>Next Mil Purchy</th><th>total Missing</th><th>Missing From-To</th>';
while ($row = mysql_fetch_array($result)) {
if ($i % 1 == 0)
{
// if $i is divisible by our target number (in this case "3")
echo "<script> alert('$i') </script>";
$dyn_table.= '<tr><td>' . $row[0] . '</td>';
$dyn_table.= '<td>' . $row[1] . '</td>';
$dyn_table.= '<td>' . $row[2] . '</td>';
$dyn_table.= '<td>' . $row[3] . '</td>';
}
else
{
echo "<script> alert ('in else statement') </script>";
}
$i++;
}
$dyn_table.= '</tr></table>';
echo $dyn_table;
}
13 will not divisible by 3 so it only shows 12 results
<?php
$num_rows = mysql_num_rows($result);
echo $num_rows;
if ($num_rows > 0) {
$i = 0;
$dyn_table = '<table class="gridData">';
$dyn_table .= '<th>Mil Purchy</th>
<th>Next Mil Purchy</th>
<th>total Missing</th>
<th>Missing From-To</th>';
while ($row = mysql_fetch_array($result)) {
if ($i % 1 == 0) { // if $i is divisible by our target number (in this case "3")
echo "<script> alert('$i') </script>";
$dyn_table .= '<tr><td>' . $row[0] . '</td>';
$dyn_table .= '<td>' . $row[1] . '</td>';
$dyn_table .= '<td>' . $row[2] . '</td>';
$dyn_table .= '<td>' . $row[3] . '</td>';
} else {
echo "<script> alert ('in else statement') </script>";
}
$i++;
}
$dyn_table .= '</tr></table>';
echo $dyn_table;
}?>

Insert array values into mysql database

The variables are being posted from a previous page through array values.
when I print_r($values) I get the whole value on this array including the numerical values of the array ex: array[0], array[1] ..etc.
Please can some tell me what I am doing wrong. the implode function was not used because the values are passed from a cart page though session variables.
First part of code below:
<?php
$current_url = base64_encode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
if(isset($_SESSION["products"]))
{
$total = 0;
echo '<form method="post" action="process.php">';
echo '<ul>';
$cart_items = 0;
foreach ($_SESSION["products"] as $cart_itm)
{
$product_code = $cart_itm["code"];
$results = $mysqli->query("SELECT Title,Description,Price FROM main_menu WHERE MenuID='$product_code' LIMIT 1");
$obj = $results->fetch_object();
echo '<li class="cart-itm">';
echo '<span class="remove-itm">×</span>';
echo '<div class="p-price">'.$currency.$obj->Price.'</div>';
echo '<div class="product-info">';
echo '<h3>'.$obj->Title.' (Code :'.$product_code.')</h3> ';
echo '<div class="p-qty">Qty : '.$cart_itm["qty"].'</div>';
echo '<div>'.$obj->Description.'</div>';
echo '</div>';
echo '</li>';
$subtotal = ($cart_itm["price"]*$cart_itm["qty"]);
$total = ($total + $subtotal);
echo '<input type="hidden" name="item_name['.$cart_items.']" value="'.$obj->Title.'" />';
echo '<input type="hidden" name="item_code['.$cart_items.']" value="'.$product_code.'" />';
echo '<input type="hidden" name="item_desc['.$cart_items.']" value="'.$obj->Description.'" />';
echo '<input type="hidden" name="item_qty['.$cart_items.']" value="'.$cart_itm["qty"].'" />';
$cart_items ++;
}
echo '</ul>';
echo '<span class="check-out-txt">';
echo '<strong>Total : '.$currency.$total.'</strong> ';
echo '<input name=\'submit\' type="submit" value="Complete Order" style=\"width:150px;background:#333;color:#ffcc33;height:30px;\" />';
echo '</span>';
echo '</form>';
}else{
echo 'No items added';
}
?>
Second part:
Try $post and the table name in the given function and use mysql_real_escape_string() to avoid any possibility of the SQL Injection
form.php
<?php
include ('func_curd.php') ;
if($_POST['hiddenfieldinfo']=='ok')
{
$r=insert_your_table_name($_POST);
if($r==true)
{
header('Location:'.get_full_url()); /* to redirect the form to the same page after successful submission*/
}
}
?>
func_curd.php
<?php
function insert_your_table_name($post)
{
unset($post['hiddenfieldinfo']);
/* Here I am unsetting this value as it is hidden field
in the form , which I am using as form submission check and
is not in database column, apart form auto-increment in database
that is id, you have to maek sure all the post value and column
name matches with case-sensitivities */
$u = insert('your_table_name', $post);
$r=is_numeric($u)? true : false ;
return $r;
}
function insert($table, $values){
$query="INSERT INTO `$table` ";
$column='(';
$val=' (';
$count=count($values);
$mk=1;
foreach ($values as $key=>$value)
{
$value=mysql_real_escape_string($value);
if ($mk==$count)
{
$column .= '`'.$key.'`';
$val .= "'".$value."'";
}
else
{
$column .= '`'.$key.'`, ';
$val .= "'".$value."', ";
}
$mk++;
}
$column .=') ';
$val .=')';
$query=$query.$column.'VALUES'.$val;
$Q=mysql_query($query);
if(mysql_error())
{
return print(mysql_error());
}
else
{
$insert_id=mysql_insert_id();
return $insert_id;
}
}
?>
try this one:
<?php
require_once('config/connect.php');
$item_name = strip_tags($_POST['item_name']);
$item_code = strip_tags($_POST['item_code']);
$item_desc = strip_tags($_POST['item_desc']);
$item_qty = strip_tags($_POST['qty']);
$price = strip_tags($_POST['price']);
$fields = "item_name, item_code, item_desc, price,qty";
$query = "INSERT INTO `x` SET ";
$i = 0;
foreach( $fields as $fieldname )
{
if ( $i > 0 )
$query .= ", ";
$val = strip_tags($_POST[$fieldname]);
$query .= "`" . $fieldname . "` = '" . $val . "'"
$i++
}
$query_result = mysql_query($query);
echo" Record saved";
print_r ( $query );
?>
There are certain syntax errors in your code like not closed foreach etc. whihc I did skip.
As a recommendation: code like this is disclosing the database structure to everyone on the internet - form field names = database col names. This is generally a bad idea.
Better is a kind of mapping table:
$fields = array (
'myFormName' => 'mySqlName',
....
foreach( $fields as $fieldname => $sqlame)
{
if ( $i > 0 )
$query .= ", ";
$val = strip_tags($_POST[$fieldname]);
$query .= "`" . $sqlname. "` = '" . $val . "'"
....
which also will make the form more independent from the underlying data structures.

Adding an Extra Empty Column While Reading An .xlsx file in PHP

I edited a PHP code that reads an Excel Spreadsheet (.xlsx form) and displays it very well.
But I want an extra column to be added when PHP page displays the Spreadsheet. (For textareas to update one cell in each row.)
What can I do for it?
Thanks.
<?php
if((!empty($_FILES["file"])) && ($_FILES['file']['error'] == 0)) {
$limitSize = 15000000;
require_once "simplexlsx.class.php";
$getWorksheetName = array();
$xlsx = new SimpleXLSX( $_FILES['file']['tmp_name'] );
$getWorksheetName = $xlsx->getWorksheetName();
echo ' <hr>
<div id="datacontent">
';
'<div id="datacontent">';
for($j=1;$j <= $xlsx->sheetsCount();$j++){
echo '<h3>Tablodaki Worksheet: '.$getWorksheetName[$j-1].'</h1>';
echo '<table id="xlsxTable">';
list($cols,) = $xlsx->dimension($j);
foreach( $xlsx->rows($j+1) as $k => $r) {
if ($k == 0){
$trOpen = '<th';
$trClose = '</th>';
$tbOpen = '<thead>';
$tbClose = '</thead>';
}else{
$trOpen = '<td';
$trClose = '</td>';
$tbOpen = '<tbody>';
$tbClose = '</tbody>';
}
echo $tbOpen;
echo '<tr>';
for( $i = 0; $i < $cols; $i++)
echo $trOpen.'>'.( (isset($r[$i])) ? $r[$i] : ' ' ).$trClose;
echo '</tr>';
echo $tbClose;
}
echo '</table>';
}
}
?>

Need help with incrementing 2 variables in post form

I'm trying to allow a user to edit a row of their data with POST from a displayed form. The query is working and the table properly displays everything except a name value in the form input field. I've tried numerous variations but the name value keeps coming up blank. The problem might be with this line:
echo $field_name;
Here is the code:
<form action="process.php" method="POST">
<?
$qry = "SELECT activity, site, date, FROM home WHERE user_id='$session->user_id' ORDER BY date";
$res = mysql_query($qry);
$field_name = mysql_field_name($res, 0);
function mysql_fetch_all($res) {
while($row=mysql_fetch_array($res)) {
$return[] = $row;
}
return $return;
}
function create_table($dataArr) {
echo "<form action=\"process.php\" method=\"POST\"><table><tr>";
for($j = 0; $j < 3; $j++) {
echo "<td><input type=\"text\" name=\"";
echo $field_name;
echo "\" maxlength=\"30\" value=" .$dataArr[$j]. "></td>";
}
echo "<td><input type=\"hidden\" name=\"subedit\" value=\"1\"><input type=\"submit\" value=\"Update\"></td></tr></table></form>";
}
$all = mysql_fetch_all($res);
echo "<table class='data_table'>";
echo "<tr><td colspan=\"3\"><h2>Current Profile</h2></td></tr>";
echo "<tr><small><td>Activity </td><td>Site </td><td>Date </td></small></tr>";
for($i = 0; $i < count($all); $i++) {
create_table($all[$i]);
}
echo "</table></form>";
$field_name is out of scope (check out PHP's variable scope page). Try changing your create_table function to accept the $field_name var like so:
function create_table($dataArr, $field_name) {
...
}
...
for($i = 0; $i < count($all); $i++) {
create_table($all[$i], $field_name);
}
Or using global (not as recommended)
function create_table($dataArr) {
global $field_name;
...
}
Try this code:
<form action="process.php" method="POST">
<?
$qry = "SELECT activity, site, date, FROM home WHERE user_id='$session->user_id' ORDER BY date";
$res = mysql_query($qry);
$field_name = mysql_field_name($res, 0);
function mysql_fetch_all($res) {
while($row=mysql_fetch_array($res)) {
$return[] = $row;
}
return $return;
}
function create_table($dataArr, $field_name) {
echo "<form action=\"process.php\" method=\"POST\"><table><tr>";
for($j = 0; $j < 3; $j++) {
echo "<td><input type=\"text\" name=\"";
echo $field_name;
echo "\" maxlength=\"30\" value=" .$dataArr[$j]. "></td>";
}
echo "<td><input type=\"hidden\" name=\"subedit\" value=\"1\"><input type=\"submit\" value=\"Update\"></td></tr></table></form>";
}
$all = mysql_fetch_all($res);
echo "<table class='data_table'>";
echo "<tr><td colspan=\"3\"><h2>Current Profile</h2></td></tr>";
echo "<tr><small><td>Activity </td><td>Site </td><td>Date </td></small></tr>";
for($i = 0; $i < count($all); $i++) {
create_table($all[$i], $field_name);
}
echo "</table></form>";
However, I do recommend that you try to create a Table class. It would be much more efficient and neater.

Categories