DO while based on query result - php

I got a block of the code written in PHP it uses a DB connection to an Oracle DB, i need to run a query on a data and the result for the first query it should be an input of the next query and this should be inside a loop, if i don't got any more result from the next query i should exit the loop, at the moment i am using and integer to loop through max 5 times as i know this the maximum possible results received, but this is dynamic.
My actual code what is working is the following:
this is the form when i input the data
<form name="identificare_cusut" action="test_hlkz.php" method="post">
Scanati piesa: <input type="text" name="piesa"><br>
<input type="submit" value="Cautare">
</form>
php code where i verify data and use function to execute query on DB while i am running a loop.
if (isset($_POST['piesa']) && strlen($_POST['piesa'])>0) {
$barcode = $_POST['piesa'];
}
if (isset($barcode)) {
echo "<tr>";
echo "<th>".$barcode."</th>";
echo "</tr>";
array_push($trasabilitate_array, $barcode);
$x=1;
do {
$arr=get_query_results_hlkz($barcode);
if ($arr) {
foreach ($arr as $row) {
echo "<tr>";
echo "<th>" .$row[0]. "</th>";
echo "</tr>";
$barcode=$row[0];
array_push($trasabilitate_array, $row[0]);
}
}
$x++;
} while ($x <=5);
}
i don't want to use a static solution like while ($x <=5)
Any idea how to fulfill this in a different way?

Should do the trick. So if the next $arr is empty it will exit the loop.
<?php
if (isset($_POST['piesa']) && strlen($_POST['piesa'])>0) {
$barcode = $_POST['piesa'];
}
if (isset($barcode)) {
echo "<tr>";
echo "<th>".$barcode."</th>";
echo "</tr>";
array_push($trasabilitate_array, $barcode);
$x=1;
do {
$arr=get_query_results_hlkz($barcode);
if ($arr != null) {
foreach ($arr as $row) {
if ($arr == null) {
$x = 6;
}
if($x < 6){
echo "<tr>";
echo "<th>" .$row[0]. "</th>";
echo "</tr>";
$barcode=$row[0];
array_push($trasabilitate_array, $row[0]);
}
}
$x++;
}
} while ($x <=5);
}
?>

Related

a PHP table map

I want to create a game where I have to create a map with PHP. I want to create 100 tables boxes in the right way but I can't get it work...
$field = 100;
echo "<table border='3px' dir='ltr'>";
for ($row=0; $row < 10 ; $row++) {
echo "<tr>";
for ($column=0; $column < 10; $column++) {
echo "<td>";
echo $field;
$field--;
echo "</td>";
}
echo "</tr>";
}
echo "</table>";
?>
This gives me this table:
But I will need a table like:
If a for loop is not a requirement.
I would use an array, then you have a set to work from rather then calculating things, then you just need reverse the odd row, like so:
$rows = array_reverse(array_chunk(range(1, 100), 10));
echo "<table>\n";
foreach ($rows as $level => $row) {
if (($level-1) % 2) {
$row = array_reverse($row);
}
echo "\t<tr>\n";
foreach ($row as $value) {
echo "\t\t<td>$value</td>\n";
}
echo "\t</tr>\n";
}
echo "<table>\n";
https://3v4l.org/204eh

apply css to specific element in array

I am fetching data of employees from mysql database into array and displaying in table.
everything is working but i want to apply a condition in array that
If salary is greater then 30,000 then change its color to red .
Tried
$q = "select name, salary from array";
$res = mysqli_query($link, $q);
$arr = array();
while ($data = mysqli_fetch_assoc($res)) {
$arr[] = $data;
}
echo '<table class="table table-hover">
<th>Name</th><th>Salary</th>';
$keys = array_keys($arr);
foreach ($keys as $key => $value) {
echo "$value , ";
}
for ($i=0; $i < count($arr); $i++) {
echo '<tr>';
foreach ($arr[$keys[$i]] as $key => $value) {
if ($arr[$keys[$i]['salary']] > 34000) {
echo "<td style='color: red; background-color:pink;'> $key=>$value </td>";
}else{
echo "<td> $key=>$value </td>";
}
}
echo "</tr>";
}
echo '</table>';
this is how my table looks
i want to change color of salary if it is greater than 30,000...
Change
if ($arr[$keys[$i]['salary']] > 34000) {
to
if ($value > 30000) {
I think you just got a little lost when processing an array which contains another arrays. A simple foreach loop is the simplest way of dealing with this.
echo '<table class="table table-hover"><th>Name</th><th>Salary</th>';
foreach ($arr as $row) {
echo '<tr>';
// using a ternary operator here rather than an IF
$style = $row['salary'] > 30000
? ' style="color:red;background-color:pink;"'
: '';
echo "<td>{$row['name']}</td>";
echo "<td $style>{$row['salary']}</td>";
echo '</tr>';
}

Add links to data in HTML table Created using PHP and a MYSQL database

I am trying to pull data from a table in PHPmyadmin and convert it to an HTML table based on some customer form input which filters out unneeded rows. The code below does that fine. The issue is that two of my columns need to contain links.
It would be easy enough to use PHP to change the table data into the link using a strtolower() and str_replace() to remove spaces, then concatinating the "www.website.com/" and the ".html". But I'm using a foreach loop to get all of the rows that I need and I don't know how to only alter one value per row.
I have tried using "Broswer Display Transformations" and "Input Transformations" in PHPmyadmin, but that only seems to affect the data in PHPmyadmin and not when I access the data via PHP.
My current code:
//* Code for Table
$query = "SELECT $searchFields FROM `hose_reels` $searchPhrase ORDER BY `model` ASC";
$result = mysqli_query($cxn,$query);
if ($row[$key] != "0") {
echo '<table width="100%" border="1" class="table"><tr>';
$row = $result->fetch_assoc();
foreach ($row AS $key => $value) {
$key = ucwords(str_replace('_', ' ', $key));
echo "<th>" . $key . "</th>";
}
echo "</tr>";
$result2 = mysqli_query($cxn,$query);
while($row = $result2->fetch_assoc()) {
echo "<tr>";
foreach ($row AS $key => $value) {
$row['$key'] = $value;
echo "<td>$row[$key]</td>";
}
echo "</tr>";
}
echo "</table>";
}
else {
echo "<p>No results match your selection. Please broaden your search.</p>";
}
Just add <a> tag in your php code. Below is the code. One more thing you have error in echo "<td>$row[$key]</td>"; line . it prints <td>$row[$key]</td> not the result you are fetching from DB.
echo '<table width="100%" border="1" class="table"><tr>';
$row = $result->fetch_assoc();
$i = 1;
foreach ($row AS $key => $value) {
$key = ucwords(str_replace('_', ' ', $key));
if($i == 1 || $i ==3){
echo "<th><a href='".key ."'" . $key . "</a></th>";
}else{
echo "<th>" . $key . "</th>";
}
$i++;
}
echo "</tr>";
$result2 = mysqli_query($cxn,$query);
$j =1;
while($row = $result2->fetch_assoc()) {
echo "<tr>";
foreach ($row AS $key => $value) {
$row['$key'] = $value;
if($i == 1 || $i ==3){
echo "<td><a href='".$row[$key]."'".$row[$key]."</a></td>";
}else{
echo "<td>$row[$key]</td>";
}
}
echo "</tr>";
}
echo "</table>";

creating html table from data pulled from database using PHP

I am working on a project to pull data from a sql database via PHP and create an HTML table from it. It is part of a form I am creating and the table will be a listing of what I am selling, costs, weights, etc. Anyway, I need to do this with PHP. So far I have the following in this section of my code to make this table:
<?php
$db=mysqli_connect(null,null,null,'weblab')
or die("Can't connect to DB: " .
mysqli_connect_error());
$query="SELECT fruit_item_no, fruit_name, fruit_price, fruit_weight FROM fruit_$
$result=mysqli_query($db, $query);
if (!$result) {
print "Error - The query could not be executed!" .
mysqli_error();
}
print "<table class = 'main'><caption> <h2> Fruit Purchasing Form </h2> </c$
print "<tr align = 'center'>";
$num_rows=mysqli_num_rows($result);
if ($num_rows > 0) {
$row=mysqli_fetch_assoc($result);
$num_fields=mysqli_num_fields($result);
$keys=array_keys($row);
for ($index = 0; $index < $num_fields; $index++)
print "<th class='a'>" . $keys[$index] . "</th>";
print "</tr>";
for ($row_num = 0; $row_num < $num_rows; $row_num++) {
print "<tr>";
$values = array_values($row);
for ($index = 0; $index < $num_fields; $row_num++) {
$value=htmlspecialchars($values[$index]);
print "<td class = 'b'>" . $value . "</td>";
}
print "</tr>";
$row=mysqli_fetch_assoc($result);
}
}
else {
print "There were no such rows in the table <br />";
}
print "</table>";
?>
The problem I am running into is when I attempt the view the entire page in Chrome, all I see is:
I think the error is somewhere around this section of code:
for ($row_num = 0; $row_num < $num_rows; $row_num++) {
print "<tr>";
$values = array_values($row);
for ($index = 0; $index < $num_fields; $row_num++) {
$value=htmlspecialchars($values[$index]);
print "<td class = 'b'>" . $value . "</td>";
If anyone can give me a little direction on what I might be missing, I would greatly appreciate it. I have been researching a while now and no clear fix has come up that i can see.
UPDATE:
Thought it would be best to just update my post instead of new question or comment somewhere. Thanks to all your suggestions I was able to correct my code to properly display my table and worked out all validation errors. I apologize for the code reading nightmare... I am still fairly new at this and I need to work more at it.
I did run into one issue I still cannot resolve though. I am trying to add an input box on the end of each row in the table I created. Problem is no matter what I try the boxes stay in a line above the table (pretty much at the top of the browser screen.
I placed this line in the sql query block to try to get the input box:
echo ("<input name='item[]' type='text' .=''/>");
and I also tried:
echo ("<input type='text' name ='item'/>");
Both did the same thing in giving me the line of boxes along the top. Any direction you could provide in getting these to be at the end of each row? I do not need it to put data back in the database or add to a table there. I just am trying to get input fields that will allow input that will submit with my form.
You can simplify the code by running and while loop on the result and iterating through the rows. And then using foreach loops since each row is an array of key value pairs. On the first iteration you could print the header.
$num_rows=mysqli_num_rows($result);
if ($num_rows > 0) {
$i = 0;
// loop through each row in the result
while ($row=mysqli_fetch_assoc($result)) {
// if first then print the header
if ($i == 0) {
print "<tr>";
foreach ($row as $field => $value) {
print "<th class='a'>".$field."</th>";
}
print "</tr>";
}
// print the row
print "<tr>";
foreach ($row as $value) {
print "<td class='b'>".$value."</td>";
}
print "</tr>";
$i++;
}
}
else {
print "<tr></td>There were no such rows in the table</td></tr>";
}
As suggested in the comments it would be a good idea to separate your view from your code.
In your second for loop, you have this:
for($index=0; $index<$num_fields; $row_num++)
Well, the value of $index will remain 0 throughput your execution. Try changing it to
for($index=0; $index<$num_fields; $index++)
{
$row_num++;
//rest of code
}
Hope it helps.
This is unnecessarily complicated:
$row=mysqli_fetch_assoc($result);
$num_fields=mysqli_num_fields($result);
$keys=array_keys($row);
for ($index = 0; $index < $num_fields; $index++)
print "<th class='a'>" . $keys[$index] . "</th>";
print "</tr>";
for ($row_num = 0; $row_num < $num_rows; $row_num++) {
print "<tr>";
$values = array_values($row);
for ($index = 0; $index < $num_fields; $row_num++) {
$value=htmlspecialchars($values[$index]);
print "<td class = 'b'>" . $value . "</td>";
}
print "</tr>";
$row=mysqli_fetch_assoc($result);
}
Something like this would be easier to read and should solve your problem, which was caused by incrementing the wrong index on one of the for loops:
$headers = false;
while($row=mysqli_fetch_assoc($result)) {
if (!$headers) {
echo "<thead><tr>";
foreach($row as $k=>$v) {
echo "<th>$k</th>";
}
echo "</tr></thead>";
$headers = true;
}
echo "<tr>";
foreach ($row as $k=>$v) {
$v=htmlspecialchars($v);
print "<td class='b'>$v</td>";
}
echo "</tr>";
}
But I would strongly recommend a) using a database abstraction layer like PDO, and b) separating your logic from your presentation. Debugging problems with HTML is made 100 times harder when it's jumbled all together with your PHP like this.

Number_format specific item in foreach php

Thanks for directing the link about the mySql API, i think there is a need to change to mySQLi or PDO. I have post the near-complete code below of same case, as my first time, could you please help what's error below, as it doesn't show the results as expected as the code using mysql_... please help. (assuming the select statement is correct please.)
<?php
$Ticker = htmlspecialchars($_GET["Ticker"]);
$StartDate = htmlspecialchars($_GET["StartDate"]);
$EndDate = htmlspecialchars($_GET["EndDate"]);
echo "<td>testing.</td>";
echo "</table>";
$pdo = new PDO('mysql:host=;dbname=, ,);
$statement = $pdo->query("Select Ticker, xxx as 'Last Update',Price, xxx as TTlUndetAmt,
FROM trade
WHERE Ticker = '$Ticker' and DATE(xxx) between '$StartDate' and '$EndDate'
GROUP BY Ticker, date
ORDER BY Ticker ASC, Date(ReleaseDT) DESC");
$row = $statement->fetch(PDO::FETCH_ASSOC);
//echo htmlentities($row['_message']);
echo "<table>";
while ($row = mysql_fetch_assoc($sql_result)) {
echo "<tr><td>";
foreach ($row as $value) {
if ($value === end($row)) {
echo number_format($value);
} else
{
echo $value . ",";
}
}
echo " </td></tr> " . "\n";
$i++;
}
?>
I got the results from select statement from mysql database. I use php to get the required data. I want specify the format only a specific item of each row to be numeric, i.e. (thousand separated). How could I do so? can below code do so?
Current output:
ticker1,2014-09-03 ,1.190,0,37247000
ticker2,2014-09-03 ,1.180,0,23246000
ticker3,2014-09-03 ,1.170,0,19188000
Expected Output:
ticker1,2014-09-03 ,1.190,0,37,247,000
ticker2,2014-09-03 ,1.180,0,23,246,000
ticker3,2014-09-03 ,1.170,0,19,188,000
The code I am using:
while ($row = mysql_fetch_assoc($sql_result)) {
echo "<tr><td>";
foreach ($row as $value) {
echo $value . ",";
if ($value === $row[5]) {
echo number_format($value);
}
}
echo " </td></tr> " . "\n";
$i++;
}
echo "</table>";
I found out that the above code will create duplicate role at the last row [5].
To my limited knowledge, I changed to
while ($row = mysql_fetch_assoc($sql_result)) {
echo "<tr><td>";
foreach ($row as $value) {
if ($value === end($row)) {
echo number_format($value);
} else
{
echo $value . ",";
}
}
echo " </td></tr> " . "\n";
$i++;
}
I would incorporate the key. That way, you can just check for the field name:
while ($row = mysql_fetch_assoc($sql_result)) {
echo "<tr><td>";
foreach ($row as $key => $value) {
echo $value . ",";
if ($key === 'YourFieldName') {
echo number_format($value);
}
}
echo " </td></tr> " . "\n";
$i++;
}
echo "</table>";
The function mysql_fetch_assoc already returns a key/value array, so you don't need anything there. Note though, that mysql_fetch_assoc is part of an old and deprecated API. If you like, have a look at: Choosing a MySQL API.
I would bring in the names, and use a $key=>$val in your foreach as such:
foreach ($row as $key=>$value)
{
echo $value . ",";
if ($key == "theRightColumn") // guessing the column name
{
echo number_format($val);
}
else
{
echo $val;
}
}
You have to change the modification in this line
foreach ($row as $value) {
to
foreach ($row AS $key => $value) {

Categories