Create HTML table from numbers elements of array [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have the variable $count that contains the total elements of my array.
I want to insert the html code to another variable that contains a table of as many lines as the lines of variable $count.
how can I do ?
<?php
$count=5;
$html="<table>
<tr>
<td></td>
<td></td>
</tr>
</table>"
?>

There are many possibilities to do this.
Use a loop:
$table = '<table>';
for ($i = 0; $i < $count; $i++) {
$table .= '<tr><td></td><td></td></tr>';
}
$table .= '</table>';
or you could use str_repeat
$table = '<table>';
$table .= str_repeat('<tr><td></td><td></td></tr>', $count);
$table .= '</table>';
or many others - depends on your needs

You can use this:
<?php
$count = 5;
?>
<table>
<?php for($i = 0; $i < $count; $i++) : ?>
<tr>
<td></td>
<td></td>
</tr>
<?php endfor; ?>
</table>

Not quite sure on the question (it's incredibly vague), but I'll try to help.
<?php
$count = 5;
$html = "<table>";
for($i=0;$i<$count;$i++){
$html .= "<tr><td>New Row!</td></tr>";
}
$html .= "</table>";
Use this for rows.
<?php
$count = 5;
$html = "<table><tr>";
for($i=0;$i<$count;$i++){
$html .= "<td>New column!</td>";
}
$html .= "</tr></table>";
Use this for columns.
Combine the two examples for a 100% dynamic table with dynamic rows and columns. If you've got an array, you'd be better off just using a foreach:
<?php
$array = array( array('Col1'=>'Val1', 'Col2'=>'Val2', 'Col3'=>'Val3'), array('Col1'=>'Test', 'Col2'=>'Test', 'Col3'=>'Test') );
$html = "<table>\n\t<tr>";
//Columns
foreach(array_key($array[0]) as $col){
$html .= "\n\t\t<td>{$col}</td>";
}
$html .= "\n\t</tr>";
//Rows
foreach($array as $row){
$html .= "\n\t<tr>";
foreach($row as $rowcol){
$html .= "\n\t\t<td>{$rowcol}</td>";
}
$html .= "\n</tr>";
}
$html .= "</table>";
Yes I'm a little OCD about the newlines and tabs.
If you can update your question with a use-case I can probably provide a better, more accurate example.

You can do it two ways. By using a foreach or a for/while cycle.
In my opinion you can go ahead and use the foreach to iterate your array().
<?php $array= array('blue', 1, 3, 'red', 'monkey'); ?>
<table>
<?php foreach($array as $value): ?>
<tr>
<td><?php echo $value ?></td>
</tr>';
<?php endforeach; ?>
</table>
?>
For me it's the cleaner way to iterate an array. If you just want to make multiple columns/rows on a table than use a for($i=0; $i<$count; i++) instead.

Related

Can i pass array to an HTML? Creating a dynamic html table with php/javascript

I have created a table with 3 columns and rows with the size of an array pulled from the database. I have got the value but I want to create a button inside the cells with the name from pname and when you click that button it will take you to the value of plink. I tried using <input type="button" value=" " onclick="window.open( )", but it doesn't seem to pass the arrays. I am sure there is an easier/ better way to do it with JavaScript, but I am not familiar with JavaScript. Please help me out. Here is my code.
I want the format 3 columns and infinite rows(based on the data).
<!DOCTYPE html>
$pname = array();
$plink = array();
$results = $wpdb->get_results("SELECT name, link FROM `wptable`);
if(!empty($results)) {
foreach($results as $row){
$pname[] = $row->name;
$plink[] = $row->link;
}
}
$num = 0;
echo "<table class='table'>";
echo "<tbody>";
echo "<br><br>";
$quant_row = count($pname)/3;
$quant_col = 3;
for ($count_row = 0; $count_row < $quant_row; $count_row++)
{
echo "<tr>";
for ($count_col = 0; $count_col < $quant_col; $count_col++)
{
echo "<td>";
echo $plink[$num];
echo "</td>";
$num++;
}
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
?>
You just need to echo a button inside an anchor:
echo '<button type="button">' . $pname[$num] . '</button>';
try this.
echo "<td>";
echo "<button onclick=\"Document.getElementById('link$num').display=state$num? 'none' :'block';state$num=!state$num; \">". $pname[$num] ."</button><div id='link$num'>". $plink[$num]."<div>";
echo "";
when you click on $pname , you show the $plink. reclick and hide the content

PHP: javascript alert, with value from sql query, into IF condition

With the following code, a popup table should appear with sql query data, only when retrieved records are greater than 1.
$sql = "SELECT * FROM pt_locations WHERE country = ('$countryCode') AND location = ('$cityCode')";
$result = $conn->query($sql);
$rowcount=mysqli_num_rows($result);
$message = "Records found: " . $rowcount . "<br /><br />";
if ($rowcount > 1) {
echo '<script language="javascript">';
echo 'alert' .$message;
foreach($result as $val){
$id_country = $val["country"] ;
$id_code = $val["code"] ;
$id_location = $val["location"] ;
$id_latitude = $val["latitude"] ;
$id_longitude = $val["longitude"] ;
echo "<table border='1' cellpadding='5'>";
echo "<tr>";
echo "<td><i><strong>ID Code</strong></i></td><td>";
echo $id_code."</td>";
echo "<td><i><strong>Country</strong></i></td><td>";
echo $id_country."</td>";
echo "<td><i><strong>Code</strong></i></td><td>";
echo $code."</td>";
echo "<td><i><strong>Location</strong></i></td><td>";
echo $id_location."</td>";
echo "<td><i><strong>Latitude</strong></i></td><td>";
echo $id_latitude."</td>";
echo "<td><i><strong>Longitude</strong></i></td><td>";
echo $id_longitude."</td>";
echo "</tr>";
echo "</table><br /><br />";
}
echo '</script>';
}
Recording counts are done correctly, but I can not make the popup appear in any way.
try this. Hope this help you.
$sql = "SELECT * FROM pt_locations WHERE country = ('country') AND
location = ('location')";
$result = $conn->query($sql);
$rowcount=mysqli_num_rows($result);
$message = "Records found: " . $rowcount;
if ($rowcount > 1) {
echo '<script language="javascript">';
echo 'alert("'.$message.'")';
echo '</script>';
while($val=mysqli_fetch_assoc($result)){
$id_country = $val["country"] ;
$id_code = $val["code"] ;
$id_location = $val["location"] ;
$id_latitude = $val["latitude"] ;
$id_longitude = $val["longitude"] ;
echo "<table border='1' cellpadding='5'>";
echo "<tr>";
echo "<td><i><strong>ID Code</strong></i></td><td>";
echo $id_code."</td>";
echo "<td><i><strong>Country</strong></i></td><td>";
echo $id_country."</td>";
echo "<td><i><strong>Code</strong></i></td><td>";
echo $code."</td>";
echo "<td><i><strong>Location</strong></i></td><td>";
echo $id_location."</td>";
echo "<td><i><strong>Latitude</strong></i></td><td>";
echo $id_latitude."</td>";
echo "<td><i><strong>Longitude</strong></i></td><td>";
echo $id_longitude."</td>";
echo "</tr>";
echo "</table><br /><br />";
}
}
There are some errors, because for logic you must put the alert at the end of the table complete, just for logic and after you put alert something without brakets and you open a script before the foreach loop and after the foreach loop you close the script, this is absolutley wrong, another error is in the $message, you are using br inside an alert javascript that isn't recognize as html but just like characters at the least you can use unicode \n\t not br, i used also a setTimeout,but works also without setTimeout.
Sometimes can result essential use javascript injection inside the php for example to autofill of some forms and input select or to call a change event from external compilation of other application that pass variables in get and need to autofill a form, but i think in this case is not necessary do a javascript injection you can print the total Records just in the page, btw...
The code under works
Bye
$message = "Records found: " . $rowcount." \\n\t\\n\t";
if ($rowcount > 1) {
foreach($result as $val){
//var_dump($val);
$id_country = $val["country"] ;
$id_code = $val["code"] ;
$id_location = $val["location"] ;
$id_latitude = $val["latitude"] ;
$id_longitude = $val["longitude"] ;
echo "<table border='1' cellpadding='5'>";
echo "<tr>";
echo "<td><i><strong>ID Code</strong></i></td><td>";
echo $id_code."</td>";
echo "<td><i><strong>Country</strong></i></td><td>";
echo $id_country."</td>";
echo "<td><i><strong>Code</strong></i></td><td>";
echo $code."</td>";
echo "<td><i><strong>Location</strong></i></td><td>";
echo $id_location."</td>";
echo "<td><i><strong>Latitude</strong></i></td><td>";
echo $id_latitude."</td>";
echo "<td><i><strong>Longitude</strong></i></td><td>";
echo $id_longitude."</td>";
echo "</tr>";
echo "</table><br /><br />";
}
$jvsVar = "<script type='text/javascript'>;setTimeout(function(){alert('$message');},100)</script>";
echo $jvsVar;
}

How can i refresh only data in table with javascript?

I have page with data table and i need to refresh only data in table and i use bootstrap datatable to sort but when i use refresh data in my page will can not use bootstrap to sort data. How can i fix it?
this my code for get data to refresh
$request = $this->m_request->get_request_list();
$row = '';
$row .= '<table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered" id="datatable">';
$row .= '<thead>';
$row .= '<tr>';
$row .= '<td>Start</td>';
$row .= '<td>End</td>';
$row .= '<td>Type</td>';
$row .= '</tr>';
$row .= '</thead>';
$row .= '<tbody>';
foreach ($re as $r){
$row .= '<tr id="sh">';
$row .= '<td>'.$r->date_start.'</td>';
$row .= '<td>'.$r->date_end.'</td>';
$row .= '<td>'.$r->leave_type.'</td>';
$row .= '</tr>';
}
$row .= '</tbody>';
$row .= '</table>';
echo $row;
and this is my javascript to get data to show
var $container = $("#show_data");
$container.load("<?php echo site_url('request/get')?>");
var refreshId = setInterval(function()
{
$container.load('<?php echo site_url('request/get')?>');
}, 3000);
if i show table in view page the data will can not refresh to get data and if i call table in controller page i will can not use bootstrap datatable.
Please help. Thank you so much for your help.
Reinitialize you datatable after each ajax success
var $container = $("#show_data");
$container.load("<?php echo site_url('request/get')?>",function(){ $('table').DataTable();});
var refreshId = setInterval(function()
{
$container.load("<?php echo site_url('request/get')?>",function(){ $('table').DataTable();});
}, 3000);

Looping Datatables Row

I am doing a reportentry that use datatables which has input entry. The problem is The last row doesnt show up correctly.
this is my datatables,
$flightsCount = $_POST['flights'];
<tbody>
<?php
for($i = 1; $i <= count($flightsCount);$i++){
$flightRoute = $mysqli->query("SELECT flight_region FROM mst_flight WHERE flight_id = '$flightsCount[$i]'")->fetch_object()->flight_region;
echo "<tr>";
echo "<td>$i</td>";
echo "<td>GA $flightsCount[$i]</td>";
echo "<td>$flightRoute</td>";
echo "<td>$newDate</td>";
echo "<td><input type='text'/></td>";
echo "<td><input type='text'/></td>";
echo "<td><input type='text'/></td>";
echo "</tr>";
}
?>
</tbody>
error message is ,
Notice: Undefined offset: 5 in C:\xampp\htdocs\SOBCASHIER\html\main\divpages\srdetailstab.php on line 34
Notice: Trying to get property of non-object in C:\xampp\htdocs\SOBCASHIER\html\main\divpages\srdetailstab.php on line 34
Notice: Undefined offset: 5 in C:\xampp\htdocs\SOBCASHIER\html\main\divpages\srdetailstab.php on line 37
last row only shows GA without showing the code.
Please help me
Just start your for loop from 0. like:
for($i = 0; $i < count($flightsCount);$i++)
and to display in td just write $i + 1.
Note: Not able to test this, But hope it should work
You forgot to include the 0 index for $flightsCount
Your code should be updated to :
$flightsCount = $_POST['flights'];
<tbody>
<?php
for($i = 0; $i < count($flightsCount);$i++){
$flightRoute = $mysqli->query("SELECT flight_region FROM mst_flight WHERE flight_id = '$flightsCount[$i]'")->fetch_object()->flight_region;
echo "<tr>";
echo "<td>".($i+1)."</td>";//updated to include the index update
echo "<td>GA $flightsCount[$i]</td>";
echo "<td>$flightRoute</td>";
echo "<td>$newDate</td>";
echo "<td><input type='text'/></td>";
echo "<td><input type='text'/></td>";
echo "<td><input type='text'/></td>";
echo "</tr>";
}
?>
</tbody>

Execute Javascript through PHP

I'm using this PHP code to write a HTML table, but it takes time to load. I was thinking it would be a good idea to let JavaScript do the job, but the problem is that $width and $height are dynamic and is defined on the server-side. How do I get around that?
echo "<table>";
for ($y = 0; $y < $height; $y++) {
echo "<tr>";
for ($x = 0; $x < $width; $x++) {
echo '<td x="' . $x . ' y="' . $y . ' id="' . $x . '-' . $y . '"></td>'; //coordinates to be used for cropping later
}
echo '</tr>';
}
echo '</table>';
I'm unsure if this is best practice, but you can echo from PHP directly into Javascript. For example:
<script>
var width = <?php echo $width; ?>;
var height = <?php echo $height; ?>;
//now build table here using the Javascript width and height variables
</script>
Put PHP variables in javascript
<script>
var height = <?php echo $height ?>;
</script>
If no paramount forms are intented to exist in your page, you can store them in hidden HTML tags as hidden inputs, like this:
echo ="<form action ='#' name='form'>
<input type='hidden' name='v_height' id='v_height' value='".$height."'>
<input type='hidden' name='v_width' id='v_width' value='".$width."'>
</form>";
And then in Javascript get those variables and iterate with them.
jHeight = parseInt(document.form.v_height.value);
And so with the width.

Categories