if checkbox checked enable his textarea - php

in this php code i have foreach loop create textarea with checkbox for each statement
i wanna to enable textarea if his checkbox is checked
but they have same id
<?php
foreach($Arows as $row){
echo '<tr class="row">
<th class="col-sm-12"><h4>'.$row['Type_A'].'</h4></th>
</tr>';
$stmt3 = $con->prepare("SELECT * FROM sous_analyse WHERE Id_A =".$row['Id_A']);
$stmt3->execute();
$SArows = $stmt3->fetchAll();//Analyse rows
foreach($SArows as $Srow){
echo '<tr class="row">
<td class="col-sm-4">'.$Srow['Parameter'].'</td>
<td class=" col-sm-5"><input type="text" class="form-control col-xl-12 border-secondary" name="Fonctionnalite" placeholder="RESULTATS" required=""></td>
<td class="col-sm-3 text-center">'.$Srow['Normal'].'</td>
</tr>';
}
echo '<tr class="row">
<th class="col-sm-12">
<div class="input-group">
<span class="input-group-addon form-check">
<span class="checkbox-custom checkbox-default">
<input type="checkbox" class="icheckbox-grey" id="inputUnchecked" name="inputUnchecked">
<label for="inputUnchecked"></label>
</span>
</span>
<textarea class="form-control" id="textareaDefault" rows="3" style="margin-top: 0px; margin-bottom: 0px; height: 60px;" disabled></textarea>
</div>
</th>
</tr>';
}
?>
i use this script but is working in first textarea
<script >
$(document).ready(function() {
$("#inputUnchecked").on('click', function() {
if($(this).is(':checked')){
$("#textareaDefault").prop('disabled',false);
} else {
$("#textareaDefault").prop('disabled',true);
}
alert("fdg");
})
});
</script>

Expanding on my comment, you will want to adjust your PHP. This is easily done with a counter ($c).
<?php
foreach($Arows as $row){
$html = "";
$html .= '<tr class="row">'."\r\n";
$html .= '<th class="col-sm-12"><h4>'.$row['Type_A'].'</h4></th>'."\r\n";
$html .= '</tr>'."\r\n";
$stmt3 = $con->prepare("SELECT * FROM sous_analyse WHERE Id_A =".$row['Id_A']);
$stmt3->execute();
$SArows = $stmt3->fetchAll();
$c = 1;
foreach($SArows as $Srow){
$html .= '<tr class="row">'."\r\n";
$html .= '<td class="col-sm-4">'.$Srow['Parameter'].'</td>';
$html .= '<td class=" col-sm-5"><input type="text" class="form-control col-xl-12 border-secondary" name="Fonctionnalite" placeholder="RESULTATS" required=""></td>';
$html .= '<td class="col-sm-3 text-center">'.$Srow['Normal'].'</td>';
$html .= '</tr>';
}
$html .= '<tr class="row">';
$html .= '<th class="col-sm-12">';
$html .= '<div class="input-group">';
$html .= '<span class="input-group-addon form-check">';
$html .= '<span class="checkbox-custom checkbox-default">';
$html .= '<input type="checkbox" class="icheckbox-grey" id="inputUnchecked-$c" name="inputUnchecked">';
$html .= '<label for="inputUnchecked-$c"></label>';
$html .= '</span></span>';
$html .= '<textarea class="form-control" id="textareaDefault-$c" rows="3" style="margin-top: 0px; margin-bottom: 0px; height: 60px;" disabled></textarea>';
$html .= '</div></th></tr>';
echo $html;
$c++;
}
?>
Your JavaScript can then use the ID since it is unique or can simply be relative to nearby elements.
$(function() {
$("[id^='inputUnchecked-']").on('click', function() {
if($(this).is(':checked')){
$(this).parent().parent().find("[id^='textareaDefault-']").prop('disabled',false);
} else {
$(this).parent().parent().find("[id^='textareaDefault-']").prop('disabled',true);
}
alert("fdg");
})
});

Related

How do I add a color written in PHP?

Is it possible to add color on approve and decline, basically green for approve and red for declined? I've tried looking it up but I can't seem to find a way to do it.
Here's the php code:
<?php
if(isset($_POST['approve']))
{
$msg = "Approved";
$approval="Approved";
}
if(isset($_POST['decline']))
{
$msg = "Declined";
$approval="Declined";
}
$reqnumber=$_POST['reqnumber'];
$con = mysqli_connect('localhost', 'root', '');
mysqli_select_db($con, 'pcrequest');
$sql = "UPDATE request SET approval = '$approval' WHERE reqnumber = '$reqnumber'";
if(mysqli_query($con, $sql))
header("refresh:1; url=messages-admin.php?msg=$msg");
else
var_dump(mysqli_error($con));
?>
HTML:
<div class="container" style="width: 1370px; margin-left: -40px;">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">Search</span>
<input type="text" name="search_text" id="search_text" placeholder="Search by Employee Name, Account, Platform, etc." class="form-control" />
</div>
</div>
<div id="result"></div>
</div>
</div>
</div>
Fetch:
$output .= '<tr>
<td>'.$row["reqname"].'</td>
<td>'.$row["month"]."/".$row["day"]."/".$row["year"].'</td>
<td>'.$row["empname"].'</td>
<td>'.$row["position"].'</td>
<td>'.$row["account"].'</td>
<td>'.$row["platform"].'</td>
<td>'.$row["processor"].'</td>
<td>'.$row["ram"].'</td>
<td>'.$row["monitor"].'</td>
<td>'.$row["phone"].'</td>
<td>'.$row["phonetype"].'</td>
<td>'.$row["headset"].'</td>
<td>'.$row["approval"].'</td>';
if ($row['status']) :
$output .= '<td>'.$row["status"].'</td> ';
else:
$output .= '
<td>
<form method="post" action="update-request-status.php">
<input type="hidden" name="reqnumber" value="'.$row['reqnumber'].'" />
<button class="button" type="submit" name="completed" value=""><span>New Request!</span></button>
</form>
</td>
<td><i class="fa fa-edit" style="color: black; font-size: 25px;"></i></td>
<td><i class="fa fa-trash" style="color: red; font-size: 25px;"></i></td>
</tr>
';
endif;
I've added the HTML and PHP code, as you can see HTML is fetching data from PHP.
Store your color in a variable and use it wherever you want to colorize
$color = $row["approval"] == "Approved" ? "green" : "red";
//Then use $color in any element you want to colorize
'<td style="color:' . $color . ';">' .$row["approval"] . '</td>';
or use that
'<td style="color:' . ($row["approval"] == "Approved" ? "green" : "red") . ';">' .$row["approval"] . '</td>';
For multiple colors, use an array()
$colors = array();
$colors["Approved"] = "green";
$colors["Declined"] = "red";
$colors["Pending"] = "blue";
<td style="color:' . $colors[$row["approval"]] . ';">' .$row["approval"] . '</td>';
You can use php to generate css and html.
<?php
if(isset($_POST['approve']))
{
$msg = "Approved";
$approval="Approved";
$color = "green";
}
else if(isset($_POST['decline']))
{
$msg = "Declined";
$approval="Declined";
$color="red";
}
?>
$output .= '<tr>
<td>'.$row["reqname"].'</td>
<td>'.$row["month"]."/".$row["day"]."/".$row["year"].'</td>
<td>'.$row["empname"].'</td>
<td>'.$row["position"].'</td>
<td>'.$row["account"].'</td>
<td>'.$row["platform"].'</td>
<td>'.$row["processor"].'</td>
<td>'.$row["ram"].'</td>
<td>'.$row["monitor"].'</td>
<td>'.$row["phone"].'</td>
<td>'.$row["phonetype"].'</td>
<td>'.$row["headset"].'</td>
<td' . 'style="color:' . $color . '"><?=$msg?>>'.$row["approval"].'</td>';
if ($row['status']) :
$output .= '<td>'.$row["status"].'</td> ';
else:
$output .= '
<td>
<form method="post" action="update-request-status.php">
<input type="hidden" name="reqnumber" value="'.$row['reqnumber'].'" />
<button class="button" type="submit" name="completed" value=""><span>New Request!</span></button>
</form>
</td>
<td><i class="fa fa-edit" style="color: black; font-size: 25px;"></i></td>
<td><i class="fa fa-trash" style="color: red; font-size: 25px;"></i></td>
</tr>
';
endif;

Functions inside a Loop

I've been staring at code all day, and I just can't seem to find what im looking for, I know how to do this with PHP but I'm new to dynamic stuff.
This code is inside a loop that is generated by a database. The dropdown items are fixed, but each individual is inside a database. I want to be able to choose the next drop down box selections based on the first one. This code works but not for each individual in the loop. Each item in the loop just updates the top one.
<div class="grid-container-fluid" style="margin-bottom: 25px;">
<div class="grid-container" style="font-family: 'Roboto Condensed', sans-serif;">
<div class="grid-x align-center">
<div class="large-10 cell">
<div class="grid-x">
<?php
if ($result->num_rows > 0) {
echo '<div class="large-12 cell">';
echo '<p style="font-family: Roboto Condensed, sans-serif; letter-spacing: 2px; font-weight: bold; line-height:1; font-size: 30px;">ADMIN PANEL:</p>';
echo '<p style="font-family: Roboto Condensed, sans-serif; font-size: 20px;">Income: $'.$total.'/mo<br>Program Value: $'.$value.'/person</p>';
echo '</div>';
echo '<div class="large-12 hide-for-small-only cell" style="border-bottom: 3px black solid; padding-bottom: 5px;">';
echo '<div class="grid-x">';
echo '<div class="medium-auto small-6 cell">';
echo '<p align="left" style="margin: 0;">NAME</p>';
echo '</div>';
echo '<div class="medium-auto small-6 cell">';
echo '<p align="left" style="margin: 0;">EMAIL</p>';
echo '</div>';
echo '<div class="medium-auto small-6 cell">';
echo '<p align="left" style="margin: 0;">PROGRAM</p>';
echo '</div>';
echo '<div class="medium-auto small-6 cell">';
echo '<p align="left" style="margin: 0;">PLAN</p>';
echo '</div>';
echo '<div class="medium-2 small-6 cell">';
echo '<p align="left" style="margin: 0;">STATUS</p>';
echo '</div>';
echo '<div class="medium-1 small-12 cell" style="padding-left: 15px;">';
echo '<p style="margin:0; text-align: center">';
echo '<i class="fi-wrench"></i>';
echo '</p>';
echo '</div>';
echo '</div>';
echo '</div>';
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<div class="large-12 cell" style="border-bottom: 1px black solid; padding: 5px;">';
echo '<div class="grid-x align-middle">';
echo '<div class="medium-auto small-12 cell" style="padding:2px;">';
echo '<input style="background-color: white; border: 0; margin: 0;" value="'.$row["name"].'" name="name">';
echo '</div>';
echo '<div class="medium-auto small-12 cell" style="padding:2px;">';
echo '<input style="background-color: white; border: 0; margin: 0;" value="'.$row["email"].'" name="email">';
echo '</div>';
echo '<div class="medium-auto small-12 cell" style="padding:2px;">';
echo '<select style="margin: 0; height: auto; border: 0;" name="program" id="program" onChange="changecat(this.value, '.$value.');">';
echo '<option value="" disabled selected>'.$row["program"].'</option>';
echo '<option value="Hockey">Hockey</option>';
echo '<option value="Fundamentals">Fundamentals</option>';
echo '</select>';
echo '</div>';
echo '<div class="medium-auto small-12 cell" style="padding:2px;">';
echo '<select style="margin: 0; height: auto; border: 0;" name="plan" id="plan">';
echo '<option value="" disabled selected>'.$row["plan"].'</option>';
echo '</select>';
echo '</div>';
?>
<script>
var programsByplan = {
Hockey: ["Off Season", "Pre Season", "In Season"],
Fundamentals: ["Phase 1"],
}
function changecat(value) {
if (value.length == 0) document.getElementById("plan").innerHTML = "<option></option>";
else {
var catOptions = "";
for (planId in programsByplan[value]) {
catOptions += "<option>" + programsByplan[value][planId] + "</option>";
}
document.getElementById("plan").innerHTML = catOptions;
}
}
</script>
<?php
echo '<div class="medium-2 small-12 cell">';
echo '<div class="grid-x align-middle">';
echo '<div class="small-6 cell">';
echo '<select style="margin: 0; height: auto; border: 0;" name="week">';
echo '<option value="'.$row["week"].'">' . 'Week ' . $row["week"] . '</option>';
echo '<option value="1">Week 1</option>';
echo '<option value="2">Week 2</option>';
echo '<option value="3">Week 3</option>';
echo '<option value="4">Week 4</option>';
echo '<option value="5">Week 5</option>';
echo '<option value="6">Week 6</option>';
echo '<option value="7">Week 7</option>';
echo '<option value="8">Week 8</option>';
echo '<option value="9">Week 9</option>';
echo '<option value="10">Week 10</option>';
echo '<option value="11">Week 11</option>';
echo '<option value="12">Week 12</option>';
echo '<option value="13">Week 13</option>';
echo '<option value="14">Week 14</option>';
echo '<option value="15">Week 15</option>';
echo '</select>';
echo '</div>';
echo '<div class="small-6 cell">';
echo '<select style="margin: 0; height: auto; border: 0;" name="day">';
echo '<option value="'.$row["day"].'">' . 'Day ' . $row["day"] . '</option>';
echo '<option value="1">Day 1</option>';
echo '<option value="2">Day 2</option>';
echo '<option value="3">Day 3</option>';
echo '<option value="4">Day 4</option>';
echo '</select>';
echo '</div>';
echo '</div>';
echo '</div>';
echo '<div class="medium-1 small-12 cell" style="padding-left: 15px;">';
echo '<p style="margin:0; text-align: center">';
echo '<input style="font-size: 12px;" class="expanded button nav" type="submit" value="Update" name="submit" id="submit"/>';
echo '</p>';
echo '</div>';
echo '</div>';
echo '</div>';
}
}
?>
</div>
</div>
</div>
</div>
</div>
I know it needs a unique id, I just can't figure out where.
Something like this:
echo '<div class="medium-auto small-12 cell" style="padding:2px;">';
echo '<select style="margin: 0; height: auto; border: 0;" name="program" id="program-'.$row['id'].'" >';
echo '<option value="" disabled selected>'.$row["program"].'</option>';
echo '<option value="Hockey">Hockey</option>';
echo '<option value="Fundamentals">Fundamentals</option>';
echo '</select>';
echo '</div>';
echo '<div class="medium-auto small-12 cell" style="padding:2px;">';
echo '<select style="margin: 0; height: auto; border: 0;" name="plan" id="plan-'.$row['id'].'">';
echo '<option value="" disabled selected>'.$row["plan"].'</option>';
echo '</select>';
echo '</div>';
?>
<script>
var programsByplan = {
Hockey: ["Off Season", "Pre Season", "In Season"],
Fundamentals: ["Phase 1"],
}
$('select[name="program"]').change(function(){
var program = $(this).val();
var plan_id = $(this).prop('id').replace('program', 'plan');
if(programsByplan[program]){
var options = [];
$.each(programsByplan[program], function(i,v){
options.push('<option value="'+v+'">'+v+'</option>');
});
$('#'+plan_id).html(options.join("\n"));
}else{
//or, do somkind of error recovery here.
$('#'+plan_id).html('<option value="">No Plans</option>');
}
});
</script>
I would get rid of the onChange, I'm also making heavy use of jQuery, but the question is tagged with it.
So on the change of any select with the name program (which we haven't changed, so they all have the same name) we trigger the event callback. You could also do this part with a class, of course.
In the callback we get the value selected in the current select, then we check that it exists in programsByplan (which it always should) but doesn't hurt to check.
Then we convert the program id program-'.$row['id'].' to plan-'.$row['id'].'. Now we know which plan select to change. I prefer using an array to add the options, but you could do the += thing. And then it's a simple matter to replace them, now that we know the plan elements id, with .html().
I haven't tested this but it should be pretty close. The big thing is setting yourself up to succeed by having the id easy to correlate, or in other words easy to find the right plan element for the changed program element.
I am also assuming you have a $row['id'] that is at least unique to the loop that generates these.
Update
But how do I get the options to show up on page load when the program/plan is proper from the database
I would further change it like this:
//outside of the loop define your data
$programsByplan = [
'Hockey' => ["Off Season", "Pre Season", "In Season"],
'Fundamentals' => ["Phase 1"],
];
//inside the loop
echo '<div class="medium-auto small-12 cell" style="padding:2px;">';
echo '<select style="margin: 0; height: auto; border: 0;" name="program" id="program-'.$row['id'].'" >';
foreach($programsByplan as $program => $plans){
//$selected = $row["program"] == $program ? 'disabled selected' : '';
$selected = $row["program"] == $program ? 'selected="selected"' : '';
echo '<option value="'.$program.'" '.$selected.'>'.$program.'</option>';
}
echo '</select>';
echo '</div>';
echo '<div class="medium-auto small-12 cell" style="padding:2px;">';
echo '<select style="margin: 0; height: auto; border: 0;" name="plan" id="plan-'.$row['id'].'">';
foreach($programsByplan[$row["program"]] as $plan){
//$selected = $row["plan"] == $plan ? 'disabled selected' : '';
$selected = $row["plan"] == $plan ? 'selected="selected"' : '';
echo '<option value="'.$plan.'" '.$selected.'>'.$plan.'</option>';
}
echo '</select>';
echo '</div>';
?>
<script>
var programsByplan = <?php echo json_encode($programsByplan); ?>;
//... other code
Here we are adding $programsByplan in PHP, then with json_encode we can add the same array to Javascript, which is awesomeness. Hopeful this works
var programsByplan = <?php echo json_encode($programsByplan); ?>;
Sometimes it can take a bit of fiddling to, but it has huge benefits in maintainability for the code. Because you are using only one authoritative source for the data for that. As opposed to it being spread everywhere. A side benefit of this is, if you go and make the programs and plans as two tables with a Many to One relationship you could put those in the DB and easily update the code by building that array. See if the data is just spread out hard coded then it's difficult to make changes like that later.
It also lets us fix a few of the other issues you had with building the selects originally, and just simplifies the code. One big issue was removing the value on the selected items, and having duplicate items.
echo '<option value="" disabled selected>'.$row["program"].'</option>';
You are actually removing the value here, which is probably not what you want. I am also not sure about the disabled bit, so I just left that in. Maybe that was just there to fix the selection issues from initializing it? Anyway I put that part in a comment. I've always done selected like this:
$selected = $row["program"] == $program ? 'selected="selected"' : '';
It's probably the "old-school" way of doing it but it always worked for me.
Anyway, and obviously if we try to get the value of the selected option and its value has been removed, it probably wont work out to good. Not to mention there is no way to "know" what that is to remove the option with the same value when it's just hard coded in like it was and so you'll wind up with a duplicate option for it.
This should fix most of that, but this is all done in my head, so hopefully it all works out like I am thinking it should. The theory is sound anyway.
You can test it in this sandbox:
http://sandbox.onlinephpfunctions.com/code/077c8a988697122549713ede9c305bf4f7620ed9
using (As canned data for a row.)
$row = [
'id' => 1,
'program' => 'Hockey',
'plan' => 'Off Season'
];
Which outputs:
<div class="medium-auto small-12 cell" style="padding:2px;">
<select style="margin: 0; height: auto; border: 0;" name="program" id="program-1" >
<option value="Hockey" selected="selected">Hockey</option>
<option value="Fundamentals" >Fundamentals</option>
</select>
</div>
<div class="medium-auto small-12 cell" style="padding:2px;">
<select style="margin: 0; height: auto; border: 0;" name="plan" id="plan-1">
<option value="Off Season" selected="selected">Off Season</option>
<option value="Pre Season" >Pre Season</option>
<option value="In Season" >In Season</option>
</select>
</div>
As you can see we have program-1 and plan-1 our ID's, then both selects have the proper element with selected="selected"
Update2
To handle cases where no data was previously selected for the program.
For the first loop above I would add this
//echo <select ...
echo '<option value="" > - Please select a program - </option>';
//foreach( ...
Do it before the loop and after the opening for the <select. Then for the second loop I would disable the second select, until they make a choice in the first.
$disabled = empty($row["program"]) ? 'disabled="disabled"': '';
echo '<select style="margin: 0; height: auto; border: 0;" name="plan" id="plan-'.$row['id'].'" '.$disabled.'>';
And then in the Javascript
$('select[name="program"]').change(function(){
var program = $(this).val();
if(program == '' ) return; //exit on empty selection
var plan_id = $(this).prop('id').replace('program', 'plan');
//enable the select if disabled.
$('#'+plan_id).attr('disabled',false);
Then you may just want to check before saving it that they selected a program etc. etc..
Update3
For any Javascript issues always use the debug window in the browser (f12) then click on console. Then in your code you can just do like
console.log(var);
And it will print that value in the console. It's simular to PHP's var_export, print_r or var_dump etc...
So I would start with this
<script>
var programsByplan = <?php echo json_encode($programsByplan); ?>;
console.log(programsByplan);
$('select[name="program"]').change(function(){
var program = $(this).val();
console.log(program);
var plan_id = $(this).prop('id').replace('program', 'plan');
console.log(programsByplan[program]);
if(programsByplan[program]){
var options = [];
$.each(programsByplan[program], function(i,v){
options.push('<option value="'+v+'">'+v+'</option>');
});
$('#'+plan_id).html(options.join("\n"));
}else{
//or, do somkind of error recovery here.
$('#'+plan_id).html('<option value="">No Plans</option>');
}
});
</script>
And so on and see what the values are. That's probably the best way.
Cheers.

Foreign Key In Php to get data from another table

function show_username($connect)
{
$output = '';
$query = "SELECT * from users";
$res = mysqli_query($connect, $query);
while($row = mysqli_fetch_array($res))
{
$output .= '<option value="'.$row["id"].'">'.$row["name"].'</option>';
{
}
return $output;
}
function show_offer($connect)
{
$output = '';
$query = "SELECT * FROM add_offer ORDER BY id DESC";
$res = mysqli_query($connect, $query);
while($row = mysqli_fetch_array($res))
{
$output .= '<div class="col-md-3 col-sm-4 col-lg-6">';
$output .= '<div class="panel panel-default">';
$output .= '<div class="panel-body">';
$output .= '<div style="padding:1px;float:left;font-weight:bold;">'.$row["part_no"].'</div>';
$output .= '<div style="padding:1px;float:left;">'.$row["make"].'</div>';
$output .= '<div style="padding:1px;float:left;">'.$row["date_code"].'</div>';
$output .= '<div style="padding:1px;float:left;">'.$row["qty"].'</div>';
$output .= '<br>';
$output .= '<div style="float:left;font-size:9px;">'.$row["time"].'</div>';
$output .= '</div>';
$output .= '</div>';
$output .= '</div>';
}
echo $output;
}
<div class="container">
<div class="row">
<div class="col-lg-offset-3 col-lg-6">
<div class="panel">
<div class="panel panel-default" style="border: 1px solid #66512c;">
<div class="panel-heading" style="background-color: #66512c;color: white;">
Market Offers
</div>
<div class="panel-body" style="padding: 0px;padding-left: 5px;border-bottom: 1px solid #66512c;">
<div class="nav nav-pills nav-stacked">
<select name="category" id="user" class="form-control">
<option selected="" value="" class="form-control">All User Offers</option>
<?php echo show_username($connect); ?>
</select>
<div class="panel panel-body" id="show_offer">
<?php echo show_offer($connect);?>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-lg-3"></div>
</div>
<script>
$(document).ready(function(){
$('#user').change(function(){
var user_id = $(this).val();
$.ajax({
url:"load_data.php",
method:"POST",
data:{user_id:user_id},
success:function(data){
$('#show_offer').html(data);
}
});
});
});</script>
<?php
//load_data.php
$connect = mysqli_connect("localhost", "root", "", "customer");
$output = '';
if(isset($_POST["user_id"]))
{
if($_POST["user_id"] != '')
{
$query = "SELECT * FROM add_offer WHERE user_id = '".$_POST["user_id"]."' ORDER BY id DESC";
}
else
{
$query = "SELECT * FROM add_offer ORDER BY id DESC";
}
$res = mysqli_query($connect, $query);
while($row = mysqli_fetch_array($res))
{
$output .= '<div class="col-md-3 col-sm-4 col-lg-6">';
$output .= '<div class="panel panel-default">';
$output .= '<div class="panel-body">';
$output .= '<div style="padding:1px;float:left;font-weight:bold;">'.$row["part_no"].'</div>';
$output .= '<div style="padding:1px;float:left;">'.$row["make"].'</div>';
$output .= '<div style="padding:1px;float:left;">'.$row["date_code"].'</div>';
$output .= '<div style="padding:1px;float:left;">'.$row["qty"].'</div>';
$output .= '<br>';
$output .= '<div style="float:left;font-size:9px;">'.$row["time"].'</div>';
$output .= '</div>';
$output .= '</div>';
$output .= '</div>';
}
echo $output;
}?>
In this above code I have used functions to take data from 2 seperate table and I want to display the table in the following format as
name from users table
part_no,make,date_code,qty from add_offers table
the image shows my output market_offers page
I want the data not to be selected by dropdown but has to display whole data as first with name from users table and followed by users part_no from add_offers table.
Also the timestamp display as 2018-03-22 12.40.55 which i want as 22-03-2018 12.40.55
You've to change your code as bellow:
function show_username($connect)
{
$output = '';
$query = "SELECT * from users order by id asc";
$res = mysqli_query($connect, $query);
while($row = mysqli_fetch_array($res))
{
$output .= '<option value="'.$row["id"].'">'.$row["name"].'</option>';
{
}
return $output;
}
function show_offer($connect)
{
$output = '';
$user_query = "SELECT * from users order by id asc";
$user_res = mysqli_query($connect, $user_query );
$user_row = mysqli_fetch_array($user_res);
$query = "SELECT * FROM add_offer where user_id = ".$user_row['id']." ORDER BY id DESC";
$res = mysqli_query($connect, $query);
while($row = mysqli_fetch_array($res))
{
$output .= '<div class="col-md-3 col-sm-4 col-lg-6">';
$output .= '<div class="panel panel-default">';
$output .= '<div class="panel-body">';
$output .= '<div style="padding:1px;float:left;font-weight:bold;">'.$row["part_no"].'</div>';
$output .= '<div style="padding:1px;float:left;">'.$row["make"].'</div>';
$output .= '<div style="padding:1px;float:left;">'.date('d-m-Y H:i:s',strtotime($row["date_code"])).'</div>';
$output .= '<div style="padding:1px;float:left;">'.$row["qty"].'</div>';
$output .= '<br>';
$output .= '<div style="float:left;font-size:9px;">'.$row["time"].'</div>';
$output .= '</div>';
$output .= '</div>';
$output .= '</div>';
}
echo $output;
}
Html Code:
<div class="container">
<div class="row">
<div class="col-lg-offset-3 col-lg-6">
<div class="panel">
<div class="panel panel-default" style="border: 1px solid #66512c;">
<div class="panel-heading" style="background-color: #66512c;color: white;">
Market Offers
</div>
<div class="panel-body" style="padding: 0px;padding-left: 5px;border-bottom: 1px solid #66512c;">
<div class="nav nav-pills nav-stacked">
<select name="category" id="user" class="form-control">
<option selected="" value="" class="form-control">All User Offers</option>
<?php echo show_username($connect); ?>
</select>
<div class="panel panel-body" id="show_offer">
<?php echo show_offer($connect);?>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-lg-3"></div>
</div>
Java Script Code:
<script>
$(document).ready(function(){
$('#user').change(function(){
var user_id = $(this).val();
$.ajax({
url:"load_data.php",
method:"POST",
data:{user_id:user_id},
success:function(data){
$('#show_offer').html(data);
}
});
});
});</script>
PHP Code:
<?php
//load_data.php
$connect = mysqli_connect("localhost", "root", "", "customer");
$output = '';
if(isset($_POST["user_id"]))
{
if($_POST["user_id"] != '')
{
$query = "SELECT * FROM add_offer WHERE user_id = '".$_POST["user_id"]."' ORDER BY id DESC";
}
else
{
$query = "SELECT * FROM add_offer ORDER BY id DESC";
}
$res = mysqli_query($connect, $query);
while($row = mysqli_fetch_array($res))
{
$output .= '<div class="col-md-3 col-sm-4 col-lg-6">';
$output .= '<div class="panel panel-default">';
$output .= '<div class="panel-body">';
$output .= '<div style="padding:1px;float:left;font-weight:bold;">'.$row["part_no"].'</div>';
$output .= '<div style="padding:1px;float:left;">'.$row["make"].'</div>';
$output .= '<div style="padding:1px;float:left;">'.$row["date_code"].'</div>';
$output .= '<div style="padding:1px;float:left;">'.$row["qty"].'</div>';
$output .= '<br>';
$output .= '<div style="float:left;font-size:9px;">'.$row["time"].'</div>';
$output .= '</div>';
$output .= '</div>';
$output .= '</div>';
}
echo $output;
}?>

Adding Sort by Price and Sort by Name

I created a website selling components. Each component has 9 products. How can I add a dropdown button which can arrange the product showing by its Price or Name?
<?php
$query = "SELECT * FROM products ORDER BY id ASC";
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
?>
<div class="col-md-4">
<form method="post" action="shop.php?action=add&id=<?php echo $row["id"]; ?>">
<div style="border: 1px solid #eaeaec; margin: -1px 19px 3px -1px; box-shadow: 0 1px 2px rgba(0,0,0,0.05); padding:10px;" align="center">
<h5 class="text-info"><?php echo $row["p_name"]; ?></h5>
<img src="<?php echo $row["image"]; ?>" class="img-responsive">
<h5 class="text-danger">$ <?php echo $row["price"]; ?></h5>
<div class="col-xs-8">
<input type="text" name="quantity" class="form-control" value="1">
</div>
<input type="hidden" name="hidden_name" value="<?php echo $row["p_name"]; ?>">
<input type="hidden" name="hidden_price" value="<?php echo $row["price"]; ?>">
<input type="submit" name="add" class="btn btn-primary" value="Add to Cart" align="right">
</div>
</form>
</div>
<?php
}
}
?>
<?php
}
?>
</div>
</div>
Perhaps you could use Javascript as well and add a few select boxes to give Users the chance to choose the Attribute they want to sort by and also the Direction of the Sorting as in ASC or DESC. The Code Snippet below might shed some light:
<?php
$query = "SELECT * FROM products ORDER BY id ASC";
$result = mysqli_query($connect, $query);
// CREATE VARIABLES TO HOLD THE SELECT OPTIONS VALUES FOR THE SORTING...
$sortParam1 = 'price';
$sortParam2 = 'name';
$sortDir1 = 'ASC';
$sortDir2 = 'DESC';
// START BUILDING THE OUTPUT...
$output = "<div class='col-md-12'>"; //<== WRAPPER FOR SORING & DIRECTION BOXES
$output .= "<form method='post' action='' id='sorting_form'>"; //<== FORM FOR THE SORTING: SUBMITS TO SAME SCRIPT
// SORTING
$output .= "<div class='col-md-6'>";
$output .= "<select name='sorting' id='sorting'class='form-control'>";
$output .= "<option value='id'>Sorting</option>";
$output .= "<option value='{$sortParam1}'>{$sortParam1}</option>";
$output .= "<option value='{$sortParam2}'>{$sortParam2}</option>";
$output .= "</select>";
$output .= "</div>";
// DIRECTION
$output .= "<div class='col-md-6'>";
$output .= "<select name='direction' id='direction'class='form-control'>";
$output .= "<option value='ASC'>Sort Direction</option>";
$output .= "<option value='{$sortDir1}'>{$sortDir1}</option>";
$output .= "<option value='{$sortDir2}'>{$sortDir2}</option>";
$output .= "</select>";
$output .= "</div>";
$output .= "</form>"; //<== CLOSE SORTING FORM...
$output .= "</div>"; //<== CLOSE WRAPPER...
$rowData = "";
// WE USE JQUERY BELOW TO SUBMIT THE SORTING FORM ONCE USER
// SELECTS ANY OPTION FROM.... SO WE NOW HANDLE THAT SCENARIO HERE USING PHP
if(isset($_POST['sorting']) || isset($_POST['direction']) ){
$sortDirection = isset($_POST['direction']) ? $_POST['direction'] : $sortDir1; // DEFAULTS TO ASC
$sortField = isset($_POST['sorting']) ? $_POST['sorting'] : 'id'; // DEFAULTS TO id
$query = "SELECT * FROM products ORDER BY {$sortField} {$sortDirection}";
$result = mysqli_query($connect, $query);
}
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)) {
// USE HEREDOC TO CAPTURE THE DATA WITHIN THE LOOP...
$rowData .=<<<R_DATA
<div class="col-md-4">
<form method="post" action="shop.php?action=add&id={$row["id"]}">
<div style="border: 1px solid #eaeaec; margin: -1px 19px 3px -1px; box-shadow: 0 1px 2px rgba(0,0,0,0.05); padding:10px;" align="center">
<h5 class="text-info">{$row["p_name"]}</h5>
<img src="{$row["image"]}" class="img-responsive">
<h5 class="text-danger">\$ {$row["price"]}</h5>
<div class="col-xs-8">
<input type="text" name="quantity" class="form-control" value="1">
</div>
<input type="hidden" name="hidden_name" value="{$row["p_name"]}">
<input type="hidden" name="hidden_price" value={$row["price"]}">
<input type="submit" name="add" class="btn btn-primary" value="Add to Cart" align="right">
</div>
</form>
</div>
R_DATA;
} // CLOSE WHILE LOOP
} // CLOSE IF CONDITIONAL LOGIC
// ADD THE DATA GATHERED FROM WHILE LOOP ($rowData) TO THE OUTPUT: $output
$output .= $rowData;
$output .= "</div>\n</div>"; // THESE APPEAR IN YOUR CODE BUT SEEM IRRELEVANT HERE...
// DISPLAY THE OUTPUT
echo $output;
?>
<!-- ENTER JAVASCRIPT: JQUERY -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js" integrity="sha384-I6F5OKECLVtK/BL+8iSLDEHowSAfUo76ZL9+kGAgTRdiByINKJaqTPH/QVNS1VDb" crossorigin="anonymous"></script>
<script type="text/javascript">
(function($){
$(document).ready(function(e){
var sortForm = $("#sorting_form");
var sortBox = $("#sorting");
var directionBox = $("#direction");
var bothBoxes = sortBox.add(directionBox);
// IF EITHER OF THE SORTING OR DIRECTION IS CHANGED
// JUST SUBMIT THE FORM
bothBoxes.on("change", function(evt){
sortForm.submit();
});
});
})(jQuery);
</script>

Fix Table Output for PHP

I am trying to make a table in PHP.
There is form where I am taking in Value - Market, Production Date, Sales Date and sending it in POST to Table to get it populated.
At the POST I am calling a set of data from production table from MySQL and populating in the same table.
I am able to populate the table from SQL and Form POST Action but I am not able to align them as per the required output format.
Please help in finding fix for the below Code:
<?php
if(isset($_POST['for_post']))
{
try
{
?>
<div class="card-box" style="padding-left:5px;padding:10px;padding-bottom:50px">
<div class="row">
<div class="col-sm-12">
<?php
if(isset($_POST['for_post_market'])){ $pname = $_POST['for_post_market']; }
if(isset($_POST['for_post_prod_date'])){ $pcat = $_POST['for_post_prod_date']; }
if(isset($_POST['for_post_sale_date'])){ $pprice = $_POST['for_post_sale_date']; }
$query = 'SELECT * FROM product';
$stmt = $DB_con->prepare($query);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$result[$row['prod_cat_name']][] = $row['prod_name'];
}
?>
<table id="invoices" border="1">
<thead>
<th>Category</th>
<th>Product</th>
<th>Production Date</th>
<th>Sales Date</th>
<th>Market</th>
</thead>
<tbody>
<?php
foreach($result as $id => $invoices) {
echo '<tr>';
echo '<td rowspan='. count($invoices) . '>' . $id . '</td>';
$count = 0;
foreach ($invoices as $invoice) {
if ($count != 0) {
echo '<tr>';
}
echo "<td>$invoice</td>";
echo "<td>".$pcat."</td>";
echo "<td>".$pprice."</td>";
$count++;
}
}
$a=count($pname);
for($i=0;$i<$a;$i++)
{
echo "<td>".$pname[$i]."</td></tr>";
}
echo "</tbody>";
echo "</table>";
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
else
{ ?>
</div>
</div>
</div>
<div class="card-box" style="padding-left:5px;padding:10px;padding-bottom:50px">
<div class="row">
<div class="col-sm-12">
<form class="form-inline" method="post">
<div class="form-group m-r-10">
<label for="exampleInputName2">Market : </label>
<div class="input-group">
<select class="selectpicker" multiple data-selected-text-format="count" data-style="btn-white" name="for_post_market[]">
<?php
$stmt = $DB_con->prepare('Select * from location');
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo '<option>'.$row['location_name'].'</option>';
}
?>
</select>
<div>
&nbsp
<div class="form-group m-r-10">
<label for="exampleInputEmail2">Production Date : </label>
<div class="input-group">
<input type="text" class="form-control" placeholder="mm/dd/yyyy" id="datepicker-autoclose" name="for_post_prod_date">
<span class="input-group-addon bg-custom b-0 text-white"><i class="icon-calender"></i></span>
</div>
</div>
<div class="form-group m-r-10">
<label for="exampleInputEmail2">Sales Date : </label>
<div class="input-group">
<input type="text" class="form-control" placeholder="mm/dd/yyyy" id="datepicker2-autoclose" name="for_post_sale_date">
<span class="input-group-addon bg-custom b-0 text-white"><i class="icon-calender"></i></span>
</div>
</div>
<button type="submit" class="btn btn-default waves-effect waves-light btn-md" id="for_post" name="for_post">
Submit
</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<?php
}
?>
The Current Output that I am able to get from this code is :
What I am trying to get is :
Updated Changes Suggested and worked:
<table id="invoices" border="1">
<thead>
<th>Category</th>
<th>Product</th>
<th>Production Date</th>
<th>Sales Date</th>
<th>Market</th>
<th>Input</th>
</thead>
<tbody>
<?php
$a=count($pname);
foreach($result as $id => $invoices) {
echo '<tr>';
echo '<td rowspan='. count($invoices)*$a . '>' . $id . '</td>';
$count = 0;
foreach ($invoices as $invoice) {
if ($count != 0) {
echo '<tr>';
}
echo '<td rowspan='. count($pname) . '>' . $invoice . '</td>';
echo '<td rowspan='. count($pname) . '>' . $pcat . '</td>';
echo '<td rowspan='. count($pname) . '>' . $pprice . '</td>';
for($i=0;$i<$a;$i++)
{
echo '<td>'. $pname[$i] . '</td>';
echo '<td><input type="text" class="form-control"></td></tr>';
}
$count++;
}
}
echo '</tbody>';
echo '</table>';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
else
{ ?>
You have to set Category column rowspan to count($invoices)*count($pname) and set rowspan to Product, Production date and Sales date columns to count($pname)

Categories