I have an array such:
$prices = array();
Along with a MySQL query and fetch:
$query = "SELECT $columns FROM Prices WHERE `key` LIKE '$rows' LIKE '$AirportPU' AND rate LIKE '$rate'";
if($results = $db->query($query))
{
if($results->num_rows)
{
while($row = $results->fetch_object())
{
$prices[] = $row;
}
$results->free();
}
I've printed out the table using the following code: (I have removed some table columns)
<?php
if(!count($prices)) {
echo '<p>No results found for your current search. Use the inputs to the left to change the filters.</p>';
} else {
?>
<table>
<thead>
<tr>
<th>Location</th>
<th>City</th>
</tr>
</thead>
<tbody>
<?php
foreach ($prices as $p) {
?>
<tr>
<td> <?php echo $p->Location; ?> </td>
<td> £<?php echo $p->City; ?> </td>
</tr>
<?php
}
?>
</tbody>
</table>
<?php } ?>
I can return data from the MySQL query, and print this to the table. However, sometimes not all the columns need be printed as they have no values. I would like to hide these columns.
I have tried checking the array using:
print (isset($prices["City"])) ? "Exists</br>" : "Doesn't Exist</br>" ;
But that always returns "Doesn't Exist"
if (array_key_exists("City",$prices))
{
echo "Element exists!";
}
else
{
echo "Element does not exist!";
}
That also returns false.
You need to check it inside the foreach loop which you are executing.
print (isset($p->City)) ? "Exists</br>" : "Doesn't Exist</br>" ;
Check with
if(empty($price['City'] || $price['City'] == "")){
//Hide column
}
Related
I have multiple select options. however, i want when i select 1 option or two or whatever to change the columns <th></th> of html dynamically and get data from database
Currently I have created the multiple select option and html table
<select class="selectpicker" id="sensor" name="sensor[]" multiple>
<option
value="temperature">Temperature</option>
<option value="humidity">Humidity</option>
<option value="presure">Presure</option>
<option
value="level">Level</option>
</select>
$query = "SELECT ".$selectedSensorOption." from p1";
$result = $db_handle->runQuery($query);
foreach ($result as $key => $value) {
<table>
<tr>
<th>$result</th>
</tr>
<tr>
<td>$result</td>
I want to get dynamic columns and fields as well from MySQL db based on multiple select options
A straight forward way of doing this is to use the key values of the result to act as the headers and then output each row of data as the values (comments in code)...
// Output table start and header row
echo "<table><tr>";
// Use the first rows results as the header values
foreach ( $result[0] as $header => $value ) {
echo "<th>{$header}</th>";
}
echo "</tr>";
// Output each data row
foreach ($result as $values) {
echo "<tr>";
// Loop over each item in the row and output the value
foreach ( $values as $value ) {
echo "<td>{$value}</td>";
}
echo "</tr>";
}
echo "</table>";
You can create shorter code (using implode() etc.), but sometimes simpler code is easier to start with and maintain.
Using the returned column names means you may be able to use specific headings using column aliases - something like
id as `User ID`, fullname as `Name`
I used AJAX. Hope this helps ;D
read.php
<?php
//include header
header('Content-Type: application/json');
$conn= mysqli_connect("localhost","my_user","my_password","my_db");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$type = $_GET["type"];
if($type == "GetCategory"){
//SAMPLE QUERY
$sql = "SELECT CategoryID,CategoryName from Category";
$data = array();
$results = $db -> query($sql);
while($row = mysqli_fetch_assoc($results)){
$data[] = $row;
}
echo json_encode($data);
}
if($type == "GetSubCategory"){
$CategoryID = $_POST["CategoryID"];
//SAMPLE QUERY
//LET'S ASSUME THAT YOU HAVE FOREIGN KEY
$sql = "SELECT SubCategoryID,SubCategoryName from SubCategory where CategoryID = '".$CategoryID."'";
$data = array();
$results = $db -> query($sql);
while($row = mysqli_fetch_assoc($results)){
$data[] = $row;
}
echo json_encode($data);
}
?>
index.html
<select id="category"></select>
<select id="subcategory"></select>
<!--PLEASE INCLUDE JQUERY RIGHT HERE E.G. <script src='jquery.min.js'></script>-->
<!--DOWNLOAD JQUERY HERE https://jquery.com/-->
<script>
LoadCategory();
function LoadCategory(){
$.ajax({
url:"read.php?type=GetCategory",
type:"GET",
success:function(data){
var options = "<option selected disabled value="">Select
Category</option>";
for(var i in data){
options += "<option value='"+data[i].CategoryID+"'>" + data[i].CategoryName + "</option>";
}
$("#category").html(options);
}
});
}
function LoadSubCategory(CategoryID){
$.ajax({
url:"read.php?type=GetSubCategory",
type:"POST",
data:{
CategoryID : CategoryID
},
success:function(data){
var options = "<option selected disabled value="">Select Sub-Category</option>";
for(var i in data){
options += "<option value='"+data[i].SubCategoryID+"'>" + data[i].SubCategoryName + "</option>";
}
$("#subcategory").html(options);
}
});
}
$("#category").change(function(){
LoadSubCategory(this.value);
});
first you have to get the headers, you can use explode to get the header keys.
you'll use two loops, the first one to build the header and the second one to build the body. inside the body loop, you have to use another loop to get the correct value for each column
<select class="selectpicker" id="sensor" name="sensor[]" multiple>
<option value="temperature">Temperature</option>
<option value="humidity">Humidity</option>
<option value="presure">Presure</option>
<option value="level">Level</option>
</select>
<?php
$query = "SELECT ".$selectedSensorOption." from p1";
$results = $db_handle->runQuery($query);
//get the headers if $selectedSensorOption is not an array
$headers = explode(',', $selectedSensorOption)
?>
<table>
<thead>
<tr>
<!-- loop and fill the header -->
<?php foreach ($headers as $header) : ?>
<th><?= ucfirst($header) ?></th>
<?php endforeach; ?>
</tr>
</thead>
<tbody>
<!-- loop and fill the body-->
<?php foreach ($results as $result) : ?>
<tr>
<!-- loop and fill each column -->
<?php foreach ($headers as $header) : ?>
<th><?= $result[$header] ?></th>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</tbody>
</table>
I have the following code. How can I get my results ($x) for the foreach function to print into the table at the top, but in columns instead of a straight horizontal row? Is there a way to do this without just inserting each individual value into the HTML table? I need to do the same for my $employee['name'] variable but am not sure how I could get these values inserted into a table format without going one by one and entering the value myself.
Also, one value for $x at the end stays an integer and does not echo the string variable specified by the foreach function, is there a way I could fix this?
<!--4.3-->
<table>
<tr>
<td>Employee name</td><td></td><td></td><td></td><td></td><td></td>
<td>Type of Paying</td><td></td><td></td><td></td><td></td><td></td>
</tr>
<tr>
<td></td><td></td><td></td><td></td><td></td><td></td>
<td><?php echo $x;?></td><td></td><td></td><td></td><td></td><td></td>
</tr>
</table>
</html>
<?php
foreach ($employees as $employee) {
$x = ($employee['wage'] * $employee['hrs']) * 4;
if ( 3000 <= $x ) {
echo "High paying";
} elseif (2000 <= $x && $x <= 2999) {
echo "Good paying";
} else {
echo "Low paying";
}
}
print_r ($x);
I inserted the foreach function into the table where I needed the results printed, then added tags within the ifelse statement after each parameter, and it worked like a charm.
My code for that table now looks like this:
<html>
<table>
<tr>
<td>Employee name</td><td></td><td></td><td></td><td></td><td></td>
<td>Type of Paying</td><td></td><td></td><td></td><td></td><td></td>
</tr>
<tr>
<td></td><td></td><td></td><td></td><td></td><td></td>
<td> <?php
foreach ($employees as $employee) {
$x = ($employee['wage'] * $employee['hrs']) * 4;
if ( 3000 <= $x ) {
echo "High paying"; echo "<br/>";
} elseif (2000 <= $x && $x <= 2999) {
echo "Good paying"; echo "<br/>";
} else {
echo "Low paying"; echo "<br/>";
}
} echo "<br/>" ; ?>
</td><td></td><td></td><td></td><td></td><td></td>
</tr>
</table>
The other section above the foreach function will hold employee names and is not yet filled out to match.
I am new in Codeigniter and i have problem when trying to display data in view page. I have follow Codeigniter documentation, tutorials and questions in stackoverflow but still no answer can help me althought i run the tutorial and it work perfectly. but when i implement in my code, it give me an error. Hope you guys can help me. I am not sure what the problem. Thank you in advanced.
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: b
Filename: home/adminviewbranch.php
Line Number: 81
Form.php(controller)
public function view_branch(){
$this->load->model('branch_model');
$data = array();
$data['b'] = $this->branch_model->branch_view();
$this->load->view('home/adminviewbranch', $data);
}
branch_model.php(model)
public function branch_view(){
//data is retrive from this query
$query = $this->db->get('branch');
return $query;
}
adminviewbranch.php(view)
<div id="page" class="container">
<table id="table_id" class="display">
<thead>
<tr>
<th>Branch Name</th>
<th>Branch Address</th>
<th>Branch Contact</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
if(count($b)>0) {
foreach ($b as $row) {
?>
<tr>
<td><?=$row->branch_name;?></td>
<td><?=$row->branch_add;?></td>
<td><?=$row->branch_Hp;?></td>
<td><?=$row->branch_Hp;?></td>
<?php
}
}
else {
echo "No Record found!";
}
?>
</tr>
</tbody>
</table>
</div>
in foreach do foreach ($b->result() as $row)
I think there is missing function in your foreach.
Try this:
<?php
if(count($b)>0)
{
foreach ($b->result() as $row){
?>
Modify your model code like below
public function branch_view(){
//data is retrive from this query
$query = $this->db->get('branch')->result_array();
return $query;
}
Change your model code to following
public function branch_view(){
//data is retrive from this query
$query = $this->db->get('branch');
return $query->result_array(); // this allows you to fetch results in the form of multidimentional array
}
Then you can access it in view as
<?php
if(count($b)>0)
{
foreach ($b as $row)
{
?>
<tr>
<td><?=$row['branch_name'];?></td>
<td><?=$row['branch_add'];?></td>
<td><?=$row['branch_Hp'];?></td>
<td>Action</td>
</tr>
<?php
}
}
else
{
echo "<tr colspan='3'><td>No Record found!</td></tr>";
}
?>
in model change this line
$query = $this->db->get('branch');
to
$query = $this->db->get('branch')->result();
(OR)
in view change this lines
<?php
if(count($b)>0) {
foreach ($b as $row) {
?>
to
<?php
if($b->num_rows()>0) {
foreach ($b->result() as $row) {
?>
Your model is not result anything.you can check with print_r() function.you must use be returning with object or array.return $query->result();
and your view must be foreach($tes as $t){$t->your_view}
or return $query->row();
with single data $row->your_view
I wrote some code to display a html table with PHP.
It reads data from a file and checks whether the value is true or false.
The problem is the ugly appearance of the table at the end of the function:
True False
blue
Red
Red
blue
I would like to display the table like this:
True False
blue Red
blue Red
Also it displays the outcome before the function is finished c.q flush();
Here is the code:
?>
<table>
<tr>
<th>True</th>
<th>False</th>
</tr>
<?php foreach ($trimmed_array as $value) { ?>
<tr>
<?php if (check($value) == 0) { ?>
<td><?php print $value ?></td>
<td> </td>
<?php
} else { ?>
<td> </td>
<td><?php print $value ?></td>
<?php
}
sleep(1);
ob_flush();
flush();
} ?>
</table>
I realize this code outputs the table like the first example but I can`t seem to figure out how to change it to fit the second example?
Your code creates one table row per item in the array, so there will always be one blank column per row.
In the 'table' that you would like to display, the items in each row aren't related to each other.
So really you're creating 2 lists here, not a table as such.
I'd do something like this
<?php
$all_values = array('true' => array(), 'false' = array());
foreach($trimmed_array as $value){
if (check($value) == 0){
$all_values['true'][] = $value;
}else{
$all_values['false'][] = $value;
}
}
foreach($all_values as $name => $values){
?>
<ul class="<?php print $name;?>">
<?php
foreach($values as $value){
?>
<li><?php print $value; ?></li>
<?php
}
?>
</ul>
<?php
}
?>
You can then arrange your lists side by side with CSS
$true = array();
$false = array();
foreach ($trimmed_array as $value) {
if (check($value) == 0) {
$true[] = $value;
} else {
$false[] = $value;
}
}
for ($i = 0; $i < max(count($true), count($false)); $i++) {
echo '<tr>
<td>' . (isset($true[$i]) ? $true[$i] : '') . '</td>
<td>' . (isset($false[$i]) ? $false[$i] : '') . '</td>
</tr>';
}
Here is the code, and this code is producing the following output: screenshot of output
the idea is to have a different header everytime the number of beds changes.
$tableTop = '<table> ... <tbody>';
$tableBottom = '</tbody> </table>';
$last_bed = null;
foreach ($unitsForSaleData as $row) {
if($units_for_sale['beds'] == 0){
if ($last_bed == null) {
echo '<h1> Studios For Sale </h1>';
echo $tableTop;
$last_bed = $units_for_sale['beds'];
}
} else {
if ($units_for_sale['beds'] !== $last_bed) {
if ($last_bed !== null) { // End previous table
echo $tableBottom;
}
echo '<h1>'.$units_for_sale['beds'].' Bedroom Condos For Sale </h1>';
echo $tableTop; // Start new table
$last_bed = $units_for_sale['beds'];
}
}
?>
<tr> ... </tr>
<?php
} // end loop
Solved it with an isset instead of an == null. Here is the full code for anyone else who needs something like this done:
$tableTop = '<table> ... <tbody>';
$tableBottom = '</tbody> </table>';
$last_bed = null;
foreach ($unitsForSaleData as $row) {
if($units_for_sale['beds'] == 0){
if (!isset($last_bed)) {
echo '<h1> Studios For Sale </h1>';
echo $tableTop;
$last_bed = $units_for_sale['beds'];
}
} else {
if ($units_for_sale['beds'] !== $last_bed) {
if ($last_bed !== null) { // End previous table
echo $tableBottom;
}
echo '<h1>'.$units_for_sale['beds'].' Bedroom Condos For Sale </h1>';
echo $tableTop; // Start new table
$last_bed = $units_for_sale['beds'];
}
}
?>
<tr> ... </tr>
<?php
} // end loop