I am building a dynamic table using php, pear HTML_Table, and sql.
My the first query pulls the information for the table headers, and then pear uses this to create the headers. The next query pulls the information from multiple tables to return the correct data sets. Next, I need to tie these data sets to the headers and display the results down each matching column. I am able to display all of the data, but not properly. Column 0 starts at row 1, and displays the current 4 test items, column 1 starts at row 5 and displays the current 2 test items, column 2 then starts at 7...How can I get the column count to reset to 0 after the previous column runs out of matching data? The other part of this problem is that I also need to apply rowSpans to the inserted data as this is a scheduling project. I have been at this for a week now and have been unable to find any relevant examples or suggestions. What am I missing, as I don't think this should be such a difficult task?
Code below.
<?php
session_start();
include_once("../php/functions.php");
include_once("HTML/TABLE.PHP");
$assetHead = headers('Assets', $_SESSION['deptID']);
$captionHeading = $_SESSION['dept'];
$conn = connect();
$attrs = array( 'id' => 'main',
'width' => '100%',
'Border' => '1');
$table = new HTML_Table($attrs);
$table->setAutoGrow(true);
$table->setAutoFill('n/a');
$sql_assets = "select AssetName, AssetID
from Assets
where Assets.DepartmentID = $_SESSION[deptID]";
$stmt1 = sqlsrv_query($conn, $sql_assets);
if ($stmt1)
{
$rows = sqlsrv_has_rows($stmt1);
if ($rows === true)
{
while( $row = sqlsrv_fetch_array( $stmt1, SQLSRV_FETCH_ASSOC) )
{
$assetName [] = $row['AssetName'];
$assetID [] = $row['AssetID'];
}
}
}
else
{
die( print_r(sqlsrv_errors(), true));
}
$i = 0;
foreach($assetName as $val)
{
$table->setHeaderContents(0, $i++, $val);
unset($val);
}
sqlsrv_close($conn);
$conn = connect();
$tsql = "select + 'Job#' + CAST (JobNum AS VARCHAR(10))+ ' ' + Description AS newField, datediff(MI,StartTime, EndTime) / 15 as 'RowSpan', AssetName, AssetID
from Calendar_View, Departments, Status, Assets
where Departments.DepartmentName = '$captionHeading' and Calendar_View.Department = Departments.DepartmentID and AssetStatus = Status.StatusID and
Calendar_View.Asset = Assets.AssetID
order by AssetID asc";
$rowcounter = 1;
$stmt = sqlsrv_query($conn, $tsql);
if ($stmt)
{
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) )
{
for ($i = 0; $i < count($assetID);$i++)
if ($row['AssetID'] == $assetID[$i])
$table->setCellContents($rowcounter++,$i,$row['newField']);
}
}
else
{
die( print_r(sqlsrv_errors(), true));
}
sqlsrv_close($conn);
echo $table->toHTML();
?>
</body>
</html>
$headerCounter = 0;
$stmt = sqlsrv_query($conn, $tsql);
if ($stmt)
{
$rows = sqlsrv_has_rows($stmt);
if ($rows === true)
{
$cellCounter = 1;
$cellPosition = 0;
$rowCounter = 1;
echo "Header position outside of loop: $headerCounter ";
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) )
{
if ($row['AssetID'] == $assetID[$headerCounter])
{
echo "<br>begining of if statement<br>";
echo "Header (beginning of loop) = " . $assetName[$headerCounter] . "<br>" ;
echo "Header Position (beginning of loop) = " . $headerCounter . "<br>";
echo "Row position = " . $rowCounter . "<br>" ;
echo "Cell position = " . $cellPosition . "<br>";
echo "<pre>";
var_dump($row);
echo "</pre>";
/*foreach ($row as $result)
{
echo "<pre>";
var_dump($result);
echo "</pre>";
}*/
$table->setCellContents($rowCounter,$cellPosition,$row['newField']);
//echo "$headerCounter";
//echo "<br>";
echo "Header Name (end of loop) = " . $assetName[$headerCounter] . "<br>" ;
echo "Header Position (end of loop) = " . $headerCounter . "<br>";
echo "Row position = " . $rowCounter . "<br>" ;
echo "Cell position = " . $cellPosition . "<br>";
//$cellPosition++;
$rowCounter++;
echo "end of if statment<br><br>";
}
else
{
echo "<br>header before increase $headerCounter";
echo "<br>header name outside of loop, before increment $assetName[$headerCounter]";
$cellPosition++;
$rowCounter = 1;
$headerCounter++;
$table->setCellContents($rowCounter,$cellPosition,$row['newField']);
echo "<br>header name outside of loop, after increment $assetName[$headerCounter]";
echo "<br>header increased by 1, now: $headerCounter";
}
}//$headerCounter++;
//$table->setCellContents($rowCounter,$cellPosition,$row['newField']);
}
Ok, the problem was that I was not incrementing the rowcounter variable after i left the initial loop. The following line:
$cellPosition++;
$rowCounter = 1;
$headerCounter++;
$table->setCellContents($rowCounter,$cellPosition,$row['newField']);
Should have been:
$cellPosition++;
$rowCounter = 1;
$headerCounter++;
$table->setCellContents($rowCounter++,$cellPosition,$row['newField']);
Sorry for the poor formatting of the original post. I am not sure what went wrong.
Related
I have an html-form to read out data from a DB that are then dislayed in an html-table. Columns that contain no values should not be displayed. This works well with the following code using array_column and array_filter:
$sql = "SELECT DISTINCT $selection FROM $table WHERE $where";
$result = mysqli_query($db, $sql) or die("<b>No results</b>"); //Running the query and storing it in result
$numrows = mysqli_num_rows($result); // gets number of rows in result table
$numcols = mysqli_num_fields($result); // gets number of columns in result table
$field = mysqli_fetch_fields($result); // gets the column names from the result table
$custom_column_arr = array('Color' => 'color_comment', 'Weight' => 'weight_comment');
if($numrows > 0) {
echo "<table id='myTable'>";
echo "<thead>";
$results = array();
while($row = mysqli_fetch_assoc($result)) {
$results[] = $row;
}
echo "<tr>";
echo "<th>" . 'Nr' . "</th>";
for($x = 0; $x < $numcols; $x++) {
$column[$x] = array_column($results, $field[$x]->name); // puts all existing values of a column into the field-name
if(array_filter($column[$x])) { // displays only those columns with at least one value in it
$key = array_search($field[$x]->name, $custom_column_arr);
if($key !== FALSE) {
echo "<th>" . $key . "</th>";
} else {
echo "<th>" . $field[$x]->name . "</th>";
}
}
}
echo "</tr></thead>";
echo "<tbody>";
$nr = 1;
$result = mysqli_query($db, $sql);
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $nr . "</td>";
for($k = 0; $k < $numcols; $k++) { // goes around until there are no columns left
$column[$k] = array_column($results, $field[$k]->name); // puts all existing values of a column into the field-name
if(array_filter($column[$k])) { // displays only those columns with at least one value in it
echo "<td>" . $row[$field[$k]->name] . "</td>"; //Prints the data } } echo "</tr>"; $nr = $nr + 1;
} // End of while-loop
echo "</tbody></table>";
}
}
mysqli_close($db);
}
Due to security reasons, I switched to PDO prepared statements to avoid SQL-injection:
enter code here
$sql = "SELECT DISTINCT $selection FROM $table WHERE color = :color AND weight = :weight";
$stmt = $pdo->prepare($sql);
$renalstatus = '10';
$bindValue = implode("/n ", $bindValue);
$stmt->bindValue(':color', $color, PDO::PARAM_STR);
$stmt->bindValue(':weight', $weight, PDO::PARAM_INT);
$stmt->execute();
$zeilen = $stmt->rowCount();
$spalten = $stmt->columnCount();
if($zeilen > 0) {
echo "<table id='myTable'>";
echo "<thead>";
$results = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$results[] = $row;
}
echo "<tr>";
echo "<th>" . 'Nr' . "</th>";
for($x = 0; $x < $spalten; $x++) {
$column[$x] = array_column($results, $fields[$x]->name); // puts all existing values of a column into the field-name
if(array_filter($column[$x])) { // displays only those columns with at least one value in it
$key = array_search($fields[$x], $custom_column_arr);
if($key !== FALSE) {
echo "<th>" . $key . "</th>";
} else {
echo "<th>" . $fields[$x] . "</th>";
}
}
}
echo "</tr></thead>";
echo "<tbody>";
$nr = 1;
$stmt = $pdo->query($sql);
while($row = $stmt->fetch(PDO::FETCH_NUM)) {
echo "<tr>";
echo "<td>" . $nr . "</td>";
for($k = 0; $k < $spalten; $k++) { // goes around until there are no columns left
$column[$k] = array_column($results, $fields[$k]->name); // puts all existing values of a column into the field-name
if(array_filter($column[$k])) { // displays only those columns with at least one value in it
echo "<td>" . $row[$k] . "</td>"; //Prints the data}
}
echo "</tr>";
$nr = $nr + 1;
} // End of while-loop
echo "</tbody></table>";
}
}
$stmt->close();
The query results are correctly displayed as before. However, completely empty columns are displayed as well and shoul be hidden.
After having built the headline, in mysqli there is a second query before the rows are generated:
$result = mysqli_query($db, $sql);
Unfortunately, using PDO this does not work with:
$stmt = $pdo->query($sql); or $stmt->execute();
I would be more than happy if someone could help me make this function work again!
How i separate the first result of for each loop and remaining. I have 2 divs, i want first result to be displayed there and rest on another div.
Also is there any way that i can get json decode without for each loop, i want to display result based on for each values from database, and querying database in for each loop is not recommended.
Here is my code, What i want
<div class="FirstDiv">
Result1
</div>
<div class="RemDiv">
Remaining result from for each loop
</div>
Here is full code
$data = json_decode($response->raw_body, true);
$i = 0;
foreach($data['photos'][0]['tags'][0]['uids'] as $value) {
if (++$i == 6)
break;
$check = "SELECT fullname FROM test_celebrities WHERE shortname = '$value[prediction]'";
$rs = mysqli_query($con,$check);
if (mysqli_num_rows($rs)==1) //uid found in the table
{
$row = mysqli_fetch_assoc($rs);
$fullname= $row['fullname'];
}
echo 'Celebrity Name: ' . $fullname . '<br/>';
echo 'Similar: ' . $value['confidence']*100 .'%'. '<br/><br/>';
echo "<img src='actors/$value[prediction].jpg'>";
echo "<hr/>";
}
Try this:
$data = json_decode($response->raw_body, true);
$i = 0;
echo '<div class="FirstDiv">'; // add this line here
foreach( $data['photos'][0]['tags'][0]['uids'] as $value ) {
if (++$i == 6) break;
$check = "SELECT fullname FROM test_celebrities WHERE shortname = '$value[prediction]'";
$rs = mysqli_query($con,$check);
if ( mysqli_num_rows($rs) == 1 ) { //uid found in the table
$row = mysqli_fetch_assoc($rs);
$fullname= $row['fullname'];
}
// Echo celebrity information:
echo 'Celebrity Name: ' . $fullname . '<br/>';
echo 'Similar: ' . $value['confidence']*100 .'%'. '<br/><br/>';
echo "<img src='actors/$value[prediction].jpg'>";
echo "<hr/>";
if ($i==1) { echo '</div><div class="RemDiv">'; }; // add this line here
}
echo '</div>'; // close the last tag
$predictions=array();
foreach($data['photos'][0]['tags'][0]['uids'] as $value) {
$predictions[]="'" . mysqli_real_escape_string($con, $value[prediction]) . "'";
}
$check="SELECT fullname FROM test_celebrities WHERE shortname IN (" . implode(',' $predictions) . ")";
$rs = mysqli_query($con,$check);
while ($row = mysqli_fetch_assoc($rs)) {
if (!$count++) {
// this is the first row
}
But note that you now have two sets of data which are sorted differently - hence you'll need to iterate through one and lookup values in the other.
I have the following bit of code, that selects a table, loops through all the values which match an actor and displays the reviews for that actor.
include("app/config/db.php");
$aid=$actor['id'];
$query = "SELECT * FROM `reviews` WHERE `actor_id` = $aid";
$result = $mysqli->query($query);
$num_results = $result->num_rows;
if( $num_results ){
//loop to show each records
while( $row = $result->fetch_assoc() ){
extract($row);
echo "<span class=\"review-score\">";
echo $row['score']*10;
echo "</span>";
echo " by <strong>";
echo $row['author'];
echo "</strong>";
echo " on <strong>";
echo $row['created_at'];
echo "</strong>";
echo "<p class=\"review-body\">";
echo $row['body'];
echo "</p>";
echo "</br>";
}
}else{
echo "No records found.";
}
$result->free();
$mysqli->close();
I want to convert to using PDO prepared statements.
This is what I've tried. It doesn't display any of the reviews assigned to the actor. Please help
include("app/config/db.php");
$aid=$actor['id'];
$st = DBase::singleton()
->prepare(
'select * ' .
'from `reviews` ' .
'where `actor_id` like :aid ' .
'limit 0,10');
$st->bindParam(':aid', $aid, PDO::PARAM_STR);
if ($st->execute())
{
while ($row = $st->fetch(PDO::FETCH_OBJ))
{
echo "<span class=\"review-score\">";
echo $st['score']*10;
echo "</span>";
echo " by <strong>";
echo $st['author'];
echo "</strong>";
echo " on <strong>";
echo $st['created_at'];
echo "</strong>";
echo "<p class=\"review-body\">";
echo $st['body'];
echo "</p>";
echo "</br>";
}
}
DBase:singleton
static public function singleton()
{
if (!is_object(self::$pdo))
{
self::$pdo = new PDO('mysql:dbname=' . self::DATABASE . ';host=' . self::HOST,
self::USERNAME,
self::PASSWORD);
}
return self::$pdo;
}
You're storing each row's result in $row, but not accessing $row when you want to display the data.
while ($row = $st->fetch(PDO::FETCH_OBJ))
{
...
echo $st['score']*10;
The echo line should be:
echo $row->score*10;
You're also fetching objects but accessing the data as an array.
thats how I was taught to write a while loop.. how else could I do it?
My point is that if assign a variable with successive values of the row, then the data is in that variable, not in the object that iterates over rows. What you've done is analogous to this:
for ($i = 0; $i < $count; $i++) {
echo $count;
}
Whereas in that example one should do this instead to get successive values in the loop:
for ($i = 0; $i < $count; $i++) {
echo $i;
}
I have the following PHP code:
echo "var s1 = [";
$count = 0;
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
if ($count++ > 0) echo ", ";
echo $row['OrdersBal'];
}
echo "];\n";
echo "var ticks = [";
$count2 = 0;
while($row2 = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
if ($count2++ > 0) echo ", ";
echo "'" . $row2['CardName'] . "'";
}
echo "];\n";
It's currently outputting:
var s1 = [37966.550000, 19876.170000, 17314.580000, 15614.410000, 7575.000000];
var ticks = [];
But I want it to output:
var s1 = [37966.550000, 19876.170000, 17314.580000, 15614.410000, 7575.000000];
var ticks = ['Parameter Technology', 'Earthshaker Corporation', 'Microchips', 'Mashina Corporation', 'SG Electronics'];
If I move the second while statement so that it occurs first then that statement will output correctly. This has lead me to believe that I can't execute two while statements in a row in this fashion, but I'm not sure what my alternatives are. Thanks for any help!
Use variables to store text during loop and then print them out:
$count = 0;
$orders = "";
$cardNames = "";
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
if ($count++ > 0)
{
$orders .= ", ";
$cardNames .= ", ";
}
$orders .= $row['OrdersBal'];
$cardNames .= $row['CardName'];
}
echo "var s1 = [" . $orders . "];\n";
echo "var ticks = [" . $cardNames . "];\n";
I am making a login page that checks for matching values in a database if the SELECT query returns a matching row with username and password then it will return a row count of 1. The way I have it coded right now when I echo the variable that stores the row count it will echo 26 for some reason and I'm not to sure why.
Would someone explain if I am doing something wrong or if this is normal behavior and where that value is coming from?
function checkLogin($conn,$myusername,$mypassword,$row,$row1){
try {
$sql = "SELECT COUNT(*) FROM CLL_users WHERE user_name = 'user' AND password = 'XXXX'";
if ($results = $conn->query($sql)) {
if($results->fetchColumn() > 0) {
$sql = "SELECT * FROM CLL_users WHERE user_name = 'user' AND password = 'XXXXX'";
foreach ($conn->query($sql) as $row)
{
$rowCount = count($row);
echo $rowCount;
print ("Username: " . $row['user_name'] . "<br>");
print ("Username: " . $row['password'] . "<br>");
}
echo $count;
}
else {
print "NO ROWS";
}
}
} catch (PDOException $e){
echo 'Connection failed: ' . $e->getMessage();
}
}
Your code, $rowCount = count($row);, is counting the columns in the current row - not the number of rows returned by the query.
On the same note, you are echoing a second count related variable, $count, but you neither declare-it nor increment it in your code. It looks like this one is the one that's supposed to be counting the number of rows you loop through. If this is true, you should set it as $count = 0; before the loop and use $count++; within it:
$count = 0;
foreach ($conn->query($sql) as $row) {
print ("Username: " . $row['user_name'] . "<br>");
print ("Username: " . $row['password'] . "<br>");
$count++;
}
echo $count;
Also, you're currently using PDO's rowCount prior to selecting a user, and you're using it properly. You could just store that result into a variable and use it to tell how many rows you are receiving:
$sql = "SELECT COUNT(*) FROM CLL_users WHERE user_name = 'user' AND password = 'XXXX'";
if ($results = $conn->query($sql)) {
$numRows = $results->fetchColumn();
if($numRows > 0) {
... rest of your code ....
function checkLogin($conn,$myusername,$mypassword,$row,$row1)
{
try
{
$sql = "SELECT COUNT(*) FROM CLL_users WHERE user_name = 'user' AND password = 'XXXX'";
if ($results = $conn->query($sql))
{
$count = $results->fetchColumn();
echo "$count\n";
if($count > 0)
{
$sql = "SELECT * FROM CLL_users WHERE user_name = 'user' AND password = 'XXXXX'";
foreach ($conn->query($sql) as $row)
{
print ("Username: " . $row['user_name'] . "<br>");
print ("Username: " . $row['password'] . "<br>");
}
}
else
{
print "NO ROWS";
}
}
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
}