PHP fetch_row limits the result - php

I have a table with the rows but for some reason it populates only 14 rows. I have around 800 rows in the db. Any ideas?
code:
$result = mysqli_query($con,"SELECT * FROM translation ORDER BY id");
while($row = mysqli_fetch_row($result) and $property = mysqli_fetch_field($result))
{
echo "<tr>";
foreach($row as $column => $value) {
// $column is column name 'englsih', 'spanish' etc.
$name = $property->name;
echo "<td align='left' class='cell".$column."'>". $value . "</td>";
}
echo "<td><span class='edit_b'></span><span class='remove_b'></span></td></tr>";
}
echo "</thead></table>";

I assume your translation table has 14 columns?
The problem is this:
... and $property = mysqli_fetch_field($result) )
You are fetching information about the columns in your result-set - and not even using it - and as soon as you have passed the last column, this will return false and your loop will end.
Don't fetch information about the columns in the same loop as your main results loop.

Related

Get SQLite Table Data into HTML Table

I have an SQLite database and using PHP to serve up and interact the data with.
I am trying to build an HTML table with for each SQLite table columns as the HTML Table Columns and then for each row in the SQLite table render as a for each row in the HTML table.
Issue is that each sql row data is only rendered into one html table row (with current code) (should be for each row) question would be how I go about getting the sql row data into array for looping through to render html table rows.
Currently I have;
PHP get the SQL Columns into the HTML table & SQl Row data(foreach) into HTML Table Rows (foreach)
//get table count
$countTable = $dbConnect->querySingle("SELECT COUNT(*) as count FROM ".$table['name']."");
if($countTable){
//data exists, do work
//new query to get table data
$query = $dbConnect->query("SELECT * FROM ".$table['name']." ORDER BY id DESC");
//init arrays
$dataColumns = array();
$dataRows = array();
while($row = $query->fetchArray(SQLITE3_ASSOC))
{
//add columns to array, checking if value exists
foreach($row as $key => $value)
{
if(in_array(''.$key.'', $dataColumns)){
//column already in array, dont add again.
}else{
//column not in array, add it.
$dataColumns[]=array(
'column'=>$key
);
}
//while in this foreach do I add the row values to an array or do it again outside this loop?
//below does not work, only adds to the one array item and renders one HTML Table row with multiple SQL Table row values
$dataRows[]=array(
'row_item'=>$row[''.$row.'']
);
}
}
//build HTML table
echo '<div class="table-responsive"><table class="table"><thead><tr>';
//build columns from array... works
foreach($dataColumns as $dataColumn){
echo '<th>'.$dataColumn['column'].'</th>';
}
//close table column headers 7 start HTML table body...
echo '</tr></thead><tbody>';
//Issue is here, how do I get the each row (value is either null or not null) to
echo '<tr>';
foreach($dataRows as $dataRow){
echo '<td>'.$dataRow['row_item'].'</td>';
}
echo '</tr>';
//close table body & table...
echo '</tbody></table></div>';
}else{
//table has no data
echo 'no data in the selected table';
}
I rewrote this to do it all in one loop like this.
$firstRow = true;
echo '<div class="table-responsive"><table class="table">';
while ($row = $query->fetchArray(SQLITE3_ASSOC)) {
if ($firstRow) {
echo '<thead><tr>';
foreach ($row as $key => $value) {
echo '<th>'.$key.'</th>';
}
echo '</tr></thead>';
echo '<tbody>';
$firstRow = false;
}
echo '<tr>';
foreach ($row as $value) {
echo '<td>'.$value.'</td>';
}
echo '</tr>';
}
echo '</tbody>';
echo '</table></div>';
You might find it clearer to read? It also avoids building an array of all the dataRows in memory.
Try to replace
$dataRows[]=array(
'row_item'=>$row[''.$row.'']
);
with
$dataRows[]=$row;
Put this line at first line inside your while loop (or general outside the foreach loop over your columns), because adding a row is not connected analyzing your columns.
Then, in your output foreach, you should find the rows with all columns selected from your database query inside $dataRow (here symbolized with column1, column2, …):
echo '<tr>';
foreach($dataRows as $dataRow){
echo '<td>'.$dataRow['column1'].'</td>';
echo '<td>'.$dataRow['column2'].'</td>';
echo '<td>'.$dataRow['column3'].'</td>';
echo '<td>'.$dataRow['column4'].'</td>';
echo '<td>'.$dataRow['column5'].'</td>';
echo '<td>'.$dataRow['column6'].'</td>';
echo '<td>'.$dataRow['column7'].'</td>';
// etc.
}
echo '</tr>';
After all your code should look like this (a bit simplified):
$query = $dbConnect->query("SELECT * FROM ".$table['name']." ORDER BY id DESC");
$dataColumns = array();
$dataRows = array();
while ($row = $query->fetchArray(SQLITE3_ASSOC)) {
$dataRows[] = $row;
foreach ($row as $key => $value) {
//Bilding $dataColumns, see Question
}
}
echo '<div class="table-responsive"><table class="table"><thead><tr>';
foreach ($dataColumns as $dataColumn) {
echo '<th>'.$dataColumn['column'].'</th>';
}
echo '</tr></thead><tbody>';
echo '<tr>';
foreach ($dataRows as $dataRow) {
foreach ($dataRow as $columnName => $columnValue) {
echo '<td>'.$columnValue.'</td>';
}
}
echo '</tr>';
echo '</tbody></table></div>';
Thanks to akrys
in the while loop, but outside the foreach column loop;
//$dataRows = array();
$dataRows[]=$row;
and in the building of the HTML Table;
foreach($dataRows as $dataRow){
echo '<tr>';
foreach($dataRow as $key => $value){echo '<td>'.$value.'</td>';}
echo '</tr>';
}

Compare rows in PHP

Hi I would like to compare two tables from two different databases.
Select from the first database
$sql= mysqli_query ("SELECT * FROM emasa.staff_detail");
$row = mysqli_fetch_array($sql);
Select from the second database
$sql2 = mysqli_query ("SELECT * FROM employee");
$row2 = mysqli_fetch_array($sql2);
Then I compare the two table
if ($row['icnum'] == $row2['emp_ic'])
{
echo "Data already exist in both database.";
}
else
{
while ($row = mysqli_fetch_assoc($sql))
{
echo "<td align='center' height='30'>" . $row ['name'] . "</td>";
echo "<td align='center'>" .$row['icnum'] . "</td>";
}
}
But my problem is it only compares the first row in the database.
My output should only display the staff name that is not available in the other database. However, this is my output.
Based on the output it only compares the first row. So how do I change my code so that it compares the whole row. Please help me, thank you!
You're not looping through the results of the query. You're simply getting back the first row and going with that.
Ex:
$sql= mysqli_query ("SELECT * FROM emasa.staff_detail");
This is returning a result set which you then need to use
$row = mysqli_fetch_array($sql);
to get the actual values. The problem comes when
$row = mysqli_fetch_array($sql);
by itself only gives you one row.
Solution 1
You must use code like this:
while($row = mysqli_fetch_array($sql))
{
//Do some comparison
}
Since you're going to have to loop through two different result sets, you're going to have to do a loop within a loop, build an array of results and then loop through the results afterwards to output your HTML.
Ex:
while($row = mysqli_fetch_array($sql))
{
while($row2 = mysqli_fetch_array($sql2))
{
if ($row['icnum'] == $row2['emp_ic'])
{
//add to array of equal data
}
else
{
//add to array of not equal data
}
}
}
foreach($array as $not_equal_or_equal_data)
{
//output your desired HTML
}
Solution 2
Depending on what you actually care about, you could do a sql statement like this
$sql = "
SELECT
*
FROM
emasa.staff_detail AS sd
JOIN db2.employee AS e
ON sd.icnum = e.emp_ic";
This would return all the rows where those two columns were equal

Why does MySQL Query skips null value? How to prevent MySQL skipping the NULL value?

I would like to know why MySQL Query serves different number of columns when some values in NULL or Zero(Integer Case).
For example, I have due as "0" integer (not sting - without Quotes) in some columns. When I make a query, I want to show "0" integer. But that column is skipped.
Can't it return just nothing instead of skipping the NULL value?
How Can we overcome this error?
$sql = "SELECT * FROM `2014-02-20`";
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($query);
while ($row = mysqli_fetch_assoc($query)){
while ($this_item = current($row)) {
echo key($row)."-->".$row[key($row)]."<br />";
next($row);
}
echo "<br />";
}
?>
I see different results like:
Case 1 (with 0 in due column)
qty-->1
amount-->390
Case 2 (with some value in due)
activity-->sales
qty-->1
amount-->25500
Use foreach in the inner loop:
while ($row = mysqli_fetch_assoc($query)){
foreach($row as $key => $value) {
echo "$key --> $value <br />";
}
echo "<br />";
}
A foreach loop will iterate through the whole $row array regardless of values that might evaluate to false.

Generate HTML table from SQL query

From the image above, I am trying to generate this table dynamically with PHP. Below is my tables in the mysql DB
Here is the SQL that I am using to pull the data from the database
SELECT DISTINCT execution_date,class_name,method_name,status FROM test_cases INNER JOIN test_case_executions ON test_cases.id=test_case_executions.test_case_id WHERE version='$platform' AND execution_date >= ( CURDATE() - INTERVAL 2 DAY ) ORDER BY execution_date DESC;
This is returning the data that need but I am struggling to figure out how to build the table. I was thinking of using arrays and when I have all the data I need, then echo out the table code. The thing I need to guard is that a test is not always guaranteed that there will be three dates for a test. Thanks for the help in advance.
You will have to do a couple passes on your data set to generate that output. That is, you'll have lets say 4 rows representing all of the status values and you will have to iterate over it a couple of times to extract out the date column headers and the "Class" row identifiers.
You can perform this in PHP. So on the 1st pass you grab the dates for the header. And also store the "Class" for the first column.
On the 2nd pass you then iterate over the data again but this time its wrapped in a loop so you can pull out the records for that cell.
Here is some psuedo-code:
$records = $db->query("select * from your_query here...");
$dates = [];
$classes = [];
// first pass is to pull out the distinct dates & classes which represent our bounds
foreach($records AS $record) {
$dates[] = $record['execution_date'];
$classes[] = $record['class_name'];
}
// distinct the date set and sort them from lowest to highest
$dates = array_unique($dates);
$dates = sort($dates);
$classes = array_unique($classes);
// display the date row
echo "<tr><td> </td>"
foreach($dates AS $date) {
echo $date;
}
echo "</tr>";
// start displaying each class+date pair
foreach($classes AS $klass) {
echo "<tr>";
echo "<td>" . $klass . "</td>";
// display each date record for this class
foreach($dates AS $date) {
$class_and_date_record = filter($records, $klass, $date);
if($class_and_date_record) {
echo "<td>" . $class_and_date_record['status'] . "</td>";
}
}
echo "</tr>";
}
function filter($records, $klass, $date) {
foreach($records AS $row) {
if($row['class_name'] == $klass && $row['execution_date'] == $date) {
return $row;
}
}
return NULL;
}
If I understand your question correctly, you only want to output data to the table when there is a value in "execution_date"
$query = "SELECT DISTINCT execution_date,class_name,method_name,status FROM test_cases INNER JOIN test_case_executions ON test_cases.id=test_case_executions.test_case_id WHERE version='$platform' AND execution_date >= ( CURDATE() - INTERVAL 2 DAY ) ORDER BY execution_date DESC;";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
echo '<table>';
if(isset($result["execution_date") && !empty($result["execution_date"])){
echo '<tr><td>' . $result["execution_date"] . '</td></tr>';
...
}
echo '</table>';
}
/* free result set */
$result->free();
}
The line to note is :
if(isset($result["execution_date") && !empty($result["execution_date"])){
will check your returned row for execution_date having a value.
You can then print the rest of the items using the same $result["<column name>"] formatting.

Why is PDOStatement->columnCount not returning the right number?

I'm querying the database first to get all records associated with a certain userid, then i need to go in and modify the array, because one of the fields is an id and i need the name associated with that id.
So i use columnCount to iterate through the resulting array at the index of the id and replace it with the right name, which works fine, for the first six results. columnCount only returns 6, but those first six are renamed as they should be. But outside of that it takes the results from that pdostatement and populates the table normally, with all the relevant data, 17 rows right now.
Why is it returning 6, or what am i doing to get that wrong columncount?
global $__CMS_CONN__;
$timeqry = 'SELECT facility_id, program, date, visit_length, mileage, served FROM timesheet_db WHERE volunteer_id = '.$_SESSION['user_id'];
$stmt = $__CMS_CONN__->prepare($timeqry);
$stmt->execute();
$columns = $stmt->columnCount();
print $columns;
if($stmt)
{
$arrValues = $stmt->fetchAll(PDO::FETCH_ASSOC);
for($x=0;$x<$stmt->columnCount();$x++)
{
global $__CMS_CONN__;
$qry = 'SELECT facility FROM facility_db WHERE id = '.$arrValues[$x]['facility_id'];
$stmt1 = $__CMS_CONN__->prepare($qry);
$stmt1->execute();
if($stmt1)
{
$facilityName = $stmt1->fetchAll(PDO::FETCH_ASSOC);
foreach ($facilityName as $item)
{
foreach ($item as $key => $val)
{
$arrValues[$x]['facility_id'] = $val;
}
}
}
}
print "<table style=\"font-size:90%\">\n";
print "<tr>\n";
print "<th style=\"width:100%\">Facility</th>";
print "<th>Program</th>";
print "<th>Date</th>";
print "<th>Visit Length</th>";
print "<th>Mileage</th>";
print "<th>Served</th>";
print "</tr>";
foreach ($arrValues as $row)
{
print "<tr>";
foreach ($row as $key => $val)
{
print "<td>$val</td>";
}
print "</tr>\n";
}
print "</table>\n";
}
You asked for six columns in your first SELECT query:
SELECT facility_id, program, date, visit_length, mileage, served FROM timesheet_db WHERE volunteer_id = $_SESSION['user_id']
So, naturally, columnCount() is 6. It doesn't multiply the column count by the number of rows returned or anything like that.
If you want the number of rows, you need count($arrValues) (the manual says database behavior with rowCount() is inconsistent regarding SELECTs).

Categories