I have while loop to get information from mysql table. But can't figure how to find las entry containing same factor_id and add append new element after it.
if ($this->_db->numRows() > 0) {
$i = 1;
$j = '';
$row = '';
while ($row = mysqli_fetch_assoc($res_info)) {
if ($row['task_factor_category'] != $j) {
$title = '<tr><td colspan="4" class="title" style="text-align: left;">' . $row['task_factor_category'] . '</td></tr>';
$comment = '<tr><td class="title" style="text-align: left" colspan="4">' . $this->_glan['comments'] . '</td></tr><tr><td colspan="4"><textarea cols="82" rows="3" name="factor_comment[' . $row['factor_id'] . ']" id="' . $row['factor_id'] . '"></textarea></td></tr>';
} else {
$title = false;
$comment = false;
}
$this->reg['edit_fields']['factors'] .= $title . '<tr>
<td>
' . $row['factors'] . '
</td>
<td>
<input type="radio" name="task_factor[' . $i . '_' . $row['factor_id'] . ']" value="1" />
</td>
<td>
<input type="radio" name="task_factor[' . $i . '_' . $row['factor_id'] . ']" value="2" checked />
</td>
<td>
<input type="radio" name="task_factor[' . $i . '_' . $row['factor_id'] . ']" value="3" />
</td>
</tr>
';
$j = $row['task_factor_category'];
$i++;
}
}
output is like:
//results with $row['factor_id'] = 10;
title
1. entry
2. entry
3. entry
4. entry
5. entry
//need new element here
//results with $row['factor_id'] = 11;
title
1. entry
2. entry
3. entry
4. entry
5. entry
//need new element here
......
I need to add additional element after the last entry containing same factor id
You may want to try this one.
$id = array();
$i = 0;
while ($row = mysqli_fetch_assoc($res_info))
{
$id[$i] = $row['id'];
if ($i != 0 && $id[$i-1] != $row['id']) {
//new element
} else {
//same element
}
$i++
}
you can count total rows suppose there are 7 rows
Add a if code in while loop like
while(cond)
{
if($i == 7 )
{
then echo("what ever you want");
}
}
Related
This question already has answers here:
Disabled form fields not submitting data [duplicate]
(4 answers)
Closed 4 years ago.
I am receiving this error (4 times) when attempting to submit a form table:
Notice: Undefined index: accountid in php/ChartOfAccountsInclude.php on >line 106
This is line 106 in my code
$account_id = $_POST["accountid"][$i];
I am attempting to load in table data from a local database. Then I allow the user access to certain fields to change the values. Once they are done they press the button to submit and that is when I get the above error. There are currently four accounts in the database which means each time my code is looping through the POST value it is failing to retrieve the accountid. I have pasted the relevant code below:
User Page ChartOfAccounts.php
<?php
include("view/SiteHeader.php");
include('php/ChartOfAccountsInclude.php');
?>
<html>
<head>
<title>Chart of Accounts</title>
</head>
<body>
<br/>
<h2>Chart of Accounts</h2>
<form action="" method="post">
<div>
<?php retrieveChart() ;?>
</div>
<div class="container">
<button type="submit" name="submitMods" class="btn btn-outline-secondary">Submit Account Modifications</button>
</div>
</form>
<?php if($submit_err) : ?>
<?php generateError('warning', 'Account could not be updated.') ?>
<?php endif; ?>
</body>
</html>
PHP Include ChartOfAccountsInclude.php
<?php
include_once('php/session.php');
$sql = "SELECT * FROM Accounts";
$result = mysqli_query($db,$sql);
$count = mysqli_num_rows($result);
$submit_err = FALSE;
$submitaccount_err = FALSE;
function retrieveChart() {
global $db;
$funcSQL = "SELECT * FROM Accounts";
$funcResult = mysqli_query($db,$funcSQL);
echo '<table border="1" class="table table-bordered table-hover">
<thead>
<tr>
<th>Account ID</th>
<th>Account Name</th>
<th>Date Created</th>
<th>Type</th>
<th>Term</th>
<th>Status</th>
<th>Created By</th>
</tr>
</thead>';
while($row = mysqli_fetch_array($funcResult))
{
$current = $longterm = $active = $inactive = $debi = $credit = $asset = $expense = $liability = $equity = $revenue = "";
$curusr = $row['user_id'];
$getUsernameSQL = "SELECT username FROM User_accounts WHERE user_id = $curusr";
$usernameResult = mysqli_query($db,$getUsernameSQL);
$usernameRow = mysqli_fetch_array($usernameResult);
switch ($row['term']) {
case 'Current':
$current = "selected = \"selected\"";
break;
case 'Long Term':
$longterm = "selected = \"selected\"";
break;
}
switch ($row['account_status']) {
case 'Active':
$active = "selected = \"selected\"";
break;
case 'Inactive':
$inactive = "selected = \"selected\"";
break;
}
switch ($row['type']) {
case 'Asset':
$asset = "selected = \"selected\"";
break;
case 'Expense':
$expense = "selected = \"selected\"";
break;
case 'Liability':
$liability = "selected = \"selected\"";
break;
case 'Equity':
$equity = "selected = \"selected\"";
break;
case 'Revenue':
$revenue = "selected = \"selected\"";
break;
}
echo '<tr>';
echo '<td> <input name="accountid[]" disabled value="' . $row['account_id'] . '"> </td>';
echo '<td> <input name="accountname[]" value="' . $row['account_name'] . '"> </td>';
echo '<td> <input name="datecreated[]" disabled value="' . $row['date_created'] . '"> </td>';
echo '<td>
<select name="type[]">
<option '.$asset.'>Asset</option>
<option '.$expense.'>Expense</option>
<option '.$liability.'>Liability</option>
<option '.$equity.'>Equity</option>
<option '.$revenue.'>Revenue</option>
</select>
</td>';
echo '<td>
<select name="term[]">
<option '.$current.'>Current</option>
<option '.$longterm.'>Long Term</option>
</select>
</td>';
echo '<td>
<select name="accountstatus[]" value="' . $row['account_status'] . '">
<option '.$active.'>Active</option>
<option '.$inactive.'>Inactive</option>
</select>
</td>';
echo '<td>
<input name="user_id[]" disabled value="' . $usernameRow['username'] . '">
</td>';
echo '</tr>';
}
echo '</table>';
}
if( isset($_POST['submitMods']) ) {
$i = 0;
while($i < $count) {
$account_id = $_POST["accountid"][$i];
$account_name = mysqli_real_escape_string($db,$_POST['accountname'][$i]);
$type = mysqli_real_escape_string($db,$_POST['type'][$i]);
$term = mysqli_real_escape_string($db,$_POST['term'][$i]);
$account_status = mysqli_real_escape_string($db,$_POST['accountstatus'][$i]);
$updateAccountsql = "
UPDATE Accounts
SET
account_id = '$account_id',
account_name = '$account_name',
type = '$type',
term = '$term',
account_status = '$account_status'
WHERE account_id = '$account_id'";
if($account_name == "") {
$submit_err = TRUE;
} else {
$updateResult = mysqli_query($db,$updateAccountsql);
}
$i++;
}
if(!$submit_err) {
//header("Location: ChartOfAccounts.php");
}
}
?>
In HTML Elements with Disabled attribute are not posted or you can say their values are not submitted.
Your input element is as below so it will not post any value.
<input name="accountid[]" value="' . $row['account_id'] . '" disabled />
Disabled controls Limitations:
it will not receive focus.
it will be skipped in tabbing navigation.
It cannot be successfully posted.
So if you dont want let user edit that input and if it is not neccessary to show that input to users then you can try input type="hidden" as below:
<input type="hidden" name="accountid[]" value="' . $row['account_id'] . '" />
Or If you want to show the id to user but not want to let them edit then you can use readonly attribute in your case, by readonly attribute you will be able to post your field's data, see below for example:
<input type="text" name="accountid[]" value="' . $row['account_id'] . '" readonly />
Read-only elements
can receive focus but cannot be modified by the user.
it will included in tabbing navigation.
it will be successfully posted.
doesn't work on checkboxes and select tags
Reference answer
Change below line
<input name="user_id[]" disabled value="' . $usernameRow['username'] . '">
to
<input name="user_id[]" type="hidden" value="' . $usernameRow['username'] . '">
Because accountid is disabled field so it do not submitted and not exist in $_POST variable so you need to replace your textbox with hidden field
Removed disabled from the input fields
replace
echo '<td> <input name="accountid[]" disabled value="' . $row['account_id'] . '"> </td>';
echo '<td> <input name="accountname[]" value="' . $row['account_name'] . '"> </td>';
echo '<td> <input name="datecreated[]" disabled value="' . $row['date_created'] . '"> </td>';
with
echo '<td> <input name="accountid[]" value="' . $row['account_id'] . '"> </td>';
echo '<td> <input name="accountname[]" value="' . $row['account_name'] . '"> </td>';
echo '<td> <input name="datecreated[]" value="' . $row['date_created'] . '"> </td>';
in case if you don't allow people to edit the fields you could use readonly in place of disabled.
Context: The page is for menu item entry into an order. When a menu item button is pressed, data from 'theProducts' table is queried and inserted into 'theOrderItems' table. I also want the same button press to take the serving size value (theProducts.dbProdServing) and subtract that amount from the product's inventory (theInventory.dbInventoryAmt), and update that table accordingly.
The problem I'm having is trying to figure out how to have one button press execute two prepared statements with bound values at the same time, those being the statement that INSERTS product data into 'theOrderItems' table and the statement that UPDATEs 'theInventory' table.
Currently, the page runs the INSERT statement fine, but the UPDATE statement doesn't run at all.
There are three pages that handle the entire order system, 'insertOrder.php' opens the order, 'insertOrderItem.php' allows the adding of items to a specific order, and 'completeorder.php' just displays the total order. I'll only post the first two pages.
insertOrder.php
<?php
$pagetitle = 'Insert Order';
require_once 'header.php';
require_once 'connect.php';
$errormsg = "";
$showform = 1;
$sqlselectt = "SELECT * from theTables";
$resultt = $db->prepare($sqlselectt);
$resultt->execute();
$sqlselectc = "SELECT * from theCustomers";
$resultc = $db->prepare($sqlselectc);
$resultc->execute();
$sqlselects = "SELECT * from theStaff";
$results = $db->prepare($sqlselects);
$results->execute();
$sqlselectl = "SELECT * from theLocations";
$resultl = $db->prepare($sqlselectl);
$resultl->execute();
if( isset($_POST['thesubmit']) )
{
$formfield['ffOrderPickup'] = $_POST['orderPickup'];
$formfield['ffCustKey'] = $_POST['custKey'];
$formfield['ffTableKey'] = $_POST['tableKey'];
$formfield['ffStaffKey'] = $_POST['staffKey'];
$formfield['ffLocationKey'] = $_POST['locationKey'];
$formfield['ffOrderDate'] = $_POST['orderDate'];
$formfield['ffOrderTime'] = $_POST['orderTime'];
if(empty($formfield['ffCustKey'])){$errormsg .= "<p>The customer field is empty.</p>";}
if(empty($formfield['ffTableKey'])){$errormsg .= "<p>The table field is empty.</p>";}
if(empty($formfield['ffStaffKey'])){$errormsg .= "<p>The employee field is empty.</p>";}
if(empty($formfield['ffLocationKey'])){$errormsg .= "<p>The location field is empty.</p>";}
if(empty($formfield['ffOrderDate'])) {$errormsg .= "<p>The order entry date is not selected.</p>"; }
if(empty($formfield['ffOrderTime'])) {$errormsg .= "<p>The order entry time is not selected.</p>"; }
if($errormsg != "")
{
echo "<div class='error'><p>THERE ARE ERRORS!</p>";
echo $errormsg;
echo "</div>";
}
else
{
$sqlmax = "SELECT MAX(dbOrderKey) AS maxKey FROM theOrders";
$resultmax = $db->prepare($sqlmax);
$resultmax->execute();
$rowmax = $resultmax->fetch();
$maxKey = $rowmax['maxKey'];
$maxKey = $maxKey + 1;
try
{
$sqlinsert = 'INSERT INTO theOrders (dbOrderKey, dbCustKey, dbTableKey, dbStaffKey, dbLocationKey, dbOrderComplete, dbOrderDate, dbOrderTime, dbOrderMade, dbOrderPickup)
VALUES (:bvOrderKey, :bvCustKey, :bvTableKey, :bvStaffKey, :bvLocationKey, 0, :bvOrderDate, :bvOrderTime, 0, :bvOrderPickup)';
$stmtinsert = $db->prepare($sqlinsert);
$stmtinsert->bindvalue(':bvOrderKey', $maxKey);
$stmtinsert->bindvalue(':bvCustKey', $formfield['ffCustKey']);
$stmtinsert->bindvalue(':bvTableKey', $formfield['ffTableKey']);
$stmtinsert->bindvalue(':bvStaffKey', $formfield['ffStaffKey']);
$stmtinsert->bindvalue(':bvLocationKey', $formfield['ffLocationKey']);
$stmtinsert->bindvalue(':bvOrderDate', $formfield['ffOrderDate']);
$stmtinsert->bindvalue(':bvOrderTime', $formfield['ffOrderTime']);
$stmtinsert->bindvalue(':bvOrderPickup', $formfield['ffOrderPickup']);
$stmtinsert->execute();
echo "<p>Order Number: " . $maxKey . "</p>";
echo "<p>Location: " . $formfield['ffLocationKey'] . "</p>";
echo '<br><br><form action="insertOrderItem.php" method="post">';
echo '<input type="hidden" name="orderKey" value="' . $maxKey . '">';
echo '<input type="hidden" name="locationKey" value="' . $formfield['ffLocationKey'] . '">';
echo '<input type="submit" name="submit" value="Enter Order Items">';
echo '</form>';
$showform = 0;
}
catch(PDOException $e)
{
echo 'ERROR!!!' .$e->getMessage();
exit();
}
}
}
if ($visible == 1 && $showform == 1)
{
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" name="theform">
<fieldset><legend>Order Information</legend>
<table border>
<tr>
<th><label for="custKey">Customer:</label></th>
<td><select name="custKey" id="custKey">
<option value = "">Please Select a Customer</option>
<?php while ($rowc = $resultc->fetch() )
{
echo '<option value="'. $rowc['dbCustKey'] . '">' . $rowc['dbCustLast'] . '</option>';
}
?>
</select>
</td>
</tr>
<tr>
<th><label for="tableKey">Table:</label></th>
<td><select name="tableKey" id="tableKey">
<option value = "">Please Select a Table</option>
<?php while ($rowt = $resultt->fetch() )
{
echo '<option value="'. $rowt['dbTableKey'] . '">' . $rowt['dbTableKey'] . '</option>';
}
?>
</select>
</td>
</tr>
<tr>
<th><label for="staffKey">Employee:</label></th>
<td><select name="staffKey" id="staffKey">
<option value = "">Please Select an Employee</option>
<?php
while ($rows = $results->fetch() )
{
if($_SESSION['userid'] == $rows['dbStaffKey']) {
$selected = 'selected';
} else {
$selected = '';
}
echo '<option value="'. $rows['dbStaffKey'] . '" ' . $selected . '>' . $rows['dbStaffLast'] . '</option>';
}
?>
</select>
</td>
</tr>
<tr>
<th><label for="locationKey">Location:</label></th>
<td><select name="locationKey" id="locationKey">
<option value = "">Please Select an Location</option>
<?php
while ($rowl = $resultl->fetch() )
{
echo '<option value="'. $rowl['dbLocationKey'] . '" ' . $selected . '>' . $rowl['dbLocationCity'] . '</option>';
}
?>
</select>
</td>
</tr>
<tr>
<th>Pick a Delivery Type:</th>
<td><input type="radio" name="orderPickup" id="orderPickup"
value=1 <?php echo ' checked';?> />
<label for="pickup">Pickup</label>
<input type="radio" name="orderPickup" id="orderPickup"
value=0 />
<label for="inHouse">In-House</label>
</td>
</tr>
<tr>
<th><label for="orderDate">Entry Date:</label></th>
<td><input type="date" name="orderDate" id="orderDate" value="<?php if( isset($formfield['ffOrderDate'])){echo $formfield['ffOrderDate'];}?>" /></td>
</tr>
<tr>
<th><label for="orderTime">Entry Time:</label></th>
<td><input type="time" name="orderTime" id="orderTime" value="<?php if( isset($formfield['ffOrderTime'])){echo $formfield['ffOrderTime'];}?>" /></td>
</tr>
</table>
<input type="submit" name = "thesubmit" value="Enter">
</fieldset>
</form>
<br><br>
<?php
}
include_once 'footer.php';
?>
insertOrderItem.php
<?php
$pagetitle = 'Insert Order Items';
require_once 'header.php';
require_once 'connect.php';
$formfield['ffOrderKey'] = $_POST['orderKey'];
$formfield['ffProdKey'] = $_POST['prodKey'];
$formfield['ffProdPrice'] = $_POST['prodPrice'];
$formfield['ffProdServing'] = $_POST['prodServing'];
$formfield['ffLocationKey'] = $_POST['locationKey'];
$sqlselectc = "SELECT * FROM theCategories";
$resultc = $db->prepare($sqlselectc);
$resultc->execute();
$sqlselecti = "SELECT * FROM theInventory";
$resulti = $db->prepare($sqlselecti);
$resulti->execute();
if (isset($_POST['OIEnter'])) {
$rowi = $resulti->fetch();
$invRem = $rowi['dbInventoryAmt'] - $formfield['ffProdServing'];
$sqlinsert = 'INSERT INTO theOrderItems (dbOrderKey, dbProdKey, dbProdPrice)
VALUES (:bvOrderKey, :bvProdKey, :bvProdPrice)';
$stmtinsert = $db->prepare($sqlinsert);
$stmtinsert->bindValue(':bvOrderKey', $formfield['ffOrderKey']);
$stmtinsert->bindValue(':bvProdKey', $formfield['ffProdKey']);
$stmtinsert->bindValue(':bvProdPrice', $formfield['ffProdPrice']);
$stmtinsert->execute();
$sqlupdate = "UPDATE theInventory
SET dbInventoryAmt = :bvInventoryAmt
WHERE dbLocationKey = :bvLocationKey
AND dbProdKey = :bvProdKey";
$stmtupdate = $db->prepare($sqlupdate);
$stmtupdate->bindValue(':bvInventoryAmt', $invRem);
$stmtupdate->bindValue(':bvLocationKey', $formfield['ffLocationKey']);
$stmtupdate->bindValue(':bvProdKey', $formfield['ffProdKey']);
$stmtupdate->execute();
}
if (isset($_POST['DeleteItem'])) {
$sqldelete = "DELETE FROM theOrderItems WHERE dbOrderItemKey = :bvOrderItemKey";
$stmtdelete = $db->prepare($sqldelete);
$stmtdelete->bindValue(':bvOrderItemKey', $_POST['orderItemKey']);
$stmtdelete->execute();
}
if (isset($_POST['UpdateItem'])) {
$formfield['ffProdPrice'] = trim($_POST['newProdPrice']);
$formfield['ffOrderNotes'] = trim($_POST['newOrderNote']);
$sqlupdateoi = 'UPDATE theOrderItems
SET dbProdPrice = :bvProdPrice,
dbOrderNotes = :bvOrderNotes
WHERE dbOrderItemKey = :bvOrderItemKey';
$stmtupdateoi = $db->prepare($sqlupdateoi);
$stmtupdateoi->bindValue(':bvOrderItemKey', $_POST['orderItemKey']);
$stmtupdateoi->bindValue(':bvProdPrice', $formfield['ffProdPrice']);
$stmtupdateoi->bindValue(':bvOrderNotes', $formfield['ffOrderNotes']);
$stmtupdateoi->execute();
}
$sqlselecto = 'SELECT theOrderItems.*, theProducts.dbProdName, theProducts.dbProdServing, theCategories.*
FROM theOrderItems, theProducts, theCategories
WHERE theOrderItems.dbProdKey = theProducts.dbProdKey
AND theProducts.dbCatKey = theCategories.dbCatKey
AND theOrderItems.dbOrderKey = :bvOrderKey';
$resulto = $db->prepare($sqlselecto);
$resulto->bindValue(':bvOrderKey', $formfield['ffOrderKey']);
$resulto->execute();
if($visible == 1 && ($_SESSION['userpermit'] == 1 || $_SESSION['userpermit'] == 3 || $_SESSION['userpermit'] == 4))
{
?>
<fieldset><legend><b>Enter Items for Order Number: <?php echo $formfield['ffOrderKey']; ?></b></legend>
<table border>
<?php
$counter = 0;
echo '<tr><b>';
while ($rowc = $resultc->fetch()){
if ($counter == 2){
echo '</tr><tr>';
$counter = 0;
}
$counter++;
echo '<th valign = "middle" align = "center">' . $rowc['dbCatName'] . '<br> <table border>';
$sqlselectp = "SELECT * FROM theProducts WHERE dbCatKey = :bvCatKey";
$resultp = $db->prepare($sqlselectp);
$resultp->bindValue(':bvCatKey', $rowc['dbCatKey']);
$resultp->execute();
while ($rowp = $resultp->fetch()){
echo '<td>';
echo '<form action = "' . $_SERVER['PHP_SELF'] . '" method = "post">';
echo '<input type = "hidden" name = "orderKey" value = "' . $formfield['ffOrderKey'] . '">';
echo '<input type = "hidden" name = "prodKey" value = "' . $rowp['dbProdKey'] . '">';
echo '<input type = "hidden" name = "prodPrice" value = "' . $rowp['dbProdPrice'] . '">';
echo '<input type = "hidden" name = "prodServing" value = "'. $rowp['dbProdServing'] . '">';
echo '<input type = "submit" id="order" name = "OIEnter" value = "' . $rowp['dbProdName'] . '">';
echo '</form>';
echo '</td>';
}
echo '</table></th>';
}
echo '</tr>';
?>
</table>
</table>
</fieldset>
<br><br>
<table>
<tr>
<td>
<table border>
<tr>
<th>Item</th>
<th>Category</th>
<th>Description</th>
<th>Serving Size</th>
<th>Price</th>
<th>Notes</th>
<th></th>
<th></th>
</tr>
<?php
$ordertotal = 0;
while ($rowo = $resulto->fetch()){
$ordertotal = $ordertotal + $rowo['dbProdPrice'];
echo '<tr><td>' . $rowo['dbProdName']
. '</td><td>' . $rowo['dbCatName']
. '</td><td>' . $rowo['dbProdDesc']
. '</td><td>' . $rowo['dbProdServing']
. '</td><td>' . $rowo['dbProdPrice']
. '</td><td>' . $rowo['dbOrderNotes']
. '<td>';
echo '<form action = "' . $_SERVER['PHP_SELF'] . '" method = "post">';
echo '<input type = "hidden" name = "orderKey" value = "' . $formfield['ffOrderKey'] . '">';
echo '<input type = "hidden" name = "orderItemKey" value = "' . $rowo['dbOrderItemKey'] . '">';
echo '<input type = "submit" name = "NoteEntry" value = "Update">';
echo '</form></td><td>';
echo '<form action = "' . $_SERVER['PHP_SELF'] . '" method = "post">';
echo '<input type = "hidden" name = "orderKey" value = "' . $formfield['ffOrderKey'] . '">';
echo '<input type = "hidden" name = "orderItemKey" value = "' . $rowo['dbOrderItemKey'] . '">';
echo '<input type = "submit" name = "DeleteItem" value = "Delete">';
echo '</form></td></tr>';
}
echo '<tr><th></th><th></th><th>Total</th><th>' . $ordertotal . '</th><th></th><th></th><th></th></tr>';
?>
</table>
<?php
if(isset($_POST['NoteEntry'])){
$sqlselectoi = 'SELECT theOrderItems.*, theProducts.dbProdName
FROM theOrderItems, theProducts
WHERE theOrderItems.dbProdKey = theProducts.dbProdKey
AND theOrderItems.dbOrderItemKey = :bvOrderItemKey';
$resultoi = $db->prepare($sqlselectoi);
$resultoi->bindValue(':bvOrderItemKey', $_POST['orderItemKey']);
$resultoi->execute();
$rowoi = $resultoi->fetch();
echo '</td><td>';
echo '<form action = "' . $_SERVER['PHP_SELF'] . '" method = "post">';
echo '<table>';
echo '<tr><td>Price: <input type="text" name = "newProdPrice" value = "' .
$rowoi['dbProdPrice'] . '"></td></tr>';
echo '<tr><td>Notes: <input type="text" name = "newOrderNote" value = "' .
$rowoi['dbOrderNotes'] . '"></td></tr>';
echo '<tr><td>';
echo '<input type = "hidden" name = "orderKey" value = "' . $formfield['ffOrderKey'] . '">';
echo '<input type = "hidden" name = "orderItemKey" value = "' . $rowoi['dbOrderItemKey'] . '">';
echo '<input type = "submit" name = "UpdateItem" value = Update Item">';
echo '</td></tr></table>';
}
?>
</td></tr>
</table>
<br><br>
<?php
echo '<form action = "completeorder.php" method = "post">';
echo '<input type = "hidden" name = "orderKey" value = "' . $formfield['ffOrderKey'] . '">';
echo '<input type = "submit" name = "CompleteOrder" value = "Complete Order">';
echo '</form>';
}
include_once 'footer.php';
?>
My main question is why is PDO::exec not executing every iteration of my loop, and instead only executing in the first iteration.
I am trying to insert coordinates into my MySQL database.
My database structure is (number(primary key), x, y, z).
I ask the user to insert a number ($n), and then ask them to fill in $n sets of coordinates.
The users inputs are passed to another page with $_POST, then retrieved by dynamic variable names and inserted into the database.
Everything works, except the loop only writes to the database its first iteration. So I end up with results for x1,z1,y1 but nothing else.
Can anyone explain what I am doing wrong (other than not using arrays)?
<?php
require_once('db.php');
$n = $_POST['selectOption'];
for($i = 1; $i < $n+1;$i++){
${'x' . $i} = $_POST["x" . $i];
${'y' . $i} = $_POST["y" . $i];
${'z' . $i} = $_POST["z" . $i];
$rowsAffected = $db->exec("INSERT INTO coordinate3d (number,x,y,z)
VALUES ('$n', '${'x' . $i}', '${'y' . $i}', '${'z' . $i}')");
}
?>
Here is my form
<form action="aaron_stockdale_dynamic_process.php" method="post" name="coordinateForm">
<?php
for($i = 0; $i < $n; $i++)
{
?>
x<?php echo $i+1;?> <input name="x<?php echo $i+1;?>" type=text>, y<?php echo $i+1;?> <input name="y<?php echo $i+1;?>" type=text>, z<?php echo $i+1;?> <input name="z<?php echo $i+1;?>" type=text><br>
<?php
}
?>
<br>
<input type="hidden" name="selectOption" value="<?php echo $n;?>">
<input type="submit" oonClick="document.location.href='aaron_stockdale_dynamic_process.php'" value="Submit">
</form>
require_once('aaron_stockdale_database.php');
$n = $_POST['selectOption'];
for($i = 1; $i < $n+1;$i++){
$x = $_POST["x" . $i];
$y = $_POST["y" . $i];
$z = $_POST["z" . $i];
$rowsAffected = $db->exec("INSERT INTO coordinate3d (number,x,y,z)
VALUES ('$n', '$x', '$y', '$z')");
}
the rest is on you ;)
And also check if any of the fields a primary key, that will prevent insert it twice.
Since you have received an acceptable answer for your question, I'd like to give you a hint on your html code.
<form action="aaron_stockdale_dynamic_process.php" method="post" name="coordinateForm">
<?php
for($i = 0; $i < $n; $i++)
{
?>
x<?php echo $i+1;?> <input name="x<?php echo $i+1;?>" type=text>, y<?php echo $i+1;?> <input name="y<?php echo $i+1;?>" type=text>, z<?php echo $i+1;?> <input name="z<?php echo $i+1;?>" type=text><br>
<?php
}
?>
<br>
<input type="hidden" name="selectOption" value="<?php echo $n;?>">
<input type="submit" oonClick="document.location.href='aaron_stockdale_dynamic_process.php'" value="Submit">
</form>
Now, this code can be cleaned up a bit.
<form action="aaron_stockdale_dynamic_process.php" method="post" name="coordinateForm">
<?php
for($i = 0; $i < $n; $i++)
{
echo 'x' . $i+1 . '<input name="x' . $i+1 . '" type=text>, y' . $i+1 . ' <input name="y' . $i+1. '" type=text>, z' . $i+1 . '<input name="z' . $i+1 . '" type=text><br>'
}
?>
<br>
<input type="hidden" name="selectOption" value="<?php echo $n;?>">
<input type="submit" value="Submit">
</form>
I changed the "oonClick" to "onClick", and then afterwards I removed it, as when you submit, you don't need to navigate, as the browser will do this, upon submission.
And then I removed the repetitive opening and closing of php tags, and combined all the echos into one.
Here's my solution in one file:
<!DOCTYPE html>
<html lang=en>
<head>
<script>
function validcoord(e) {
var key;
var keychar;
if (window.event)
key = window.event.keyCode;
else if (e)
key = e.which;
else
return true;
keychar = String.fromCharCode(key);
keychar = keychar.toLowerCase();
// control keys
if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) )
return true;
// Numeral Characters
else if ((("0123456789-.,").indexOf(keychar) > -1))
return true;
else
return false;
}
</script>
<style>
input[type="number"] { text-align: right; width: 50px; }
label { margin-left: 4em; }
</style>
</head>
<body>
<?php
define ("SELF", $_SERVER['PHP_SELF']);
define ("EOL", "\r\n");
// Modify as needed
define ("MINNUMCORDS" , "1");
define ("MAXNUMCORDS" , "10");
define ("DFLTNUMCORDS", "2");
$formSubmitted = (empty($_POST)) ? FALSE : TRUE;
if (!$formSubmitted) {
$htmlOutput = '
<form action="' . SELF . '" method=post name=foo id=foo>
<input type=hidden name=current value=0>
<label>Enter the number of Coordinates:
<input type=number autofocus onFocus="this.select()"' .
' min=' . MINNUMCORDS .
' max=' . MAXNUMCORDS .
' value=' . DFLTNUMCORDS .
' name=numcords /></label>
</form>' . EOL;
echo $htmlOutput;
} // end if not submitted
else { // a form HAS been submitted
foreach ($_POST as $key => $value) { $$key = $value; }
unset($_POST);
if (!empty($coord)) { // We got some input that may be a valid x,y,z coordinate
if ( substr_count($coord, ",") != 2 ) {
$error = "We're looking for THREE numbers seperated by TWO commas.";
} // end if we don't have three values
else { // We got three Values
$coord = trim($coord);
list($x,$y,$z) = explode(",", $coord);
if ( !(is_numeric($x) && is_numeric($y) && is_numeric($z)) ) {
$error = "We're looking for three VALID NUMBERS seperated by two commas.";
} // end if all three numbers are not valid
else { // We got three Values and each of them are numbers
require('db.php');
$rowsAffected = $db->exec("INSERT INTO coordinate3d (number,x,y,z)
VALUES ('$numcords', '$x', '$y', '$z')");
//echo "INSERT INTO coordinate3d (number,x,y,z) VALUES ('$numcords', '$x', '$y', '$z')<br />" . EOL;
} // end three valid numbers
} // end three values
} // end if we have some input in $coord
if ($error) {
echo "~~ " . $error . "<br /><br />" . EOL;
--$current;
} // end if error
if ( $current < $numcords ) {
$htmlOutput = 'Please enter the coordinate in the form: x,y,z (Ex: -.4,2,8.5)' . EOL;
$htmlOutput .= '<form action="' . SELF . '" method=post name=bar id=bar>' . EOL;
$htmlOutput .= ' <input type=hidden name=numcords value="' . $numcords . '" />' . EOL;
$htmlOutput .= ' <input type=hidden name=current value="' . ++$current . '" />' . EOL;
$htmlOutput .= ' <label>Coord #' . $current . ': ';
$htmlOutput .= '<input type=text name=coord size=12 maxlength=48 ' .
'autofocus onKeyPress="return validcoord(event);" /></label>' . EOL;
$htmlOutput .= '</form>' . EOL;
echo $htmlOutput;
} // end if we need to get another coord
} // end form was submitted
?>
</body>
</html>
Can anyone help me with the pagination? I am trying this code on pagination and the pages are showing but when clicked on the pages like Next or the number with links it gives a syntax error.
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?page=2' at line 1"
My tables data is around 250 and I wanted to limit it to 50 data per page.
Here is my code: (pagination section - is the problem)
<link rel="stylesheet" type="text/css" href="css/navbar.css">
<?php include 'navbar.php';?>
<br>
<?php
if(!isset($_GET['table'])){
echo 'You must assign a table to view.';
exit;
}
session_start();
//Connect here
$conn = mysqli_connect("localhost", "root", "", "dkusers");
$table = mysqli_real_escape_string($conn, $_GET['table']);
$fields = array();
$q = mysqli_query($conn, "SHOW COLUMNS FROM " . $table) or die(mysqli_error($conn));
while($r = mysqli_fetch_assoc($q)) $fields[count($fields)] = $r['Field'];
echo '<b><font size="4">Table: </b>', $table, '</font><br>';
// -----------------INSERT-----------------
if(isset($_POST['action']) && $_POST['action'] == "Insert"){
if(!isset($_POST['insert'])){
echo '<h3>Insert Row</h3>';
echo '<form method="post"><input type="hidden" name="action" value="' . $_POST['action'] . '" />';
echo '<table border="1" cellpadding="7"><tr><th>Field</th><th>Value</th><th>MD5</th></tr>';
foreach($fields as $key => $value){
echo '<tr><td>' . $value . ':</td><td><input type="text" name="field_' . $value . '" /></td><td><input type="checkbox" name="md5_' . $value . '" /></td></tr>';
}
echo '<tr><td><input type="submit" name="insert" value="Submit" /></td><td colspan="2">Back</td></tr></table></form>';
exit;
}else{
$first = true;
$query = "INSERT INTO " . $table;
foreach($_POST as $key => $value){
if(strrpos($key, "field_", -strlen($key)) !== false){
$key = substr($key, 6);
$query .= sprintf("%s%s", ($first) ? " (" : ",", $key);
$first = false;
}
}
$query .= ") VALUES";
$first = true;
foreach($_POST as $key => $value){
if(strrpos($key, "field_", -strlen($key)) !== false){
$key = substr($key, 6);
$query .= sprintf("%s'%s'", ($first) ? " (" : ",", (isset($_POST['md5_' . $key])) ? md5($value) : $value);
$first = false;
}
}
$q = mysqli_query($conn, $query . ")");
if($q) echo 'Successfully inserted row into table!<br/><br/>'; else echo mysqli_error($conn) . '<br/><br/>';
}
}
// -----------------DELETE-----------------
if(isset($_POST['action']) && $_POST['action'] == "Delete"){
if(!isset($_POST['rows'])){
echo 'You didn\'t send any rows to delete.<br/><br/>';
}else{
$count = 0;
for($i = 0;$i < count($_POST['rows']);$i++){
if($_POST['rows'][$i] >= count($_SESSION['store'])) continue;
$query = "DELETE FROM " . $table . "";
$row = $_SESSION['store'][$_POST['rows'][$i]];
$first = true;
foreach($row as $key => $value){
$query .= sprintf(" %s %s = '%s'", ($first) ? "WHERE" : "AND", $key, $value);
$first = false;
}
$q = mysqli_query($conn, $query . " LIMIT 1");
if(!$q) echo mysqli_error($conn) . '<br/>';
$count += mysqli_affected_rows($conn);
}
echo 'Successfully deleted ' . $count . ' row(s)!<br/><br/>';
}
}
// -----------------MODIFY-----------------
if(isset($_POST['action']) && $_POST['action'] == "Modify"){
if(!isset($_POST['rows'])){
echo 'You didn\'t send any rows to modify.<br/><br/>';
}else if(isset($_POST['modify'])){
$count = 0;
for($i = 0;$i < count($_POST['rows']);$i++){
if($_POST['rows'][$i] >= count($_SESSION['store'])) continue;
$first = true;
$query = "UPDATE " . $table . " SET";
foreach($_POST as $key => $value){
if(strrpos($key, "field_", -strlen($key)) !== false){
$key = explode("_", $key, 3);
if($key[1] == $i){
$query .= sprintf(((!$first) ? "," : "") . " %s = '%s'", $key[2], (isset($_POST['md5_' . $key[1] . '_' . $key[2]])) ? md5($value) : $value);
$first = false;
}
}
}
$row = $_SESSION['store'][$_POST['rows'][$i]];
$first = true;
foreach($row as $key => $value){
$query .= sprintf(" %s %s = '%s'", ($first) ? "WHERE" : "AND", $key, $value);
$first = false;
}
$q = mysqli_query($conn, $query . " LIMIT 1");
if(!$q) echo mysqli_error($conn) . '<br/>';
$count += mysqli_affected_rows($conn);
}
echo 'Successfully updated ' . $count . ' row(s)!<br/><br/>';
}else{
echo '<h3>Modify Row</h3>';
echo '<form method="post"><input type="hidden" name="action" value="' . $_POST['action'] . '" />';
for($i = 0;$i < count($_POST['rows']);$i++) if($_POST['rows'][$i] < count($_SESSION['store'])) echo '<input type="hidden" name="rows[]" value="' . $_POST['rows'][$i] . '" />';
echo '<table border="1" cellpadding="7"><tr><th>Field</th><th>Value</th><th>MD5</th></tr>';
for($i = 0;$i < count($_POST['rows']);$i++){
if($_POST['rows'][$i] >= count($_SESSION['store'])) continue;
if($i != 0) echo '<tr><td colspan="3"><hr/></td></tr>';
$row = $_SESSION['store'][$_POST['rows'][$i]];
foreach($row as $key => $value){
echo '<tr><td>' . $key . ':</td><td><input type="text" name="field_' . $i . '_' . $key . '" value="' . $value . '" /></td><td><input type="checkbox" name="md5_' . $i . '_' . $key . '" /></td></tr>';
}
}
echo '<tr><td><input type="submit" name="modify" value="Submit" /></td><td colspan="2">Back</td></tr></table></form>';
exit;
}
}
// -----------------SEARCH-----------------
echo '<br><form method="post">Search: <input type="text" name="filter" value="' . ((isset($_POST['filter'])) ? $_POST['filter'] : '') . '"/><br/>Filter by: <br/>';
for($i = 0;$i < count($fields);$i++) echo '<input type="checkbox" name="' . $fields[$i] . '"' . ((isset($_POST['filter']) && isset($_POST[$fields[$i]])) ? ' checked' : '') . '/>' . $fields[$i] . ' ';
echo '</form><form method="post"><table border="1" cellpadding="7"><tr>';
for($i = 0;$i < count($fields);$i++) echo '<th>' . $fields[$i] . '</th>';
echo '<th>-</th></tr>';
$sql = "SELECT * FROM " . $table;
if(isset($_POST['filter'])){
$filter = mysqli_real_escape_string($conn, $_POST['filter']);
foreach($fields as $key => $value) if(!isset($_POST[$fields[$key]])) unset($fields[$key]);
if(count($fields) > 0){
$first = true;
foreach($fields as $key => $value){
$sql .= " " . (($first) ? "WHERE" : "OR") . " " . $value . " LIKE '%" . $filter . "%'";
$first = false;
}
}
}
// -----------------Bottoms (Above table)-----------------
echo '<input type="submit" name="action" value="Modify" /> <input onclick="return confirm(\'Are you sure you want to delete these rows?\')" type="submit" name="action" value="Delete" /> <input type="submit" name="action" value="Insert" /><br><br></form>';
$_SESSION['store'] = array();
$q = mysqli_query($conn, $sql) or die(mysqli_error($conn));
while($r = mysqli_fetch_assoc($q)){
echo '<tr>';
foreach($r as $key => $value) echo '<td>' . $value. '</td>';
echo '<td><input type="checkbox" name="rows[]" value="' . count($_SESSION['store']) . '" /></td></tr>';
$_SESSION['store'][count($_SESSION['store'])] = $r;
}
// -----------------Bottoms (Below table)-----------------
echo '</table>';
//echo '<br><input type="submit" name="action" value="Modify" /> <input onclick="return confirm(\'Are you sure you want to delete these rows?\')" type="submit" name="action" value="Delete" /> <input type="submit" name="action" value="Insert" /></form>';
?>
<br>
// -----------------Pagination-----------------
<br>
<?php
$start=0;
$limit=50;
if(isset($_GET['page']))
{
$page=$_GET['page'];
$start=($page-1)*$limit;
}
else{
$page=1;
}
//Fetch from database first 10 items which is its limit. For that when page open you can see first 10 items.
$query=mysqli_query($conn,"select * from $table LIMIT $start, $limit");
?>
<?php
//print 10 items
while($result=mysqli_fetch_array($query))
{
//echo "<li>".$result['username']."</li>";
}
?>
<?php
//fetch all the data from database.
$rows=mysqli_num_rows(mysqli_query($conn,"select * from $table"));
//calculate total page number for the given table in the database
$total=ceil($rows/$limit);
if($page>1)
{
//Go to previous page to show previous 10 items. If its in page 1 then it is inactive
echo 'PREVIOUS';
}
if($page!=$total)
{
////Go to previous page to show next 10 items.
echo 'NEXT';
}
?>
<?php
//show all the page link with page number. When click on these numbers go to particular page.
for($i=1;$i<=$total;$i++)
{
if($i==$page) { echo "<li class='current'>".$i."</li>"; }
else { echo '<li>'.$i.'</li>'; }
}
?>
You have error on html URL syntax
echo 'NEXT';
The correct would be
echo 'NEXT';
You have to use ? only for the first URL parameter, & for the following, if any.
I wonder how I can make sure a checkbox is checked on a postback if for example someone leaves the addressfield blank it should then make sure the user doesn't have to refill the whole form again. In this case I'm generating 31 checkboxes. It's really frustrating.
$output_checkbox = '';
$checked = '';
for ($i=1; $i <= 31; $i++) {
if (isset($_POST['dagen'])) {
foreach ($_POST['dagen'] as $dag) {
if ($dag == $i) {
$checked . $i = 'checked';
}
}
}
$output_checkbox .= '<input type="checkbox" name="dagen[]" value="' . $i . '" id="day_' . $i . '"' . $checked . ' /><label for="day_' . $i . '">Dag ' . $i . '</label>';
}
Here is the form but there isn't the problem:
<form action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="post">
<div>
<label for="email">Email:</label>
<input id="email" type="text" name="email" value="<?php if(isset($_POST['email'])) { echo $_POST['email'];} ?>" />
</div>
<div>
<label for="month">Maand:</label>
<select id="month" name="month">
<?php echo $output; ?>
</select>
</div>
<div>
Dagen:
<?php echo $output_checkbox; ?>
</div>
<input type="submit" name="btnSend" value="Verzenden" />
</form>
Here is an example of how I normally do it but it's a lot easier since it comes out of a database:
$output = '';
while ($row = $result->fetch_array(MYSQLI_BOTH)) {
$selected = '';
if (isset($_POST['month']) && $_POST['month'] == $row['id']) {
$selected = 'selected';
}
$output .= '<option value="' . $row['id'] . '"' . $selected . '>' . $row['naam'] . '</option>';
}
Something like this:
$output_checkbox = '';
for ($i=1; $i <= 31; $i++) {
if (isset($_POST['dagen'])) {
foreach ($_POST['dagen'] as $dag) {
if ($dag == $i) {
$checked = 'checked';
}
else{
$checked = '';
}
$output_checkbox .= '<input type="checkbox" name="dagen[]" value="' . $i . '" id="day_' . $i . '"' . $checked . ' /><label for="day_' . $i . '">Dag ' . $i . '</label>';
}
}
}