How to pass variable from a database query to a PHP function - php

get_population($row['ID']) is causing error Variable undefined:
foreach($filterList as $row)
{
echo '<tr>';
echo '<td>' . $row['county_ID'] . '</td>';
echo '<td>' . get_population($row['ID']) . '</td>';
echo '<td>' . $row['ID'] . '</td>';
echo '</tr>';
}
When I use a database value in the function parameter I get the error :Undefined variable:
It must be out of scope but I don't know how to get around it.
If I print $row['ID'] it shows the value of 1 for this example. If I hard code 1 as the parameter value it works. It is only when I try to pass $row['ID'] to the function that I get the error.
I am sure it is a simple answer but I am chasing my tail. Thanks

In your code there's a mismatch in ''.['ID'].'';
The correct is $row['ID']:
foreach($filterList as $row)
{
echo '<tr>';
echo '<td>' . $row['county_ID'] . '</td>';
echo '<td>' . get_population($row['ID']) . '</td>';
// error here
echo '<td>' . ['ID'] . '</td>';
// change with
echo '<td>' . $row['ID'] . '</td>';
echo '</tr>';
}

The code is correct, the problem was a null value in the database. Since there was no value to pass to the function it returned variable undefined.

Related

Replacing the Null output of a MySQL query with a "String" in a php table

From the research i conducted in SO, this is the only other question similar to what i need, but im afraid that i didnt help me (How to replace null results in sql query result table with a string?).
I have a table that prints the Medical History of a Patient, and the table cells are restored from a database.
A portion of the code is down below:
echo "<tr>";
echo "<th>MRI Onset Localisation</th>";
echo "<th>CNS MRI Lesions Y/N </th>";
echo "<th>CNS MRI Lesions No.</th>";
echo "<th>CNS MRI Location</th>";
echo "<th>Person Signing the form</th>";
echo "<th>Documented at</th>";
echo "</tr>";
echo "<tr>";
echo "<td>" . $row['Onsetlocalisation'] . "</td>";
echo "<td class='tdclass exempt'>" . $row['smoker'] . '<br>' . $row['cigars'] . '<br>' . $row['cigardate'] . "</td>";
echo "<td>" . $row['onsetsymptoms'] . "</td>";
echo "<td class='tdclass exempt'>" . $row['MRIonsetlocalisation'] . "</td>";
echo "<td>" . $row['MRIenhancing'] . "</td>";
echo "<td class='tdclass exempt'>" . $row['MRInum'] . "</td>";
echo "<td>" . $row['MRIenhancinglocation'] . "</td>";
echo "<td class='tdclass exempt'>" . $row['signer'] . "</td>";
echo "<td>" . $row['reg_date'] . "</td>";
echo "</tr>";
And the MySQL Query that returns those fields is
$sql = "SELECT * FROM tblName WHERE somefield = $somevar";
The thing is... Some of those fields are allowed to have NULL as a value, but for the front end of the app, i want the table cells that contain NULL values to print a standard string such as "N/A" or "Empty" but i need it to be done inside of the php table portion of my code, or so i think...
I found numerous questions about replacing NULL with a string inside of the MySQL query, but i don't care about that since the query doesn't appear at the end user outside of the table.
I tried to implement the coalescing operator in the following way, but no nothing was displayed:
echo "<td class='tdclass exempt'>" . $row['MRInum'] ?? "N/A" . "</td>";
Any help is absolutely welcome.
You need to put the expression in brackets to make it clear which parts are supposed to be evaluated by the null coalescing operator:
echo "<td class='tdclass exempt'>" . ($row['MRInum'] ?? "N/A") . "</td>";
If you don't, it thinks the "<td class='tdclass exempt'>" is part of the text to be checked for existence - which means it always returns true because that hard-coded text always exists.
You can do this in two ways.
From SQL:
COALESCE(fieldName, 'N/A') AS fieldName
will replace NULLs with, you guessed it, 'N/A'.
Otherwise, when you fetch the row,
$row = $stmt->fetch(PDO::FETCH_OBJECT);
you can vet it:
$replacements = [
'MRI_Data' => 'N/A',
'MRI_Type' => [
'001' => 'Single Scan',
'002' => 'Multi Scan',
'003' => 'Pulsed',
'(null)' => 'N/A',
],
];
foreach ($row as $key => $value) {
if (array_key_exists($key, $replacements)) {
if (is_array($replacement[$key])) {
if (empty($value)) {
$value = '(null)';
}
if (array_key_exists($value, $replacement[$key])) {
$row[$key] = $replacement[$key][$value];
}
} else {
if (empty($value)) {
$row[$key] = $replacement[$key];
}
}
}
}

Get data from form using PHP

I have a php file that creates a table for me using data fetched from a mysql database.
<?php
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row['ID'] . "</td>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['CountryCode'] . "</td>";
echo "<td>" . $row['District'] . "</td>";
echo "<td>" . $row['Population'] . "</td>";
echo "<td>" . $row['Price'] . "</td>";
echo "<td><input type=\"number\" name="quantity" id="quantity"></td>";
echo "</tr>";
}
} else {
echo "0 results";
}
$conn->close();
?>
At the end of each row, I have an input number so that I can calculate the amount of each product(countries in this case). How could I get the amount of each country, multiply it by the price and return a total at the end of my table?
If you want to do it with PHP, you have to do it in two steps, because the PHP is processed in the server. So you would enter all the quantities you want and when you press the "Compute" button, the page would send all the values to the server who would compute everything you want and give you the final result.
A problem that I see with this solution is that once you have get all the quantities you want, you would have to get the prices once more. I don't its very efficient because you already have them on the first page. I see two solutions here :
When you display the values, keep track of the prices in a $_SESSION field, thus you will be able to access them after leaving the page, without having to get them from the database.
When you display the values, display the prices in an input field (I would recommend as readonly so that the user won't change this value here), and thus they would be included in the $_POST (or $_GET, if you use this) variable that your browser would send to the server.
If you're only interested to display the value, without using it after, you can use javascript to compute it, it might be easier.
Even though it's not the point here, you should be careful when displaying inputs via PHP on a while loop, because here all of your inputs have the same id, which would make thing harder to compute what you want to.
Hope it helps!
You must add a form tag around the table and then sum record price * qty on every row
What I did here is I checked if the quantity is set in the POST variable or not. if it exists I put data in quantity value. after that, you must make the name of quantity capable of taking array inside with the key of record Id.
after that, if the form submitted the quantity will send back to the page as a query string. then I multiply the price with quantity and add it to sum varaible. after finishing the loop and echo out the sum variable at the end of the table.
$html = '';
if ($result->num_rows > 0) {
$html .= '<form method="GET" action="" target="_self>';
$row = $result->fetch_assoc();
if(isset($_GET['quantity'][$row['ID']]))
$qty = $_GET['quantity'][$row['ID']];
else
$qty = 0;
$sum = 0;
// output data of each row
while ($row) {
$html .= '<tr>';
$html .= '<td>' . $row['ID'] . '</td>';
$html .= '<td>' . $row['Name'] . '</td>';
$html .= '<td>' . $row['CountryCode'] . '</td>';
$html .= '<td>' . $row['District'] . '</td>';
$html .= '<td>' . $row['Population'] . '</td>';
$html .= '<td>' . $row['Price'] . '</td>';
$html .= '<td>
<input type="number" name="quantity[' . $row['ID'] . ']" value="' . $qty . '">
</td>';
$html .= '<td>' . ($sum += $row['Price'] * $qty) . '</td>';
$html .= '</tr>';
}
$html .= '<input name="submitForm" value="submitForm">';
$html .= '</form>';
$html .= '<tr>';
$html .= '<td>Total = '.$sum.'</td>';
$html .= '</tr>';
} else {
$html .= "0 results";
}
$conn->close();
echo htmlspecialchars($html);
remember to use htmlspecialchars to echo out the result.

How to implement the template view pattern with a table?

At the moment I'm trying to understand the template view pattern using PHP.
I got a table that gets filled by a command (using command pattern). At the moment the array gets iterated and filled in a table using foreach. I want to split the program logic and the displaying of the table but I don't know where to declare the table and how to fill it.
I understood it generally. I'm able to display a single information.
Two questions:
How to implement it when I want to display a table from a database?
How to implement the content that should be displayed on all pages?
Unfortunately everything I found is about template engines that I don't want to use at the moment.
Here is the command combined with a table generator. I want to split that into a command that retrieves the data and a view that displays the table.
$domains = ConcreteDomainFactory::getAllDomains();
echo '<table class="domain-table">';
echo '<thead>';
echo '<tr>';
echo '<th>ID</th>';
echo '<th>Domain</th>';
echo '<th>Beschreibung</th>';
echo '<th>aktiviert</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
if((is_array($domains) ===true) && (count($domains) > 0)){
$line_number = 1;
foreach($domains as $domain){
echo '<tr>';
echo '<td>' . $domain->getPkDomainId() . '</td>';
echo '<td>' . $domain->getDomain() . '</td>';
echo '<td>' . $domain->getDescription() . '</td>';
echo '<td>';
if($domain->getActive()){
echo 'ja';
}
else{
echo 'nein';
}
echo '</td>';
echo '</tr>';
}
}
echo '</tbody>';
echo '</table>';`

PHP - Iterating through db result associative array

I was wondering if someone could help me. I want to iterate through an associative array and put the results into two combo boxes. The combo boxes will have the exact same data in each other.
while ($this->results = $this->dbhandle->fetch(PDO::Fetch_Assoc))
{
echo "<option value='" . $this->result['id] . "'>"
. $this->result['name'] . "</option>";
}
Do I have to run this loop twice for 2 seperate comboboxes or is there a more efficient way of doing this?
Your best bet in this situation is to just accumulate the text in a string and echo it out twice.
$options = "";
while ($this->results = $this->dbhandle->fetch(PDO::Fetch_Assoc))
{
$options.= "<option value='" . $this->result['id] . "'>"
. $this->result['name'] . "</option>";
}
echo "<select name='combo1'>".$options."</select>";
echo "<select name='combo2'>".$options."</select>";
How about something like this (raw code to give you an idea):
while
{
$combo_options .= "<option>" ....// rest of your code
}
Then print the variable inside your selects:
<select id="combo1"><?=$combo_options?></select>
<select id="combo2"><?=$combo_options?></select>
You can capture the output as a variable and then echo it as needed
while ($this->results = $this->dbhandle->fetch(PDO::FetchAssoc)){
$output .= "<option value='" . $this->result['id'] . "'>" . $this->result['name'] . "</option>";
}
/// later on in your script
print $output;

Why am I not able to set variables inside a foreach loop in PHP?

I'm trying to set variables inside a foreach() statement, but it keeps dying.
If I do this, all is fine.
foreach($array as $key => $value)
{
echo '<tr>';
echo '<td>' . $value['1'] . '</td>';
echo '</tr>';
}
But when I do this, it doesn't want to work.
foreach($array as $key => $value)
{
$mls = echo '' . $value['1'] . '';
echo '<tr>';
echo '<td>' $mls '</td>';
echo '</tr>';
}
Syntax wise, I don't see how there's a difference in these statements. I've also tried $mls = $value['1']; and that didn't want to work either.
Surely you got a syntax error complaining about the second case, right? If you say "it keeps dying", you should tell us exactly what happens when something dies. Even more, you should read the syntax error and consider what it says. The errors are descriptive so that you can figure out what's wrong.
In the second case, you aren't concatenating the strings with the . operator.
echo '<td>' $mls '</td>';
should be
echo '<td>' . $mls . '</td>';
$mls = echo '' . $value['1'] . '';
should be
$mls = $value['1'] ;
echo $mls;
and
echo '<td>' $mls '</td>'
should be
echo '<td>' . $mls . '</td>';
Your second code block should look more like this:
foreach($array as $key => $value)
{
$mls = (string) $value['1'];
echo '<tr>';
echo '<td>' , $mls , '</td>';
echo '</tr>';
}
When you type $var = echo "something" you aren't assigning any values to that variable. Instead you are outputting that string - echo has no return value.
You can typecast your variable into a string without appending and prepending empty strings.
You can use the , to echo multiple strings one after another with a little less overhead.
You should be using HTML entities for your ampersands, even though they are in an attribute's value
(Finally) You aren't actually concatenating your variable into the third echo.

Categories