Like to jQuery sum values - php

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!

Related

Data Tables second table is shown but no reaction

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...

Running mysql queries onclick from index page

I have an index.php on my localhost and I'd like to put several buttons to run different sql queries here. The queries will be like this one :
<table class="table1">
<tr>
<th>Date</th>
<th>Model</th>
<th>Type</th>
<th>InProduction</th>
<th>Price</th>
<th>Range</th>
<th>MaxSpeed</th>
<th>HP</th>
<th>Country</th>
<th>EType</th>
<th>Make</th>
<th>MPG</th>
<th>Seats</th>
</tr>
<?php
include ("config.php");
$sql = "SELECT Date, Model, Type, InProduction, Price, Range, MaxSpeed, HP, Country, EType, Make, MPG, Seats FROM Auto order by Date DESC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$counter = 0;
while($row = $result->fetch_assoc())
{
echo "<tr><td>" . $row["Date"]."</td><td>" . $row["Model"] . "</td><td>"
. $row["Type"]. "</td><td>". $row["InProduction"]. "</td><td>". $row["Price"]. "</td><td>".$row["Range"]. "</td><td>". $row["MaxSpeed"].
"</td><td>". $row["HP"]."</td><td>". $row["Country"]."</td><td>". $row["Etype"]."</td><td>". $row["Make"]. "</td><td>". $row["MPG"].
"</td><td>". $row["Seats"]."</td></tr>";
$counter++;
if($counter % 33 == 0) { ?>
</table>
<table class="table1">
<tr>
<th>Date</th>
<th>Model</th>
<th>Type</th>
<th>InProduction</th>
<th>Price</th>
<th>Range</th>
<th>MaxSpeed</th>
<th>HP</th>
<th>Country</th>
<th>EType</th>
<th>Make</th>
<th>MPG</th>
<th>Seats</th>
</tr>
<?php }
}
echo "</table>";
} else { echo "0 results"; }
$conn->close();
?>
</table>
Here I included all the parameters to be displayed on the page. Instead, what I would like to do is to use different parameters in each query. So with every click of a button, I'll be able to see different parameters listed as a table on the index page. So I plan to create several php files to list different parameters, and run them with the click of a button on the index.php. How can I do this with onclick button? and is this the most suitable way for this task? Note: I will publish this only locally. Thanks.
I found an ajax solution to the problem. It is not very neat and short but it works. I am open to any shorter way to achieve this task, I'd be grateful if you share. thanks. Here is the source of the solution: http://javascript-coder.com/tutorials/re-introduction-to-ajax.phtml
So for every button, the ajax code needs to be repeated with corresponding Id's.
HTML:
<div id="querydiv"> </div>
<button id='actbutton1'>query1</button>
AJAX:
<script>
document.getElementById('actbutton1').onclick=function()
{
var xhr = new XMLHttpRequest();
xhr.open("GET", "query1.php", true);
xhr.onreadystatechange = function ()
{
if (xhr.readyState==4 && xhr.status==200)
{
document.getElementById("querydiv").innerHTML=xhr.responseText;
}
}
xhr.send();
}
</script>
Depending on what exactly you want to do, you can also just use a query string to switch on/off of what queries/data you want the user to see. You can easily add the query string to the url in a button as you wish by simply setting the parameter in the onclick event:
<button onclick="location.url = '/mypage.php?show=firstdata';">Button1</button>
The switch of the queries in the PHP could look like the following:
if($_GET['show'] == "firstdata") {
//
// the first type query here
//
}elseif($_GET['show'] == "seconddata") {
//
// the second type query here
//
}

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.

Table with database values and user input

So I've been wrestling with this issue on and off for quite a while now, and just like driving around lost in a strange city, I am finally breaking down for direction! I am developing table with values from a database, but also need a column that will process user input. I have been able to display the table but my input is not updating the necessary database element. Code below:
<?php
include("pogsatbetbuddy.inc.php");
$cxn=mysqli_connect($host,$username,$password,$db_name)
or die("Did Not Connect");
$query="SELECT * FROM $tbl2_name ORDER BY $tbl2_name.$col_name ASC";
$result=mysqli_query($cxn,$query)
or die("Query Not Working");
echo"<table border='1'
<form name='payments' action='' method='POST'>
<tr>
<td class='update' colspan='5'>
<button data-theme='b' id='submit' type='submit'>Update</button>
</td>
</tr>
<tr>
<th class='profile'>Last Name</th>
<th class='profile'>First Name</th>
<th class='profile'>Saturday Payment Owing</th>
<th class='profile'>Enter Payment</th>
<th class='profile'>Saturday Balance</th>
</tr>";
while ($row=mysqli_fetch_assoc($result))
{
extract ($row);
echo"<tr>
<td class='profile'>$lastname</td>
<td class='profile'>$firstname</td>
<td class='profile'>$owingsat</td>
<td class='profile'><input type='number' name='paidsat' value=''/></td>
<td class='profile'>$owingsat-$paidsat</td>
</tr>";
}
echo "</form>";
echo "</table>";
This displays the table in the way I want. Having worked through the results of the following code, it seems that I am returning a null value, so I am thinking I have an issue with either the form action or the submit Update button, but can not find the solution after much experimentation and searching. Balance of code below:
if(isset($_POST['paidsat']))
{
$paidsat = $_POST['paidsat'];
if(($paidsat) != null)
{
$stmt = $cxn->prepare("UPDATE $tbl2_name SET paidsat = ? WHERE firstname=? and lastname=?");
$stmt->bind_param('sss', $paidsat, $firstname, $lastname);
$status = $stmt->execute();
if($status === true) //To check if the execute was successful
{
echo("<p class='click'>You have successfully added the payment for $firstname $lastname\n<br /></p>");
}
}
else echo"Not Successful";
}
else echo "<p class='click'>Make your changes as required</p>";
mysqli_close($cxn);
Everything comes to a crashing halt at the second if statement.....or should I say, although things look pretty, they don't function! Thanks in advance, appreciate any help!
Be sure you have a proper value for $tbl2_name checking
var_dump($tbl2_name)
in your code before the update
and for debug try using a string concatenation like
"UPDATE " . $tbl2_name . " SET paidsat = ? WHERE firstname=? and lastname=?";
and try use
if( $paidsat != NULL )
and last check if you have proper value for update
paidsat = ? WHERE firstname=? and lastname=?
Try
var_dump( $paidsat);
var_dump( $firstname);
var_dump( $lastname);
and build a proper select for test if you value math the rows you think and
test this select in you db console

PHP echoing MySQL data into HTML table

So I'm trying to make a HTML table that gets data from a MySQL database and outputs it to the user. I'm doing so with PHP, which I'm extremely new to, so please excuse my messy code!
The code that I'm using is: braces for storm of "your code is awful!"
<table class="table table-striped table-hover ">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Description</th>
<th>Reward</th>
<th>Column heading</th>
</tr>
</thead>
<tbody>
<?php
$con = mysql_connect("localhost", "notarealuser", 'notmypassword');
for ($i = 1; $i <= 20; $i++) {
$items = ($mysqli->query("SELECT id FROM `items` WHERE id = $i"));
echo ("<tr>");
echo ("
<td>
while ($db_field = mysqli_fetch_assoc($items)) {
print $db_field['id'];
}</td>");
$items = ($mysqli->query("SELECT name FROM `items` WHERE id = $i"));
echo ("
<td>
while ($db_field = mysqli_fetch_assoc($items)) {
print $db_field['name'];
}</td>");
$items = ($mysqli->query("SELECT descrip FROM `items` WHERE id = $i"));
echo ("
<td>
while ($db_field = mysqli_fetch_assoc($items)) {
print $db_field['descrip'];
}</td>");
$items = ($mysqli->query("SELECT reward FROM `items` WHERE id = $i"));
echo ("
<td>
while ($db_field = mysqli_fetch_assoc($items)) {
print $db_field['reward'];
}</td>");
$items = ($mysqli->query("SELECT img FROM `items` WHERE id = $i"));
echo ("
<td>
while ($db_field = mysqli_fetch_assoc($items)) {
print $db_field['img'];
}</td>");
echo ("</tr>");
}
?>
</tbody>
</table>
However, this code is not working - it simply causes the page to output an immediate 500 Internal Server Error. IIS logs show it as a 500:0 - generic ISE. Any ideas?
You are mixing mysql and mysqli, not closing php code block and you are not selecting a database. Plus you don't have to run a query for each field
Try this:
<table class="table table-striped table-hover ">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Description</th>
<th>Reward</th>
<th>Column heading</th>
</tr>
</thead>
<tbody>
<?php
$con = new mysqli("host","user", "password", "database");
$execItems = $con->query("SELECT id, name, descrip, reward, img FROM `items` WHERE id BETWEEN 1 AND 20 ");
while($infoItems = $execItems->fetch_array()){
echo "
<tr>
<td>".$infoItems['id']."</td>
<td>".$infoItems['name']."</td>
<td>".$infoItems['descrip']."</td>
<td>".$infoItems['reward']."</td>
<td>".$infoItems['img']."</td>
</tr>
";
}
?>
</tbody>
</table>
<table class="table table-striped table-hover">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Description</th>
<th>Reward</th>
<th>Column heading</th>
</tr>
</thead>
<tbody>
<?php
$con = mysqli_connect("hostname","username",'password');
$sql= "SELECT * FROM `items` WHERE id <20 ";
$items = (mysqli_query($sql));
while ( $db_field = mysqli_fetch_assoc($items) ) {?>
<tr><td><?php echo $db_field['id'];?></td></tr>
<tr><td><?php echo $db_field['name'];?></td></tr>
<tr><td><?php echo $db_field['descrip'];?></td></tr>
<tr><td><?php echo $db_field['reward'];?></td></tr>
<tr><td><?php echo $db_field['img'];?></td></tr>
<?php}
</tbody>
</table>
Try these, not tested
Where is the question?
There's many problems with this code.
First, you are confused between PHP and HTML.
Code between is PHP. It's executed on the server, you can have loops and variables and assignments there. And if you want some HTML there you use "echo".
Code outside is HTML - it's sent to the browser as is.
Second - what you seem to be doing is querying each field separately. This is not how you work with SQL.
Here's more or less what you need to do:
//Query all rows from 1 to 20:
$items = $mysqli->query("SELECT id,name,descrip,reward,img FROM `items` WHERE id between 1 and 20");
//Go through rows
while ( $row = mysqli_fetch_assoc($items) )
{
echo "<tr><td>{$db_field['id']}</td>";
//echo the rest of the fields the same way
});
I'm going to go ahead and assume that the code isn't working and that's because there's several basic errors. I'd strongly suggest doing some hard reading around the topic of PHP, especially since you're using databases, which, if accessed with insecure code can pose major security risks.
Firstly, you've set-up your connection using the procedural mysql_connect function but then just a few lines down you've switched to object-orientation by trying to call the method mysqli::query on a non object as it was never instantiated during your connection.
http://php.net/manual/en/mysqli.construct.php
Secondly, PHP echo() doesn't require the parentheses. PHP sometimes describes it as a function but it's a language construct and the parentheses will cause problems if you try to parse multiple parameters.
http://php.net/manual/en/function.echo.php
Thirdly, you can't simply switch from HTML and PHP and vice-versa with informing the server/browser. If you wish to do this, you need to either concatenate...
echo "<td>".while($db_filed = mysqli_fetch_assoc($item)) {
print $db_field['id'];
}."</td>;
Or preferably (in my opinion it looks cleaner)
<td>
<?php
while($db_filed = mysqli_fetch_assoc($item)) {
print $db_field['id'];
}
?>
</td>
However, those examples are based on your code which is outputting each ID into the same cell which I don't think is your goal so you should be inserting the cells into the loop as well so that each ID belongs to its own cell. Furthermore, I'd recommend using echo over print (it's faster).
Something else that may not be a problem now but could evolve into one is that you've used a constant for you FOR loop. If you need to ever pull more than 20 rows from your table then you will have to manually increase this figure and if you're table has less than 20 rows you will receive an error because the loop will be trying to access table rows that don't exist.
I'm no PHP expert so some of my terminology might be incorrect but hopefully what knowledge I do have will be of use. Again, I'd strongly recommend getting a good knowledge of the language before using it.

Categories