Data Tables second table is shown but no reaction - php

I have implemented a table from data tables
Link [https://datatables.net/]
i would like to use two tables in one site with different columns and datas in the columns after the mysqli connection i insert the data sets with a while mysqli fetch array function the first table works properly
"urlaubstage" -> is correct
but table 2
no matter what i do even var_dump i dint not get any reaction but the table is display correctly on the page but with empty columns
This is the html code
<table id="table_id" class="display">
<thead>
<tr>
<th>Urlaubstage Jahr</th>
<th>Urlaubstage Anspruch</th>
<th>Urlaubstage Beansprucht</th>
<th>Urlaubstage Rest</th>
</tr>
</thead>
<tbody>
<?php
while($row = mysqli_fetch_array($sql)){
$urlaubsTage = $row[4];
echo "<tr>";
echo "<td>{$urlaubsTage}</td>";
echo "<td>Anspruch</td>";
echo "<td>Beansprucht</td>";
echo "<td>Rest</td>";
echo "halllo";
}
echo "</tr>";
?>
</tbody>
</table>
!!!!!!!!!!!!<p>HERE STARTS THE SECOND TABLE</p>!!!!!!!!!!!!!!!!!!!!!!!!
<table id="table_id2" class="display">
<thead>
<tr>
<th>Urlaub Antragsdatum</th>
<th>Urlaub Startdatum</th>
<th>Urlaub Enddatum</th>
<th>Urlaubs Status</th>
</tr>
</thead>
<tbody>
<?php
while($row = mysqli_fetch_array($sql)){
var_dump($row); -> EVEn VAR_DUMP IS NOT SHOWN
echo "<tr>";
echo "<td>Antragsdatum</td>";
echo "<td>Startdatum</td>";
echo "<td>Enddatum</td>";
echo "<td>Status</td>";
echo "halllo";
}
echo "</tr>";
?>
</tbody>
</table>
JQUERY CODE
....
$('#table_id').DataTable();
//FUNKTION FÜR ZWEITE TABELLE
$('#table_id2').DataTable();
....
Picture of Code and Table

ok i got the answer by myself, after the first loop runs the query $sql with mysqli_fetch_array($sql) you cant use it anymore on the second loop why? cause it ran on the first loop and its over solution
rename;
$sql = mysqli_query(same query);
$sql2 = mysqli_query(same query);
first loop while($row = mysqli_fetch_array($sql);
second loop while($row = mysqli_fetch_array($sql2);

You don't need to execute the same query twice. You don't need the while loop either. Try to get the results into an array and then loop the array multiple times.
$result = $conn->query($sql)->fetch_all();
//...
foreach ($result as $row) {
//...
}
// Repeat the same loop again without calling query again
//foreach...

Related

Like to jQuery sum values

I like to sum all values with script but get it the result: total:NaN
(need to sum all columns except the first column)
The code PHP and script are in the same file and this is my code:
For php:
<table id="table">
<thead class="thead-dark">
<tr class="titlerow">
<th>Col1</th>
<th>Col2</th>
<th>Col3</th>
<th>Col4</th>
<th>col5</th>
</tr>
</thead>
<tbody>
<tr>
<?php
include("conn.php");
$result = mysql_query("SELECT id,name,col1,col2 FROM table GROUP BY name");
while($test = mysql_fetch_array($result))
{
$id = $test['id'];
echo"<td class='rowDataSd'>".$test['col1']."</td>";
echo"<td class='rowDataSd'>".$test['col1']."</td>";
echo"<td class='rowDataSd'>".$test['col2']."</td>";
echo"<td class='rowDataSd'>".$test['col2']."</td>";
echo"<td class='rowDataSd'>".$test['col2']."</td>";
echo "</tr>";
}
mysql_close($conn);
echo '<tfoot>
<tr class="totalColumn">
<td>.</td>
<td class="totalCol">Total:</td>
<td class="totalCol">Total:</td>
<td class="totalCol">Total:</td>
<td class="totalCol">Total:</td>
<td class="totalCol">Total:</td>
</tr>
</tfoot>';
?>
</table>
For script:
var totals=[0,0,0];
$(document).ready(function(){
var $dataRows=$("#table tr:not('.totalColumn, .titlerow')");
$dataRows.each(function() {
$(this).find('.rowDataSd').each(function(i){
totals[i]+=parseInt( $(this).html());
});
});
$("#table td.totalCol").each(function(i){
$(this).html("total:"+totals[i]);
});
});
Where is the exact problem?
I'm not sure, but... as far as i know, and maybe i'm wrong (would be happy to get advise on that) => mysql_fetch_array and mysql_query is kinda "dead" and instead, today you should use: mysqli_fetch_array and mysqli_result (see the additional i), and that depends on the version you are running on your server that is. Does the query works for you?. If not, i would defently look into that.
See an example here:
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Perform queries
mysqli_query($con,"SELECT * FROM Persons");
mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age)
VALUES ('Glenn','Quagmire',33)");
mysqli_close($con);
?>
I wouldn't sum them with jQuery at all. I would do it in PHP:
...
<tr> <!--- this tr is out of place, needs to be in the loop -->
<?php
//include("conn.php"); this should be require as it's necessary
//include will ignore missing files, require with throw an error
//this code will not work without that file, so let PHP tell you
//when it goes missing, instead of wondering why your DB calls don't work
require "conn.php"; // inlude/require are not functions they will work with (...) but it's not best practice.
$result = mysql_query("SELECT id,name,col1,col2 FROM table GROUP BY name");
//define default values for increment without errors
$totals = ['col1'=>0,'col2'=>0,'col3'=>0,'col4'=>0,'col5'=>0];
while($test = mysql_fetch_array($result))
{
$id = $test['id'];
echo "<tr>"; //-- this is the tr from above --
//use a loop if the HTML is all the same
for($i=1;$i<=5;++$i){
$key = 'col'.$i;
echo"<td class='rowDataSd'>".$test[$key]."</td>";
//simply add the values on each iteration (sum)
$totals[$key] += $test[$key];
}
echo "</tr>"; //-- without fixing the open tag as mentioned above, your HTML would be messed up --
}
mysql_close($conn);
echo '<tfoot>';
echo '<tr class="totalColumn">';
echo '<td>.</td>';
for($i=1;$i<=5;++$i){
echo '<td class="totalCol">total:'.$totals['col'.$i].'</td>';
}
echo '</tr>';
echo '</tfoot>';
...
If this stuff doesn't change dynamically (which it doesn't seem to), there is no need to do it with Javascript.
You can also reduce the code by using a simple for loop.
Cheers!

PHP PDO while loop isn't returning anything

I really can't figure out what I'm doing wrong here. I'm doing a query to check whether there are records in a DB table called 'newCards'.
With $count I check how many results it's returning: it shows me '1'. But the while loop isn't returning ANY thing. The only things I'm seeing are the <th>'s at the top of the table, but no table records are present, while $count is giving '1' as a result. Which is true, cause there is actually 1 record present in DB.
How can I fix this?
<?php
$query = $db->prepare("SELECT * FROM `newCards` WHERE `company` = :companyID");
$query->bindParam(":companyID", $enterprise['id'], PDO::PARAM_INT);
$query->execute();
$count = $query->rowCount();
echo $count;
if(empty($query->fetch())){
echo "Geen gevonden";
} else {
?>
<table>
<tr>
<th>Ontvanger</th>
<th>Saldo</th>
<th></th>
</tr>
<?php
while($result = $query->fetch()){
?>
<tr>
<td><?php echo $result['id']; ?></td>
<td>2</td>
<td>3</td>
</tr>
<?php
}
?>
</table>
<?php
}
?>
$query->fetch() already fetches a record. So next call to fetch() fetches next record or nothing if there're no records. In your case with one record second fetch() fetches nothing, so while never starts.
You can change your code to:
if($count){?>
<table>
<tr>
<th>Ontvanger</th>
<th>Saldo</th>
<th></th>
</tr>
<?php
while($result = $query->fetch()){
// show row
}?>
</table>
} else {
// echo that no rows found
}
I think fetch in first if is executed so that is why second returns empty,
try to assign it to var before conditions or check wit $cont var
I believe you want to return an array indexed by column names with
->fetch(PDO::FETCH_ASSOC)
More information can be found here http://php.net/manual/en/pdostatement.fetch.php
Because fetch() fetches the first row, even when checking in empty(), it will try to fetch the next row when you use while($result = $query->fetch()){. You can either check the value from $count (like shown by u_mulder), but you should beware of the note in the manual for rowCount() (emphasis mine)
If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behavior is not guaranteed for all databases and should not be relied on for portable applications.
You can use a do..while structure and check if the fetch was successful or not instead. If you change out if(empty($query->fetch())){ with if (!$row = $query->fetch()) {, you check if there was a row fetched or not (as fetch() returns null on an empty result). Then $row is ready to use, and you can use it before the first loop takes place.
<?php
$query = $db->prepare("SELECT * FROM `newCards` WHERE `company` = :companyID");
$query->bindParam(":companyID", $enterprise['id'], PDO::PARAM_INT);
$query->execute();
$count = $query->rowCount();
echo $count;
if (!$row = $query->fetch()) {
echo "Geen gevonden";
} else {
?>
<table>
<tr>
<th>Ontvanger</th>
<th>Saldo</th>
<th></th>
</tr>
<?php
do {
?>
<tr>
<td><?php echo $result['id']; ?></td>
<td>2</td>
<td>3</td>
</tr>
<?php
} while ($result = $query->fetch());
?>
</table>
<?php
}
PHP.net on PDOStatement::rowCount()
PHP.net on do..while

PHP How do you separate your results to echo in two divs of the one page?

I know how to produce results one after another but how do you separate them? So in my sql I'm selecting * from table and limiting it to 4
$sql = "SELECT * FROM table limit 4";
$result = $conn->query($sql);
while($row = $result->fetch_assoc())
{$rows['id']=$row;};
$price = $row['price'];
I dont seem to get any result, any suggestions, sorry guys beginner
...<?php echo $id ?></font></span>
<h4><?php echo $price ?></h4></div>
<div class="planFeatures"><ul>
<li><h1><?php echo $id=2 ?></h1></li>//how do I echo the next id?
<li><?php echo $price2 ?></li> //also the next price which id now is also 2
//and so on......
How do I display the next increments results in a different area of the same page, within another div?
I do get results if I sql and re-select all over again (and say id=2) but I'm sure there is a better way of doing it because I've already got my 4 results with my limit.
It seems you are not saving the results from the query result properly. Each iteration of the loop overwrites the same bucket in the $rows array. Instead, you need to add elements to the $rows array; this will produce an indexed array. Then you can iterate over it and generate the HTML content.
<?php
// Perform query.
$sql = "SELECT * FROM table limit 4";
$result = $conn->query($sql);
// Fetch results
while (true) {
$row = $result->fetch_assoc();
if (!$row) {
break;
}
$rows[] = $row;
}
// Generate HTML content using $rows array.
?>
<table>
<thead>
<tr>
<th>ID</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<?php foreach ($rows as $row):?>
<tr>
<td>ID: <?php print $row['id'];?></td>
<td>Price: <?php print $row['price'];?></td>
</tr>
<?php endforeach;?>
</tbody>
</table>
I took some liberty in the above example and generated a simple HTML table. Of course you can modify this to generate whatever you want.
I hope I've interpreted your question accurately, apologies if not!

php do while loop kept table looping infinitely

I executed this code in localhost but it kept looping the table infinitely. How do I fix this? Is there something I should add? The looping never stops until I click the x button to stop loading the page.
//fetching data in descending order (lastest entry first)
//$result = mysql_query("SELECT * FROM users ORDER BY id DESC"); // mysql_query is deprecated
$query=("SELECT * FROM songs ORDER BY songid DESC");
$result = mysql_query($query) or die(mysql_error());
?>
<html>
<head>
<title>View</title>
</head>
<body>
Add New Data<br/><br/>
<table width='80%' border=0>
<tr bgcolor='#CCCCCC'>
<td>Song ID</td>
<td>Title</td>
<td>Artist</td>
<td>Genre</td>
<td>Language</td>
<td>Lyrics</td>
<td>Updated by</td>
</tr>
<?php
$counter == 1;
$res = mysql_fetch_array($result);
//while($res = mysql_fetch_array($result)) { // mysql_fetch_array is deprecated, we need to use mysqli_fetch_array
do {
echo "<tr>";
echo "<td>".$res['songid']."</td>";
echo "<td>".$res['title']."</td>";
echo "<td>".$res['artist']."</td>";
echo "<td>".$res['genre']."</td>";
echo "<td>".$res['language']."</td>";
echo "<td>".$res['lyrics']."</td>";
echo "<td>".$res['update']."</td>";
echo "<td>Edit | Delete</td>";
} while($res)
?>
</table>
You are missing $res = mysql_fetch_array($result); at the end of the loop. Currently, the while statements checks if $res is (still) truthy, but it never changes, so it will always evaluate to TRUE (and so, the loop will always continue to run).
I was just about to write the same thing as Daan Meijer. res never changes and so its always true for the while-statement. I just want to add that mysql_fetch_assoc($result) works a littlebit faster than mysql_fetch_array($result). So if you have a big database, mysql_fetch_assoc($result) is the better choice.

Display MYSQL results in html table

Im not sure if a similar question has been asked before, but here goes anyway. (I did do a search and found nothing relating to my question).
I am developing a website in which videos are played using the HTML5 video player. I have a connection to my database, a "watch" page that pulls all the correct data using a variable linked to the id (watch.php?v=1). I would like to have an index page where the most recent videos are pulled. They are ordered by the column "id" and everything works when I try and pull one result from the query. How would I go about getting multiple values? Here is my php code (server details hidden):
<?php
$mysqli = new mysqli("HIDDEN", "HIDDEN", "HIDDEN", "HIDDEN");
$sql = "
SELECT id, title, imgsrc, description
FROM videos
ORDER BY id DESC
LIMIT 2
";
$result = $mysqli->query($sql);
$video = mysqli_fetch_array($result, MYSQLI_ASSOC);
mysqli_close($mysqli);
?>
And here is my HTML code for the table.
<table>
<tr>
<td><h2><? echo $video['title']; ?></h2></td>
</tr>
</table>
That isn't the full code, but once I know the procedure I can apply it where needed!
I'm quite new to php and mysql, I can connect to databases but that's about it so a full walkthrough about what does what would be great!
Many Thanks,
James Wassall
You can iterate in for or while loop by calling mysqli_fetch_array($result, MYSQLI_ASSOC):
<table>
<?php
$mysqli = new mysqli("HIDDEN", "HIDDEN", "HIDDEN", "HIDDEN");
$sql = "
SELECT id, title, imgsrc, description
FROM videos
ORDER BY id DESC
LIMIT 2
";
$result = $mysqli->query($sql);
while($video = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
?>
<tr>
<td><h2><? echo $video['title']; ?></h2></td>
</tr>
<?php
}
mysqli_close($mysqli);
?>
</table>
Note that you should consider checking error statements, null controls etc.
try this
while($video = $result->fetch_array(MYSQLI_ASSOC))
{
?>
<tr>
<td><h2><?php echo $video['title']; ?></h2></td>
</tr>
<?php
}
?>
Each time you call mysqli_fetch_array, only one row is fetched.
You need to do something like
while ($video = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
// output $video['title']
}
(according to: http://www.php.net/manual/en/mysqli-result.fetch-array.php)
Try this,
<table>
<?php while($row = $result->fetch_array(MYSQLI_ASSOC)){ ?>
<tr>
<td><h2><? echo $row['title']; ?></h2></td>
<td><h2><? echo $row['description']; ?></h2></td>
</tr>
<?php } ?>
</table>

Categories