PHP While HTML Table - php

I am trying to get my code to display in an HTML table using the while loop. However, I can't get my table to display. Is there something wrong with the way I am trying to echo the table out?
<?php
#-----call includes-----# include('E:/includes/database.php');
include('E:/includes/sendmail.php');
ini_set('error_reporting', E_ALL ^ E_NOTICE);
ini_set('display_errors','on');
$do = $_REQUEST['do'];
$queryOrders = "select t2.SlpName As 'Seller', t1.SWW As 'Vendor', t0.DocDate As 'Date',t0.DocTotal As 'Total'
from twh.dbo.OINV t0
inner join twh.dbo.inv1 t1 on t0.DocEntry = t1.DocEntry
inner join twh.dbo.OSLP t2 on t1.SlpCode = t2.SlpCode
where t0.DocDate > DATEADD (month, -2, getdate())
order by t0.DocTotal desc";
$resultItemData = sqlsrv_query($con, $queryOrders);
echo "<table border=\"1\" align=\"center\">";
echo "<tr><th>Seller</th>";
echo "<th>Vendor</th>";
echo "<th>Date</th>";
echo "<th>Total</th></tr>"
while($rowItemData = sqlsrv_fetch_array($resultItemData)){
echo "<tr><td>";
echo "$resultItemData";
echo "</td></tr>";
endwhile;
}
echo"</table>";

Modified a little bit. Check this:
while($rowItemData = sqlsrv_fetch_array($resultItemData)) :
echo "<tr><td>";
echo $rowItemData[ColumnValue]; //In your code, didn't access the column value earlier
echo "</td></tr>";
endwhile;

There's a combination of problems at play:
First, you open the while with {, but close with endwhile; - while technically not a problem, it's not consistent - if you open with {, it's best practice to close with }.
Second, you're attempting to echo an entire array, which won't work properly.
Third, no need to put the value inside of quotes: echo "$resultItemData"; could simply be echo $resultItemData.
Fourth, you're attempting to echo $resultItemData, which is a resource, not the row data. You want to echo $rowItemData values.
And finally, you'll likely want the results in an associative array, rather than a numerically-indexed array, so you might consider using sqlsrv_fetch_array( $resultItemData, SQLSRV_FETCH_ASSOC).
Below is your code, revised to work, and follow a bit better practices:
// columns: 'Seller',Vendor, 'Date', 'Total'
while( $rowItemData = sqlsrv_fetch_array( $resultItemData, SQLSRV_FETCH_ASSOC ) ) {
echo "<tr><td>";
echo "<td>$rowItemData['Seller']</td>";
echo "<td>$rowItemData['Vendor']</td>";
echo "<td>$rowItemData['Date']</td>";
echo "<td>$rowItemData['Total']</td>";
echo "</tr>";
}

You should specify the indexes of the array $rowitemdata.
For example:
echo"<tr><td>".$rowitemdata['Vendor']."

I haven't gone through your full code, but I can see wrong syntax for while
while($rowItemData = sqlsrv_fetch_array($resultItemData)){
echo "<tr>";
echo "<td>".$resultItemData['Seller']."</td>";
echo "<td>".$resultItemData['Vendor']."</td>";
echo "<td>".$resultItemData['Date']."</td>";
echo "<td>".$resultItemData['Total']."</td>";
echo "</tr>";
}
or
while($rowItemData = sqlsrv_fetch_array($resultItemData)) :
echo "<tr>";
echo "<td>".$resultItemData['Seller']."</td>";
echo "<td>".$resultItemData['Vendor']."</td>";
echo "<td>".$resultItemData['Date']."</td>";
echo "<td>".$resultItemData['Total']."</td>";
echo "</tr>";
endwhile;
Update:
still you can optimize the code, I just gave sample working

Let's assume your query actually produces a result, because you don't check that it does:
$resultItemData = sqlsrv_query($con, $queryOrders);
$header = <<<HEREDOC
<table border="1" align="center">
<tr>
<th>Seller</th>
<th>Vendor</th>
<th>Date</th>
<th>Total</th>
</tr>
HEREDOC;
echo $header;
while($rowItemData = sqlsrv_fetch_array($resultItemData)) {
echo "<tr>
<td>{$rowItemData['Seller']}</td>
<td>{$rowItemData['Vendor']}</td>
<td>{$rowItemData['Date']}</td>
<td>{$rowItemData['Total']}</td>
</tr>";
}
echo '</table>';
To actually check that the query works, you might want to do this instead. This is just to debug/illustrate error checking for the query execution. You wouldn't want to output an error to the screen, but rather log it. You probably want to just output the table header/footer and skip the while/loop entirely.
$resultItemData = sqlsrv_query($con, $queryOrders);
if (resultItemData === false) {
die(print_r(sqlsrv_errors(), true));
}

Related

How could you use PHP and a SQL database to change HTML <h> content?

I have a webpage that displays cars from the first car in the table to the last car with a while loop.
I have the following columns: Make, Model, Price. In my syntax I have an anchor tag around the Make rows that links to the description page of the Make you click on.
I want my <h> tags to change to the Model of the corresponding Make.
I've spent over an hour trying to achieve this but all I could come up with is this:
<?php
$query = "SELECT Model FROM inventory;";
$Vtitle = $conn->query($query);
$Vtitle_ar = mysqli_fetch_assoc($Vtitle);
echo "<h1>".$Vtitle_ar['Model']."</h1>";
?>
This works to an extent.
Every anchor I click replaces the <h> tags with only the first result under the Model column in my database.
Here is my code for the the entire car inventory page
<?php
$query = "SELECT * FROM inventory;";
/* Try to query the database */
if ($result = $conn->query($query)) {
// Don't do anything if successful.
}
else {
echo "Error getting cars from database:" .$conn->error()."<br>";
}
// Create the table headers
echo "<table id='Grid' style='width: 80%'><tr>";
echo "<th style='width: 50px'>Make</th>";
echo "<th style='width: 50px'>Model</th>";
echo "<th style='width: 50px'>Asking Price</th>";
echo "</tr>\n";
$class = "odd"; // keep track of whether a row was even or odd, so we can style it later
// Loop through all the rows returned by the query, creating a table for each row
while ($result_ar = mysqli_fetch_assoc($result)) {
echo "<tr class=\"$class\">";
echo "<td><a href='viewcar.php?VIN=".$result_ar['VIN']."'>".$result_ar['Make']."<a></td>";
echo "<td>".$result_ar['Model']."</td>";
echo "<td>".$result_ar['ASKING_PRICE']."</td>";
echo "</td></tr>\n";
// if the last row was even, make the next one odd and vice-versa
if ($class=="odd") {
$class = "even";
}
else {
$class = "odd";
}
}
echo "</table>";
$conn->close();
?>
Does anyone how I can do this?
I'm new to programming and I'm trying to use this for an actual project I'm working on for a hair salon's website
Add a WHERE clause to the query.
$vin = $_GET['VIN'];
$stmt = $conn->prepare("SELECT Model FROM inventory WHERE VIN = ?");
$stmt->bind_param("s", $vin);
$stmt->execute();
$stmt->bind_result($model);
$stmt->fetch();
echo "<h1>$model</h1>";
Though not a solution resolved with the use of a where clause as given by #Barmar whilst formatting the code I did find an error within the HTML which was not immediately obvious
The line echo "</td></tr>\n"; has an extra </td> which would break the flow of the html and can have detrimental effects. Also, // Don't do anything if successful. makes no sense - if there are results then process the recordset otherwise show the error ;-)
<?php
$query = "SELECT * FROM inventory;";
if ( $result = $conn->query( $query ) ) {
echo "
<table id='Grid' style='width: 80%'>
<tr>
<th style='width: 50px'>Make</th>
<th style='width: 50px'>Model</th>
<th style='width: 50px'>Asking Price</th>
</tr>";
$i=0;
while( $result_ar = mysqli_fetch_assoc( $result ) ) {
$class = $i %2 == 0 ? 'even' : 'odd';
echo "
<tr class='$class'>
<td><a href='viewcar.php?VIN={$result_ar['VIN']}'>{$result_ar['Make']}<a></td>
<td>{$result_ar['Model']}</td>
<td>{$result_ar['ASKING_PRICE']}</td>
</tr>";
$i++;
}
echo "</table>";
} else {
echo "Error getting cars from database:" .$conn->error()."<br>";
}
$conn->close();
?>
For styling alternate table rows ( the above uses a modulus function to calculate odd/even ) you can do it with some simple CSS - such as
tr:nth-child( odd ){/* rules */}

Displaying 2 records in a column using php

So I have a code
<?php
$showorder = "SELECT order_number FROM orders WHERE customer_number=522";
$orderesult = mysqli_query($con, $showorder);
$ord = mysqli_fetch_array($orderesult);
?>
in my database customer number 522 has 2 order numbers, when i tried to show the result, it only shows 1.
Here's my other code
echo "<table>";
echo "<th>Order Number</th><th>Order date</th>";
echo "<tr><td>";
echo $ord["order_number"];
echo "</td><td>";
echo $ord["order_date"];
echo "</td></tr>";
You just need to use while() here for getting all records, something like:
while($ord = mysqli_fetch_array($orderesult)){
//echo all value here
}
Also note that, if you want to print $ord["order_date"] than you must need to select column also in your query.
Otherwise, $ord will only contain order_number value.
Your SQL is missing the extra column.
Current SQL:
SELECT order_number FROM orders WHERE customer_number=522
Change to:
SELECT order_number, order_date FROM orders WHERE customer_number=522
Put mysqli_fetch_array($orderesult); in a while loop.
while($ord = mysqli_fetch_array($orderesult)) {
echo $ord["order_number"];
# code
}
Replace your code with the below code and then try again
<?php
$showorder = "SELECT order_number, order_date FROM orders WHERE customer_number=522";
$orderesult = mysqli_query($con, $showorder);
echo "<table>";
echo "<tr>";
echo "<th>Order Number</th><th>Order date</th>";
echo "</tr>";
while($ord = mysqli_fetch_array($orderesult)) {
echo "<tr>";
echo "<td>$ord['order_number']</td>";
echo "<td>$ord['order_date']</td>";
echo "</tr>";
}
echo "</table>";
?>
echo "<table>";
echo "<th>Order Number</th>";
while($ord = mysqli_fetch_array($orderesult)) {
echo "<tr><td>";
echo $ord["order_number"];
echo "</td></tr>";
}
you must use loop to show all result , and you can use echo one time .
while($ord = mysqli_fetch_array($orderesult)) {
echo "<table>
<th>Order Number</th><th>Order date</th>
<tr><td>".
$ord["order_number"]."
</td></tr>";
}

If database field is empty echo "nothing" if something there echo "something"

looking for a solution to this bit of coding below.
<?php
$nextfive_events = mysql_query("SELECT date_format(date, '%d/%m/%Y') AS formatted_date, title, location, regs FROM events WHERE status = 'ACTIVE'");
if(mysql_num_rows($nextfive_events) == 0) { echo "<p>No events coming up!"; } else {
echo "<table width=\"600\" border=\"0\" cellpadding=\"2\" cellspacing=\"2\" class=\"greywritinglight\" align=\"left\">
<tr align=\"center\">
<td>Date</td>
<td>Name</td>
<td>Location</td>
<td></td>
</tr>";
$x=1;
while($next_row = mysql_fetch_array($nextfive_events))
{
if($x%2): $rowbgcolor = "#FFFFFF"; else: $rowbgcolor = "#EEEEEE"; endif;
echo "<tr align=\"center\">";
echo "<td>" . $next_row['formatted_date'] . "</td>";
echo "<td>" . $next_row['title'] . "</td>";
echo "<td>" . $next_row['location'] . "</td>";
echo "<td>Regs</td>";
echo "</tr>";
$x++;
}
echo "</table>";
}
?>
I want the row echo "<td> <a href regs .....
To display the word Regs when there is something in 'regs' in the database. Say if there is nothing in that field I want it to be blank and not say Regs.
thanks
You could do Ternary operator:
echo "<td><a href='" . (empty($next_row['regs']) ? "#" : $next_row['regs']) . "'>Regs</a></td>";
Try not to do escape characters, they look confusing, do single quote for href attribute. Also, Did you want
<a href='#'>Regs</a>
to show if it was blank?
If Not, try this:
echo (!empty($next_row['regs']) ? "<td><a href='" . $next_row['regs'] . "'>Regs</a></td>" : "");
You could use a ternary:
echo ( ! empty($next_row['regs'])) ? '<td>Regs</td>' : '<td>&nspb;</td>';
First off, I'd like to show you a really handy trick with PHP that allows you to echo out into HTML without actually saying echo. Just create a break in your PHP code, and in between anything you put will be echoed as HTML.
As for the number of rows returned, you are doing it correctly. Make sure that you are querying properly, that you have an established connection, and that there are no logical errors in your SQL.
Sorry, didn't notice you wanted to check if the column was empty! Just use the function empty(). This function will return true when the data you give it is empty, so simply give it the column from the row of data you wish to check.
<?php
// Lets say this is your database connection variable
$connection = mysqli_connect(//Your info goes here);
// This is the query you want to run
$query = "SELECT something FROM somewhere WHERE something='$something_else'";
// This is where you are storing your results of the query
$data = mysqli_query($connection, $query);
// Here, you can ask for how many rows were returned
// In PHP, ZERO is evaluated to false. We can use a
// Short-hand boolean expression like this
if (mysqli_num_rows($data))
{
// Because zero evaluates to false, we know
// that if we get HERE that there ARE rows
// We can break out of PHP and into our HTML
// by simply ending our PHP tag! Just remember
// that you need to open it back up again though!
?>
<!--You can put your HTML here-->
<p>
We found some rows that you might
need to know about!
</p>
<?php
}
else
{
// But, if we get here, we know it evaluated as
// FALSE and therefore no rows returned
// Here's that HTML trick again
?>
<!--HTML can go here-->
<p>
No rows returned!
</p>
<?php
}
?>

do while in do while in php

That loop using do while, and it is working fine but when I add another do while in to this the second do while work but first do while only show one row not all 10 row. My code is below
<?php do { ?>
<tr>
<td><?php echo $row_Recordset1['date']; ?></td>
<?php do { ?>
<td><?php echo $row_Recordset1['nav']; ?></td>
<?php } while ($row_Recordset1= mysql_fetch_assoc($Recordset1)); ?>
</tr>
<?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
My date should be displayed once in a row but all the other td will be took from nav;
This is what I want:
------------------------
|2014-02-26|5.5|3.2|3.5|
------------------------
|2014-02-25|3.1|1.2|1.5|
But I'm currently getting:
------------------------
|2014-02-26|5.5|3.2|3.5|
------------------------
You should look at http://php.net/mysql_fetch_assoc
It moves the internal pointer one step ahead, so each time you do mysql_fetch_assoc() you get the next value, hence only your enternal do while is executed. That is, only date from the first row is output, and all other values are output in second do while;
Try this for exercise:
$q = mysql_query("SOME MYSQL QUERY WITH MINIMUM THREE ROWS");
$f = mysql_fetch_assoc($q);
$f = mysql_fetch_assoc($q);
$f = mysql_fetch_assoc($q);
print_r($f);
First of all, please don't bounce in and out of PHP like that...
<?php
do {
echo '<tr>
<td>';
echo $row_Recordset1['date'];
echo '</td>';
do {
echo '<td>';
echo $row_Recordset1['nav'];
echo '</td>';
} while ($row_Recordset1 = mysql_fetch_assoc($Recordset1));
echo '</tr>';
} while ($row_Recordset1 = mysql_fetch_assoc($Recordset1));
?>
Where do you fetch your first $row_Recordset1? Somewhere earlier than this code? You're going to output table cells (<td>) until you run out of rows. I don't think you want that.
Like so:
<?php do { ?>
<tr>
<td><?php echo $row_Recordset1['date']; ?></td>
<td><?php echo $row_Recordset1['nav']; ?></td>
</tr>
<?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
Because each time you use mysql_fetch_assoc it does the following
Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead.
Part of the reason this doesn't work is because you are re-assigning the value of the same variable. If you don't want to lose it then you cannot do it this way. At the very least it is a bad idea if you ever intend to do anything new with the code.
Next, I really recommend you populate an array with the data first before you ever do anything with outputting it. It is a very good idea to separate logic from output.
Your code should look more like this:
<?php
//Assumes you have already connected to a mysqli resource
$conditional_data_filtered = $mysqli->real_escape_string($conditional_data);
$sql = "SELECT date, nav FROM some_table WHERE some_column = '" . $conditional_data_filtered . "'";
if ($result = $mysqli->query($sql)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
$data = array(); //Make sure we start with a fresh array each time.
$data['date'] = $row['date'];
//Now I think you have a bunch of data in the nav you need to loop through
$nav_filtered = $mysqli->real_escape_string($row['nav']);
$subSql = "SELECT some_data FROM navigation WHERE some_identifier = '" . $nav_filtered . "'";
if ($subResult = $mysqli->query($subSql)) {
while ($subRow = $subResult->fetch_assoc()) {
$data['nav'][] = $subRow;
}
}
$rowList[] = $data;
}
/* free result set */
$result->free();
}
foreach ($rowList as $rowData) {
echo "<tr>";
echo "<td>" . $rowData['date'] . "</td>";
foreach ($rowData['nav'] as $navData) {
echo "<td>" . $navData['some_info'] . "</td>";
}
echo "</tr>";
}
?>
Just a note: If you really don't have sub-data and just want to output the next column then you don't need a sub-loop. You just need to echo the contents of the column like you did with the first one. Then you can get rid of the sub-loops I have shown above and just put it within the first loop.

How do I comment out php to add a HTML form within a php print?

Here is my code, works fine and prints out everything I want it to. But on the end of each cell I would like a form that makes a button which will allow the user to configure the item that the row in the table describes. I want to know how I can escape out of php to use html again, I've tried double quotes but this does not work, I was wondering if anyone could explain to me how to do this.
<?php
$data = mysql_query("SELECT * FROM basestation WHERE email_address ='$email'")
or die(mysql_error());
Print "<table border = 1>";
while( $info = mysql_fetch_array( $data ) ) {
Print "<tr>";
Print "<th>Name:</th> <td>".$info['base_station_id'] . "</td>";
Print "</tr>";
Print "<tr>";
Print "<th>Serial Number:</th> <td>".$info['serial_no'] . "</td> ";
Print "</tr>";
}
Print "</table>";
?>
PHP code will only being executed between the opening <?php and the closing ?> php tags. However you are free to use multiple php sections per file.
So, you can just close the PHP section using ?> . Then after writing HTML content you can open <?php again.
Here comes a little example. It creates a couple of <a> achors from an imaginal array $links:
<?php
foreach($links as $link) { ?>
<?php echo $link['title'];?>
<?php }
Note that this mostly leads to unreadable code. But it is possible and can be used.
Also not that there is short syntax available for shorter echo syntax. But you'll have to make sure that it is enabled in your php configuration. Using the shorter syntax, may example from above could look like this:
foreach($links as $link) { ?>
<?=$link['title'];?>
<? }
You'll find a good documentation on the PHP website
You are already using the PHP delimiters <?php and ?>. Use these to switch back to HTML within the document also.
<?php
function foo(bar) {
return bar == 1 ? 'bar' : 'nobar';
}
?>
<h1>Heading with just HTML</h1>
<div class="<?php print foo(1); ?>">This is a div with a dynamic class.</div>
<?php
// and php again
?>
Just make a link to a page with the id in the url
Print "<tr>";
Print "<th>Edit:</th><td>Edit</td> ";
Print "</tr>";
Then on edit.php you can get the id ($_GET['id']) and query the database.
<?php
$data = mysql_query("SELECT * FROM basestation WHERE email_address ='$email'")
or die(mysql_error());
Print "<table border = 1>";
while( $info = mysql_fetch_array( $data ) ) {
Print "<tr>";
Print "<th>Name:</th> <td>".$info['base_station_id'] . "</td>";
Print "</tr>";
Print "<tr>";
Print "<th>Serial Number:</th> <td>".$info['serial_no'] . "</td> ";
?>
<-- form here --->
<?php
Print "</tr>";
}
Print "</table>";
?>

Categories