with the code below i let people fill in how many pizza's they want and then pass the chosen pizza ids through the url using get.
<?php // some code that connects to database ?>
<table>
<form method="get" action="oder_process.php">
<?php
while (list($pizzaId, $pizzaName, $pizzaNumber, $pizzaPrice) = mysql_fetch_row($resultaat))
{
echo "<tr>
<td>".$pizzaName."</td>
<td>".$pizzaNumber."</td>
<td>".$pizzaPrice."</td>
<td> <input type='text' name='pizzas[$pizzaId]' value='$qty' size='3' /></td>
</tr>";
}
mysql_close($db);
?>
<input type="submit" value="Bestel!" />
</form>
</table>
Now displaying the pizza id with the amount filled in works just fine. But then I also want to read other columns like pizza name or description from the database. However what i'm doing below doesn't do it. Any ideas?
part of the order_process.php file:
echo "Your order: <br />";
foreach ($_GET['pizzas'] as $pizzaId => $qty)
{
if ($qty > 0)
echo $pizzaId." ".$qty."<br />";
$pizzaSql = mysql_query("SELECT * FROM pizzas where pizza_id = $pizzaId");
while ($row = mysql_fetch_assoc($pizzaSql))
{
echo $row['pizza_name'];
}
}
why foreach()? can't you just ...
if ( is_numeric( $_GET['pizzaid'] ) ) {
$pizzaSql = sprintf("SELECT * FROM orders WHERE pizza_id=%d",$_GET['pizzaid']);
$pizzaQuery = mysql_query($pizzaSql);
$numPizzas = mysql_num_rows( $pizzaQuery );
while ( $order = mysql_fetch_array($pizzaQuery,MYSQL_ASSOC) ) {
if ( $numPizzas > 0 ) {
echo $orderVariables;
} else {
echo 'Error: no order exists for that ID thingy';
}
}
}
i added some minor validation that assumes the pizza/order id is a numeric value. i don't trust anything that comes into a script from the $_GET array without some serious data validation first
can you try chucking in a test to make sure the query worked as expected
$pizzaSql = mysql_query("SELECT * FROM pizzas where pizza_id = $pizzaId");
if (mysql_error()) {
die(mysql_error());
}
Related
I want to display checked checkbox which are stored as values in a mysql database.
For now the table stores the value of the checkbox being checked in the database. The header and first column are fetched from three different tables in the database. While the values of the checked check-boxes gets saved in a same table.
Here's the code for inserting the data.
$active = "CourseReport";
require_once 'pages/header.php';
require_once './functions/schema-functions.php';
require_once './functions/report-functions.php';
$course = Schema::getCourseReport();
$objective = Schema::getObjective();
$goals = Schema::getGoals();
$mainobj = Schema::getMainObjectives();
$subobj = Schema::getSubObjectives();
?>
<form id="addReport" action ='./functions/report-functions.php' method="post">
<table id="table1" class="table table-hover">
<thead>
<?php
echo '<tr><th>Goals</th>';
for ($i = 0; $i < count($course); $i++) {
echo '<th id = "rotate1">'. $course[$i]->commonName . '</th>';
}
echo '</tr>';
?>
</thead>
<tbody>
<?php
for ($y = 0; $y < count($goals); $y++) {
echo '<tr class="clickable"><th class="toggle">Goal#'.$goals[$y]['GoalId'].':'." " .' '.$goals[$y]['Goals'].'</th>
</tr>';
?>
<?php
for( $z = 0; $z < count($mainobj); $z++){
if($mainobj[$z]['GoalId'] == $goals[$y]['GoalId']) {
echo '<tr class="expander"><th class=row-header>Objective#'.$mainobj[$z]['MainObjId'].':'." ".' '.$mainobj[$z]['MainObjectives'].'</th>
</tr>';
?>
<?php
for ($j = 0; $j< count($subobj); $j++) {
if($mainobj[$z]['MainObjId'] == $subobj[$j]['MainObjId']){
echo '<tr class="expander"><td class=row-header>'.$subobj[$j]['SubObjId'].' ) '.$subobj[$j]['SubObjectives'].' </td>';
for ($x = 0; $x < count($course); $x++) {
echo "<td><input name='check[]' type=checkbox value=c".$course[$x]->courseId."-o".$subobj[$j]['SubObjId']." id=checked></td>";
}
echo '</tr>';
}
}
}
}
}
?>
</tbody>
</table>
<button class="button" name= "submit" value= "Submit">Submit</button>
</form>
report-functions.php
if( isset( $_POST['submit'], $_POST['check'] ) ){
try{
require_once 'db-connect.php';
$conn = DatabaseConnection::getConnection();
$sql= " insert into `Report` (`ColRow`) values (:value) ";
$stmt = $conn->prepare( $sql );
if( $stmt ){
$conn->beginTransaction();
foreach( $_POST['check'] as $index => $value ) {
$result = $stmt->execute( [ ':value' => $value ] );
if( !$result ) {
echo '
<script>
alert("Error, please try submitting again. Error code 1");
window.history.back();
</script>';
}
}
$conn->commit();
echo '<script>
alert("Report was submitted successfully.");
window.location = ".../";
</script>';
}
} catch( Exception $e ){
$conn->rollback();
exit( $e->getMessage() );
}
I expect that once I submit the table, the table should load the same table with the checked checkboxes. I should be able to make the changes and submit the table over and over again.
Please comment if I need to provide any additional information.
When you display your page (in your first section of code), at some point you do this:
echo "<td><input name='check[]' type=checkbox value=c".$course[$x]->courseId."-o".$subobj[$j]['SubObjId']." id=checked></td>";
The value is set to:
value=c"c.$course[$x]->courseId."-o".$subobj[$j]['SubObjId']";
This value is where you get the checked or not value you mentioned in the comments (like c1-o1.1).
Right. So before you do that echo, add a new if condition.
$value = "c$course[$x]->courseId" . "-o$subobj[$j]['SubObjId']";
if (verify_checked($value)) {
$checked_code = "checked=\"checked\"";
}
else {
$checked_code = "";
}
echo "<td><input name='check[]' type=checkbox value=$value id=checked $checked_code ></td>";
The verify_checked(value) function does (from what I understand of your database, you keep the "grid location" of checked elements):
function verify_checked($value)
{
// Connect to the database if needed
// Perform: SELECT count($value) FROM Report
// If the result is >0, return TRUE
// Else return FALSE
}
The idea here is to query the database every time your are about to echo the <input> element.
Note for concatenating text, I find it more legible to put spaces around the . to clearly split what is part of the text and what is the concatenation dot.
As mentioned previously, indentation is critical for understanding of the different contexts. Until I indented your code, I had not realized how the different loops worked in relation to the others.
I use this snippet to get vehicle data from a external database:
<form method="post" action="<?php echo $_SERVER['REQUEST_URI'] ?>" class="vwe-kenteken-widget">
<p><input type="text" name="open_data_rdw_kenteken" value="<?php echo $_POST['open_data_rdw_kenteken'] ?>" maxlength="8"></p>
<p><input name="submit" type="submit" id="submit" value="<?php _e('Kenteken opzoeken', 'open_data_rdw') ?>"></p>
</form>
<?php if($data): ?>
<h3><?php _e('Voertuiggegevens', 'open_data_rdw') ?></h3>
<table>
<?php
$categories = array();
foreach ($data as $d) {
if( !is_array($fields) || in_array($d['name'], $fields) ) {
if( !in_array($d['category'], $categories) ) {
$categories[] = $d['category'];
echo '<tr class="open-rdw-header">';
echo '<td colspan="2" style="font-weight: bold;">';
echo ''.$d['category'].'';
echo '</td>';
echo '</tr>';
}
echo '<tr style="display:none">';
echo '<td>'.$d['label'].'</td>';
echo '<td>'.$d['value'].'</td>';
echo '</tr>';
}
}
?>
</table>
<?php endif; ?>
What i want to accomplish is that the data is loaded without the user have to enter a value and hit the submit button. The input value will get loaded based on the product page the user is viewing.
EDIT:
The data is loaded based on:
public function get_json() {
if ( isset( $_POST['kenteken'] ) ) {
$data = $this->rdw->get_formatted($_POST['kenteken']);
foreach ($data as $row) {
$json['result'][$row['name']] = $row['value'];
}
if ($_POST['kenteken']) {
if ($data[0]['value'] == '') {
$json['errors'] = __( 'No license plates found', 'open_data_rdw' );
}
else {
$json['errors'] = false;
}
}
else {
$json['errors'] = __( 'No license plate entered', 'open_data_rdw' );
}
header('Content-type: application/json');
echo json_encode($json);
die();
}
}
So instead of a $_POST action just get the data based on a pre-declared value that is different on each page.
Hard to answer - but I'll try to use my crystal ball.
$data comes from a database query, right?
I assume further, that the query takes the value from the open_data_rdw_kenteken form field to gather $data.
To have the table rendered, you have to fill $data with the right data. That implies that you must have a kind of default value for open_data_rdw_kenteken to get the data out of the DB. The default can be "all" which should reflect on your SQL Query or as your wrote "defined by product page".
Pseudo Code
$data = getData('BT-VP-41');
function getData($open_data_rdw_kenteken="")
{
$where = "";
if(!empty($open_data_rdw_kenteken)) {
$where = 'WHERE rdw_kenteken = "'.mysqli_real_escape_string($open_data_rdw_kenteken)';
}
$data = myslqi->query("SELECT * FROM dbTbl ".$where)
return $data;
}
As I wrote - this is pseudo code and will not run out of the box. You'll have to adapt that to your environment.
TL;DR: The line
<?php if($data): ?>
keeps you from rendering the table. To render you need $data filled with the right data.
Hope that will get you in the right direction.
I want to get the introducer5 code for the employee code from that introducer5 code need to get the introducer4 code who introduce introducer4 like wise i want to get all their codes.
I have 7 levels of employee: 1) xxxx-7000
2) yyyy-6000
3)....
7) eeee -1000
<?php
if(isset($_POST['submit'])){
$introducer_code=$_POST['intro_code'];
function getOneLevel($intro_code)
{
$get_intro_code="SELECT * FROM `emp_details` WHERE `emp_code` = '".$intro_code."' ";
// echo $get_intro_code."</br>";
$exe_code=mysql_query($get_intro_code);
//$introducer_code=array();
$rows=mysql_num_rows($exe_code);
// echo $rows;
if($rows>0)
{
$get_role=mysql_fetch_array($exe_code);
$introducer_code= $get_role['intro_code'];
$compare_role1=" SELECT * FROM emp_details WHERE `emp_code` = '".$introducer_code."' ";
// echo $compare_role1."</br>";
$exe_role1=mysql_query($compare_role1);
$get_pos1=mysql_fetch_array($exe_role1);
//echo $get_pos1['emp_role'];
if($row_c=mysql_num_rows($exe_role1) > 0){
$compare_role="SELECT * FROM user_role WHERE `emp_role_id` = '".$get_pos1['emp_role']."' ";
echo $compare_role."</br>";
$exe_role=mysql_query($compare_role);
$get_pos=mysql_fetch_array($exe_role);
$id=$get_pos['id'];
}
}
$res=$id.','.$introducer_code;
echo $res."</br>";
return $res;
}
$compare_role2="SELECT * FROM emp_details WHERE `intro_code` = '".$introducer_code."'";
// echo $compare_role2 ."</br>";
$exe_role2=mysql_query($compare_role2);
if (mysql_num_rows($exe_role2)>0) {
//$n=7;
while ($get_pos=mysql_fetch_array($exe_role2)) {
//echo $get_pos['emp_code'];
// $c=$n-$id;
/* for($i=0;$i<$c;$i++){
echo "hi";*/
getOneLevel($get_pos['emp_code']);
// }
}
}
getOneLevel($introducer_code);
}
?>
<form method="post">
<div class="form-group">
<label>Introducer Code</label>
<input type="text" placeholder="Enter Introducer Code" id="intro_code" required="required" name="intro_code" class="form-control" />
</div>
<button value="Submit" type="submit" name="submit" >Submit</button>
</form>
The above code only returns the immediate introducer4 code for the value entered in the text box.It does not returning the introducer3 code who refers introducer4 and so on...
Please Help!!
Struggling more than 4 days!!
Try this may be useful
function getIntroducer($intro_code)
{
//Write your code to get introudcer and return it's Interducer id only
return $introudcer;
}
$finalInterducer = $intro_code //start
for($i=0;$i<5;$i++){ // If its 7 loop 7 time's
$finalInterducer = getIntroducer($finalInterducer)
}
//After loop you get last finalInterducer
Change the SQL Query, try this:
SELECT ED4.emp_code AS 'introducer4',
ED3.emp_code AS 'introducer3',
ED2.emp_code AS 'introducer2',
ED1.emp_code AS 'introducer1'
FROM emp_details ED1,emp_details ED2,emp_details ED3,emp_details ED4
WHERE ED4.emp_code = '".$introducer_code."'
AND ED3.emp_code = ED4.intro_code
AND ED2.emp_code = ED3.intro_code
AND ED1.emp_code = ED2.intro_code
All the best :)
I try to create an order page on php. I have created a form which stores data into the database. The form number is based on the user and it is created dynamic.
<?php
if(isset($_POST['submit_num']))
{
$number=$_POST['sky'];
for($i=0;$i<$number;$i++)
{
$item = $_SESSION['item'];
echo $item;
$rec_query = "SELECT * FROM ylika";
$rec_result= mysql_query($rec_query) or die("my eroors");
echo '<form action="user_order_form.php" method="POST">';
echo '<html>';
while($row_rec = mysql_fetch_array($rec_result))
{
echo '<input type="checkbox" name="yliko[]" value='.$row_rec['onoma'].'> '.$row_rec['onoma'].'';
echo '<br>';
}
echo '<br>';
echo '<input type="submit" name="submit" value="ORDER">';
echo '</form>';
}
}
?>
So I have many forms and 1 script to handle them. If I submit 1 form then it applies the data to the database but the other forms dissapear. This is the second php 'handler'.
<?php
if (isset($_POST['submit']))
{
$max_id = "SELECT MAX(id_order) FROM id_of_orders";
$x=mysql_query($max_id) or die("my eroors");
$id= mysql_fetch_array($x);
$xyz = $id['MAX(id_order)'];
$item = $_SESSION['item'];
$temp = $_POST['yliko'];
$temp2 = implode(",", $temp);
$inserts = ("INSERT INTO orders (order_id,product,ulika) VALUES ('$xyz' , '$item','$temp2')");
$inc_prod=("UPDATE proion SET Counter = Counter + 1 WHERE proion.onomasia='$item'");
mysql_query($inserts) or die(mysql_error());
mysql_query($inc_prod) or die(mysql_error());
}
?>
I want to submit all the forms. Should I try to create one submit button for all of the forms or is there a way to handle all of them separately ?
You can have many submit forms, but simply define one big <form> with all of them, then you will not lose any information.
<?php
if(isset($_POST['submit_num']))
{
$number=$_POST['sky'];
echo '<form action="user_order_form.php" method="POST">';
for($i=0;$i<$number;$i++)
{
$item = $_SESSION['item'];
echo $item;
$rec_query = "SELECT * FROM ylika";
$rec_result= mysql_query($rec_query) or die("my eroors");
echo '<html>';
while($row_rec = mysql_fetch_array($rec_result))
{
echo '<input type="checkbox" name="yliko[]" value='.$row_rec['onoma'].'> '.$row_rec['onoma'].'';
echo '<br>';
}
echo '<br>';
echo '<input type="submit" name="submit" value="ORDER">';
}
echo '</form>';
}
?>
now you can also add the ~$i~ identifier to input names, so you can easily distinguish which is which.
My main issue is the number of times I query the database (see below). Also, I would like to check that the current product (optionsToProducts.productID) has options for the current optionName before outputting the select statement! See the final image below to see the blank select box...
I have 8 tables in total, but the 3 that matter are:
optionNames
http://www.grabb.co.uk/stack/001.png
productOptions
http://www.grabb.co.uk/stack/002.png
optionsToProducts
http://www.grabb.co.uk/stack/003.png
<?php
$i=0;
$optionsquery = "SELECT * FROM optionNames WHERE categoryID = ".$categoryID."";
$optionsresult= mysql_query($optionsquery) or die(mysql_error());
while ($optionnames = mysql_fetch_array($optionsresult)) {
$i++;
$optionname = $optionnames["optionName"];
$optionID = $optionnames["optionNamesID"];
//echo $optionname."<br />";
?>
<label for="option<?php echo $i; ?>"><?php echo $optionname; ?></label>
<select name="option<?php echo $i; ?>" id="<?php echo $i; ?>">
<?php
//$optionvalues = "SELECT * FROM (optionsToProducts,productOptions) WHERE optionsToProducts.productID = ".$productID." AND productOptions.optionNamesID = ".$optionID."";
//echo $optionvalues."<br /><br />";
$optionvalues = "SELECT * FROM optionsToProducts WHERE productID = ".$productID."";
$valuesresult= mysql_query($optionvalues) or die(mysql_error());
while ($optionvals = mysql_fetch_array($valuesresult)) {
$valueName = $optionvals["optionValue"];
$valueID = $optionvals["productOptionsID"];
//echo $valueName."<br />";
$optionfinal = "SELECT * FROM productOptions WHERE productOptionsID = ".$valueID." AND optionNamesID = ".$optionID."";
$finalresult= mysql_query($optionfinal) or die(mysql_error());
while ($optionlast = mysql_fetch_array($finalresult)) {
$optionValueName = $optionlast["optionValue"];
$optionValueID = $optionlast["productOptionsID"];
$num_rows = mysql_num_rows($finalresult);
?>
<option value="<?php echo $optionValueID; ?>"><?php echo $optionValueName; ?></option>
<?php
}
}
echo "</select>";
}
?>
final Output:
http://www.grabb.co.uk/stack/004.png
As always, your help is appreciated. Thank you.
Since you tagged this question with the join tag, you probably know you need to write a join query to get what you need.
<?php
$i=0;
$query = "SELECT options.optionName, options.optionNamesID, po.optionValue, po.productOptionsID
FROM optionNames AS options
INNER JOIN productOptions AS po ON po.optionNamesID=options.optionNamesID
INNER JOIN optionsToProducts AS otp ON otp.productOptionsID=po.productOptionsID
WHERE otp.productID=" . (int) $productID
. " AND options.categoryID=" . (int) $categoryID;
$result = mysql_query($query);
if($result) {
$rows = array();
while($row = mysql_fetch_assoc($result) ) {
$rows[] = $row;
}
$i = 0;
$optionId = null;
foreach($rows as $row) {
if($optionId != $row['optionNamesID']) {
$optionId = $row['optionNamesID'];
?>
<label for="option<?php echo $optionId; ?>"><?php echo $row['optionName']; ?></label>
<select name="option<?php echo $optionId; ?>" id="<?php echo $optionId; ?>">
<?php } ?>
<option value="<?php echo $row['productOptionsID']; ?>"><?php echo $row['optionValue']; ?></option>
<?php
//Close select element when the optionNamesID changes or on the last row
if( (isset($rows[$i + 1]) && $rows[$i + 1]['optionNamesID'] != $optionId) ||
!isset($rows[$i + 1]) ) { ?>
</select>
<?php }
$i++;
}
} else {
//Debug query, remove in production
echo mysql_error();
}
?>
I also made some small changes - I use the optionNamesID in the select and label tag names - I don't know how you knew previously which select belonged to which option.
I also assumed that categoryID and productID came from somewhere, since it's not specified in the code.
Pushing all the rows to an array at the beginning is optional, but it makes the code a bit more organized (since you can check ahead in the array to see where to close the select tags).
NOTICE - this code is untested so there could some minor typos. Please make the needed corrections if necessary.