Im using a datatable to show records from a DB, using PHP.
See my code below;
<table class="table datatable-basic">
<thead>
<tr>
<th> ID </th>
<th> Name</th>
<th>Address </th>
<th class="text-center">Actions</th>
</tr>
</thead>
<tbody>
<?
$result9023=mysql_query("SELECT * FROM hr_locations")or die('ERROR 315' );
$num_rows = mysql_num_rows($result9023);
for ($i = 1; $i <= mysql_num_rows($result9023); $i++) {
$row = mysql_fetch_array($result9023);
$location_id = $row ['id'];
$name = $row ['location'];
$address = $row ['address'];
echo " <tr>
<td>$location_id</td>
<td>$name</td>
<td>$address</td>
<td class='text-center'>Edit</td>
</tr>
"; } ?>
</tbody>
</table>
The table is showing correctly, with the data populated as it should however I am getting the below error when the page loads.
I have looked at https://datatables.net/tn/4 however it's not making much sense?
Since most MySQL array start with 0 do this:
for ($i = 0; $i < $num_rows; $i++) {
Set $i = 0 then state that $i must be less than the number of rows (if you have 4 you will get 0,1,2,3 (4 rows, properly indexed). Instead of counting the rows again, just use the variable you already set for the count.
You're actually probably doing a little too much with your code. Instead of using an unnecessary for loop, just use a while:
while($row = mysql_fetch_array($result9023)){
$location_id = $row ['id'];
$name = $row ['location'];
$address = $row ['address'];
echo " <tr>
<td>$location_id</td>
<td>$name</td>
<td>$address</td>
<td class='text-center'>Edit</td>
</tr>
"; } ?>
This way you're making sure to catch each row returned from your query without possibly duplicating or skipping rows as you might do when using a for loop along with mysql_fetch_array() as you're trying to do.
Related
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...
so, what i wanted to do is show the total clicks per Category id of the items only for 20 items order by the highest total clicks per day.
now i am using hard code and the result have to looks like this
so, if the item id and total clicks already fill up the
20columns (for item id and total clicks) + 2 for the tittle so means
22columns
it has to move to next row.
because i am reffering to my db, so i am using loop to create the table, and when i doing that way, i am getting this result....
the result will keep showing until the end in the left side. thats very hard to read for report purposes. so i wanted the result looks like the first figure that i've uploaded.
here is what i am doing now
include "Con.php";
//get the value from Get Method
$CatidValue = $_GET['CatIds'];
//(The date format would looks like yyyy-mm-dd)
$DateFrom = $_GET['DateFrom'];
$DateTo = $_GET['DateTo'];
//select the CatID
$SqlGet= "Select CatId from try where CatId = $CatidValue";
$_SqlGet = mysqli_query($connection,$SqlGet);
$TakeResultGet = mysqli_fetch_array($_SqlGet);
$CatIdTittle = $TakeResultGet ['CatId'];
echo"
For Category Id : $CatIdTittle
<br>
";
//For Loop purpose and break the value
$explodeValueFrom = explode("-",$DateFrom);
$explodeValueTo = explode("-",$DateTo);
$DateValueFrom = $explodeValueFrom[0].$explodeValueFrom[1].$explodeValueFrom[2];
$DateValueTo = $explodeValueTo[0].$explodeValueTo[1].$explodeValueTo[2];
//Loop through the date
for($Loop=$DateValueFrom; $Loop <= $DateValueTo; $Loop++){
$YearLoop= substr($Loop, 0,4);
$MonthLoop =substr($Loop, 4,2);
$DayLoop = substr($Loop, 6,2);
$DateTittleValue = $YearLoop."-".$MonthLoop."-".$DayLoop;
$trValue = "<th class='tg-amwm' colspan='2'>$DateTittleValue</th>";
echo"
<table class='tg'>
<tr>
$trValue
</tr>
";
echo"
<table class='tg'>
<tr>
<td class='tg-yw4l'>Items Id</td>
<td class='tg-yw4l'>Total Clicks</td>
</tr>
";
//to get the item id and total clicks
$SqlSelect = "select `Item Id`,`Total Clicks`,Day from try where CatId = $CatidValue and Day = '$DateTittleValue' ORDER BY `try`.`Total Clicks` DESC limit 20";
$_SqlSelect = mysqli_query($connection,$SqlSelect);
foreach ($_SqlSelect as $ResultSelect) {
$Day = $ResultSelect['Day'];
$ItemId = $ResultSelect['Item Id'];
$TotalClicks = $ResultSelect['Total Clicks'];
echo"
<tr>
<td class='tg-yw4l'>$ItemId</td>
<td class='tg-yw4l'>$TotalClicks</td>
</tr>
";
}
}
?>
You dont need to declare your trValueTitle in the loop. Plus you need to concatenate it in your echo, try this :
$trValueTittle ="1"."<th class='tg-amwm' colspan='2'>$DateTittleValue</th>" ;
echo"<table class='tg'>";
for($loopForTr=1; $loopForTr<=3; $loopForTr++){
echo"<tr>". $trValueTittle ."</tr>";
}
I don't know what you want to do with the "1", but I think this is what you want to do:
echo "<table class='tg'>";
for($loopForTr=1; $loopForTr<=3; $loopForTr++){
$trValueTittle ="<th class='tg-amwm' colspan='2'>$DateTittleValue</th>";
echo"
<tr>
$trValueTittle
</tr>";
}
echo "</table>";
$trValueTittle ="1"."<th class='tg-amwm' colspan='2'>$DateTittleValue</th>" ;
echo"<table class='tg'>
<thead>
<tr>";
for($loopForTr=1; $loopForTr<=3; $loopForTr++){
echo $trValueTittle;
}
echo"</tr>
</thead>
</table>";
#Mantello, good answer, but i think it's better to keep out the "tr" from the loop, cause usually you don't want to place your tableheads (th) in different rows.
#Rax your Code won't work. You'll recive an error. You can't output a Variable the way you did in your echo.
echo"<tr> '.$trValueTittle.' </tr>";
would be fine. But there's also no need to define your variable inside the for loop. This way you slow up your script.
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.
Is there a way to show data inside td and allow user to edit it in a way that the change will take place in the sql (MySQL in my case) table?
im creating a table from database using angularJS:
Creating The json file from the table:
$result = mysql_query("select * from `user script settings`");
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['user_id'] = $row['user id'];
$row_array['script_id'] = $row['script id'];
$row_array['cron_format'] = $row['cron format'];
$row_array['schedule_last_update'] = $row['schedule last update'];
$row_array['next_execution_time'] = $row['next execution time'];
$row_array['script_exec'] = $row['script_exec'];
//push the values in the array
array_push($json_response,$row_array);
}
echo json_encode($json_response);
showing it in the table:
<table class="table table-bordered table-hover">
<thead>
<td>user name</td>
<td>script name</td>
<td>cron format</td>
<td>schedule last update</td>
<td>next execution time</td>
<td>script exec</td>
</thead>
<tbody>
<tr ng-repeat="x in data">
<td>{{x.user_id}}</td>
<td>{{x.script_id}}</td>
<td>{{x.cron_format}}</td>
<td>{{x.schedule_last_update}}</td>
<td>{{x.next_execution_time}}</td>
<td>{{x.script_exec}}</td>
</tr>
</tbody>
</table>
<script>
function customersController($scope,$http) {
$http.get("getData.php")//test3.php return a json file of users table
.success(function(response) {$scope.data = response;});
}
</script>
I want to allow user to change the cron format value and to update the table ...is there "angularish" way to due that?? if not i'll appreciate guidance for a php solution, thx!
I have to pull from a table that's been made by someone else and print it onto a web page. Issue is, that column name are stored in the rows. For instance:
FIELD_NAME| FIELD_VALUE
______________________
first-name| John
last-name | Smith
This is how I'm going about grabbing the data
$tableRow = '';
$sql ="SELECT * FROM `wp_cf7dbplugin_submits` WHERE form_name = '".$nameOfForm."' ";
$result = $mysqli->query($sql);
while($tableData = $result->fetch_assoc()){
$fieldName = $tableData['field_name'];
$fieldValue = $tableData['field_value'];
//FIRST NAME
if($fieldName == 'first-name'){
$firstName = $fieldValue;
}
//LAST NAME
if($fieldName == 'last-name'){
$lastName = $fieldValue;
}
//BUILD A ROW FOR THE TABLE
$tableRow .='
<th>'.$firstName.'</th>
<th>'.$lastName.'</th>
';
}
it only KIND of works when I do $tableRow = instead of $tableRow .=
it will only show me one result, but when I do $tableRow .= it will only show me empty but the correct amount of s.
How can I populate an html table with all of the results pulling from a table like this?
EDIT:
I forgot to mention that the whole table looks like this:
<table id="theTable">
<thead>
<tr>
<th style="width:100px;">First Name</th>
<th style="width:100px;">Last Name</th>
</tr>
</thead>
<tbody id="rowsGoHere">
</tbody>
</table>
and I echo the PHP result via ajax,
//ECHO BACK RESULTS
$JSONData = array("true", $tableRow);
echo $_GET['callback']."(".json_encode($JSONData).")";
and use this to insert into table
var trueEncV = encodeURIComponent("true");
$.getJSON("pullTableData.php?callback=?",
{
trueV: trueEncV
},
function(dataBack){
alert(dataBack);
$('#rowsGoHere').html(dataBack[1]);
}
)
That all works fine and dandy.
According to your updated code the <tr> tags are missing. Also, within <tbody> you should use the <td> tag instead of the <th> tag.
$tableRow .='
<tr>
<td>'.$firstName.'</td>
<td>'.$lastName.'</td>
</tr>
';
Can you try
echo json_encode($JSONData);
instead of
echo $_GET['callback']."(".json_encode($JSONData).")";