How to put if condition inside php string properly - php

I have following code to print some data,
$html = "<table><tr><th>Email Address</th><th>Event</th><th>Tag</th><th>Time</th></tr>"
.if(count($result->http_response_body->items) > 0) {
foreach ($result->http_response_body->items as $key) {.
"<tr>
<td>". $key->recipient . "</td>
<td>". $key->event . "</td>
<td>" . #$key->tags[0] . "</td>
<td>" . date("r", $key->timestamp) . "</td>
</tr>"
.}
//fetchLogs($result);
}.
"</table>";
echo $html;
When I execute code it gives syntax error, unexpected 'if' condition. How to insert this if condition and other variables inside this table string. Please help.

you have a lot of syntax errors
$html = "<table><tr><th>Email Address</th><th>Event</th><th>Tag</th> <th>Time</th></tr>";
if ( count( $result->http_response_body->items ) > 0 ) {
foreach ( $result->http_response_body->items as $key ) {
$html .= "<tr>
<td>" . $key->recipient . "</td>
<td>" . $key->event . "</td>
<td>" . #$key->tags[ 0 ] . "</td>
<td>" . date( "r", $key->timestamp ) . "</td>
</tr>";
}
//fetchLogs($result);
}
$html .= "</table>";
echo $html;
also, dont supress errors (#$key->tags[0]). Do a proper check with isset first. Or if you are on php7 you can use the null coalesce operator like $key->tag[0] ?? 'something else'.

Firstly PHP statements close with ; that is semi-colon.
So, your first statement needs to be corrected as:
<?php
$html = "<table><tr><th>Email Address</th><th>Event</th><th>Tag</th><th>Time</th></tr>";
if (count($result->http_response_body->items) >0) { // Removed dot
foreach ($result->http_response_body->items as $key) { // Removed dot
$html .= "<tr><td>" .$key->recipient ."</td>
<td>" .$key->event ."</td>
<td>" .#$key->tags[0] ."</td>
<td>" .date("r", $key->timestamp) ."</td></tr>";
} // Removed Dot.
// fetchLogs($result);
}
$html .= "</table>";
echo $html;
?>

the trick is quite simple, you just have to understand string concatination, and once you've mastered that you can compose complex strings like this one.
$html = "<table><tr><th>Email Address</th><th>Event</th><th>Tag</th><th>Time</th></tr>";
if(count($result->http_response_body->items) > 0) {
foreach ($result->http_response_body->items as $key) {
$html."<tr>
<td>". $key->recipient . "</td>
<td>". $key->event . "</td>
<td>" . #$key->tags[0] . "</td>
<td>" . date("r", $key->timestamp) . "</td>
</tr>";
}
}
$html."</table>";
echo $html;

there are syntax errors in the code.You can use this
$html = "<table><tr><th>Email Address</th><th>Event</th><th>Tag</th> <th>Time</th></tr>";
if ( count( $result->http_response_body->items ) > 0 ) {
foreach ( $result->http_response_body->items as $key ) {
$html .= "<tr>
<td>" . $key->recipient . "</td>
<td>" . $key->event . "</td>
<td>" . #$key->tags[ 0 ] . "</td>
<td>" . date( "r", $key->timestamp ) . "</td>
</tr>";
}
}
$html .= "</table>";
echo $html;

RAther than using string concatenation which can have performance penalties with large strings my personal preference is to use an array into which items are added - implode at the end to output to screen.
<?php
$html=array();
$html[]="
<table>
<tr>
<th>Email Address</th>
<th>Event</th>
<th>Tag</th>
<th>Time</th>
</tr>";
if ( count( $result->http_response_body->items ) > 0 ) {
foreach ( $result->http_response_body->items as $key ) {
$html[]= "
<tr>
<td>{$key->recipient}</td>
<td>{$key->event}</td>
<td>{#$key->tags[ 0 ]}</td>
<td>" . date( "r", $key->timestamp ) . "</td>
</tr>";
}
}
$html[]= "</table>";
echo implode( PHP_EOL, $html);
unset( $html );
?>

Another way to do that :
<table>
<tr>
<th>Email Address</th>
<th>Event</th>
<th>Tag</th>
<th>Time</th>
</tr>
<?php if(count($result->http_response_body->items) > 0) : ?>
<?php foreach ($result->http_response_body->items as $key):?>
<tr>
<td><?php echo $key->recipient; ?></td>
<td><?php echo $key->event?; ?></td>
<td><?php echo #$key->tags[0]; ?></td>
<td><?php echo date("r", $key->timestamp); ?></td>
</tr>
<?php endforeach;?>
<?php endif;?>
</table>

Please try this
$html = "<table><tr><th>Email Address</th><th>Event</th><th>Tag</th><th>Time</th></tr>" ;
if(count($result->http_response_body->items) > 0) {
foreach ($result->http_response_body->items as $key) {
$html.= "<tr>
<td>". $key->recipient . "</td>
<td>". $key->event . "</td>
<td>" . #$key->tags[0] . "</td>
<td>" . date("r", $key->timestamp) . "</td>
</tr>";
}
//fetchLogs($result);
}
$html.="</table>";
echo $html;

Related

How can I check if all checkboxes have been checked in PHP?

I am implementing a list of items and each has a checkbox. I currently can see which checkboxes have been checked but what I want to do is check if all of them have been checked. How can I implement that?
Here is my code:
<form action="" method="post">
<?php
echo "<table>
<tr>
<th>Customer ID</th>
<th>Report ID</th>
<th>Report message</th>
<th>Device</th>
<th>Device no.</th>
<th>Barcode</th>
<th>IMEI</th>
<th>Sale-date</th>
</tr>";
while ($row2 = $clientUsername->fetch_assoc()) {
$_SESSION['cl_username'] = $row2["username"];
while ($row = $message->fetch_assoc()) {
$_SESSION['accept'] = $row["acceptance"];
$_SESSION['client_comment'] = $row["message"];
$_SESSION['name'] = $row["name"];
$_SESSION['sales_date'] = $row["sales_date"];
$_SESSION['date_sent'] = $row["date_sent"];
$_SESSION['countable_array'] = $row;
?>
<?php if ($row['acceptance'] == 3) {
echo "<tr> <td>
" . '<input type=checkbox name=devices[] value=' . $row['dev_id'] . '>' . "
</td> <td>" . $cus_id . " </td> <td>" . $rep_id . "</td> <td>" . $_SESSION['client_comment'] . "</td> <td>" . $_SESSION['name'] . "</td> <td>" . $row["device_no"] . "</td> <td>" . $row["barcode"] . "</td> <td>" . $row["serial_imei"] . "</td> <td>" . $row["serial_no"] . "</td> <td>" . $row["sales_date"] . "</td></tr>";
echo "</table>";
}
}
}
</form>
if ($_SERVER['REQUEST_METHOD'] == "POST" && isset($_POST['rejected'])) {
if (count($count_devices) == 1) {
...
}
}
<?php
while ($row2 = $clientUsername->fetch_assoc()) {
$_SESSION['cl_username'] = $row2["username"];
$i = 0; // initiate the variable here
$total_number_of_rows = $message->num_rows(); // Get total number of rows from your object
while ($row = $message->fetch_assoc()) {
$_SESSION['accept'] = $row["acceptance"];
$_SESSION['client_comment'] = $row["message"];
$_SESSION['name'] = $row["name"];
$_SESSION['sales_date'] = $row["sales_date"];
$_SESSION['date_sent'] = $row["date_sent"];
$_SESSION['countable_array'] = $row;
if ($row['acceptance'] == 3) {
$i++; // When conditions trues, increment the variable.
echo "<tr> <td>
" . '<input type=checkbox name=devices[] value=' . $row['dev_id'] . '>' . "
</td> <td>" . $cus_id . " </td> <td>" . $rep_id . "</td> <td>" . $_SESSION['client_comment'] . "</td> <td>" . $_SESSION['name'] . "</td> <td>" . $row["device_no"] . "</td> <td>" . $row["barcode"] . "</td> <td>" . $row["serial_imei"] . "</td> <td>" . $row["serial_no"] . "</td> <td>" . $row["sales_date"] . "</td></tr>";
echo "</table>";
}
}
if($i == $total_number_of_rows){ // Here implement this condition, If both equal then all inputs have checked.
echo "Check box checked all inputs";
}
}
?>
I think you expecting the same as above. We need to check the Total number of rows with Incremental variable value.
Please review my comment inside the code part, so that you can understand terms.

Not display table SQLite and php

$table = "<p><table width=\"770px\">
<thead>
<tr>
<th><b>FECHA</b></th>
<th><b>PRODUCTO</b></th>
<th><b>CANTIDAD</b></th>
<th><b>PRECIO</b></th>
</tr>
</thead>
<tbody> " . while($res = $result->fetchArray(SQLITE3_ASSOC))
{
echo
"<tr>
<td>" . $res['fecha'] . "</td>
<td>" . $res['nombre'] . "</td>
<td>" . $res['cantidad'] . "</td>
<td>" . $res['precio_hospital'] . "<br></td>
</tr>";
} . "
</tbody>
</table>";
Hello friends, I have a php page that does not allow me to show the table correctly I do not know how to place the while, please can you help me.
works friend, but I want to save the result of this table in a php variable to print it in
$ pdf-> writeHTML ($table, true, false, true, false, '');
You can't use echo when you are already inside and echo. Try:
$output = '<p><table width="770px">
<thead>
<tr>
<th><b>FECHA</b></th>
<th><b>PRODUCTO</b></th>
<th><b>CANTIDAD</b></th>
<th><b>PRECIO</b></th>
</tr>
</thead>
<tbody>';
while($res = $result->fetchArray(SQLITE3_ASSOC)) {
$output .= '<tr><td>' . $res['fecha'] . '</td>' .
'<td>' . $res['nombre'] . '</td>' .
'<td>' . $res['cantidad'] . '</td>' .
'<td>' . $res['precio_hospital'] .
'<br></td></tr>';
}
$output .= '</tbody></table>';
Like this:
$myVar = "<p><table width=\"770px\">
<thead>
<tr>
<th><b>FECHA</b></th>
<th><b>PRODUCTO</b></th>
<th><b>CANTIDAD</b></th>
<th><b>PRECIO</b></th>
</tr>
</thead>
<tbody> ";
while($res = $result->fetchArray(SQLITE3_ASSOC)) {
$myVar .=
"<tr>
<td>" . $res['fecha'] . "</td>
<td>" . $res['nombre'] . "</td>
<td>" . $res['cantidad'] . "</td>
<td>" . $res['precio_hospital'] . "<br></td>
</tr>";
}
$myVar .= "</tbody></table></p>";
//echo $myVar; //if you want to see the result
//$pdf->writeHTML ($myVar, true, false, true, false, ''); //to pdf
You can't concatenate a control structure to a string. PHP will throw a syntax error.
Edited to use a variable

How to return average data through the loop in mysqli and php

I am a beginner programmer, and i want to fetch AVG() data in every rows created by the while loop,
this is the code,
<?php
$sql = "SELECT sites_id, sites_nama, sites_alamat, sites_kota_kabupaten, perpanjangan_pagu, sites_tanggal_start, sites_tanggal_finish, perpanjangan_invoice, AVG(perpanjangan_pagu) FROM site";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table>
<tr>
<th>Site ID</th>
<th>Site Name</th>
<th>Alamat</th>
<th>Kab.Kota</th>
<th>Pagu</th>
<th>Harga Rata Rata</th>
<th>Awal Kontrak</th>
<th>Akhir Kontrak</th>
<th>Invoice</th>
</tr>";
// output data of each row
$rows = array();
while ($row = $result->fetch_assoc()) {
$rows = $row["AVG(perpanjangan_pagu)"];
echo "
<tr>
<td>" . $row["sites_id"] . "</td>
<td>" . $row["sites_nama"] . "</td>
<td>" . $row["sites_alamat"] . "</td>
<td>" . $row["sites_kota_kabupaten"] . "</td>
<td>" . $row["perpanjangan_pagu"] . "</td>
<td>" . $rows . "</td>
<td>" . $row["sites_tanggal_start"] . "</td>
<td>" . $row["sites_tanggal_finish"] . "</td>
<td>" . $row["perpanjangan_invoice"] . "</td>
</tr>";
}
echo "</table>";
}
else {
//echo "0 results";
}
$conn->close();
?>
and this is the image, you can see that it only return one row.
and this is the image when I deleted the avg function.
please help me to fetch the average data in every row in the table, not just only one table,
Thanks.
can you try this I have modified user code & added the AVG() column.
<?php
$sql = "SELECT sites_id, sites_nama, sites_alamat, sites_kota_kabupaten, perpanjangan_pagu, sites_tanggal_start, sites_tanggal_finish, perpanjangan_invoice, (SELECT AVG(perpanjangan_pagu) FROM site) AS 'AVG_pagu' FROM site";
$result = $conn->query($sql);
// AVG_pagu has the AVG value of all columns of `perpanjangan_pagu` in table `site`
if ($result->num_rows > 0) {
echo "<table>
<tr>
<th>Site ID</th>
<th>Site Name</th>
<th>Alamat</th>
<th>Kab.Kota</th>
<th>Pagu</th>
<th>Harga Rata Rata</th>
<th>Awal Kontrak</th>
<th>Akhir Kontrak</th>
<th>Invoice</th>
</tr>";
// output data of each row
// $rows = array(); // This is not actually required
while ($row = $result->fetch_assoc()) {
//$rows[] = $row["AVG_pagu"]; // This is not actually required
echo "
<tr>
<td>" . $row["sites_id"] . "</td>
<td>" . $row["sites_nama"] . "</td>
<td>" . $row["sites_alamat"] . "</td>
<td>" . $row["sites_kota_kabupaten"] . "</td>
<td>" . $row["perpanjangan_pagu"] . "</td>
<td>" . $row["AVG_pagu"] . "</td>
<td>" . $row["sites_tanggal_start"] . "</td>
<td>" . $row["sites_tanggal_finish"] . "</td>
<td>" . $row["perpanjangan_invoice"] . "</td>
</tr>";
}
echo "</table>";
}
else {
echo "No records found!";
}
$conn->close();
?>

PHP if statement in html-table outputs error

I am new to HTML5 and PHP, I am trying to output a specific value in table data, If the database-retrieved-value is per condition.
My code:
<table class="scroll">
<thead style="background-color: #99E1D9; color: #705D56;">
<tr>
<th>ID</th>
<th>Name Client</th>
<th>Last Update</th>
<th style="padding-left: 30%;">Status</th>
</tr>
</thead>
<tbody id="hoverTable">
<?php
$connection = mysql_connect('localhost', 'root', '');
mysql_select_db('patientdb');
$query = "SELECT id, name, date FROM clients";
$result = mysql_query($query);
//status waarden uit
$status = "SELECT status FROM clients";
$status_ = mysql_query($status);
while($row = mysql_fetch_array($result)){ //Loop through results
echo "<tr>
<td>" . $row['id'] . "</td>
<td>" . $row['name'] . "</td>
<td>" . $row['date'] . "</td>
<td style='padding-left: 30%;'>" .
if ($status_ > 60){echo "red";
} elseif ($status_ > 50){echo "yellow";
} else{echo "green";}
. "</td>
</tr>";
}
mysql_close();
?>
</tbody>
</table>
Error output
Parse error: syntax error, unexpected T_IF in
/test/composition/login/portal/portal.php
on line 204
What is the right way to solve this?
EDIT
my current code:
<table class="scroll">
<thead style="background-color: #99E1D9; color: #705D56;">
<tr>
<th>Naam Client</th>
<th>Laatste Update</th>
<th style="margin-left: 40%; padding-left: 0%;">Status</th>
</tr>
</thead>
<tbody id="hoverTable" style="font-size: 11pt;">
<?php
$connection = mysql_connect('localhost', 'root', '');
mysql_select_db('patientdb');
$query = "SELECT id, naam, datum FROM clients";
$result = mysql_query($query);
$query2 = "SELECT status FROM clients";
$result2 = mysql_query($query2);
if (!empty ($result2)) {
while ($row2 = mysql_fetch_assoc($result2)) {
echo $row2['status'] . "<br />";
}
}
while($row = mysql_fetch_array($result)){ //Loop through results
echo "<tr>
<td>" . $row['id'] . "</td>
<td>" . $row['naam'] . "</td>
<td>" . $row['datum'] . "</td>
<td style='padding-left: 30%;'>";
if ($results2 > 60 && $results2 < 70) {
echo "red";
} elseif ($results2 > 50 && $results2 < 60) {
echo "yellow";
} else {
echo "green";
}
echo "</td>
</tr>";
}
mysql_close();
?>
</tbody>
</table>
Output the right data. but partly outside and partly inside the table.
You will have to remove the if statement out of the echo to get rid of the error Try this:
<table class="scroll">
<thead style="background-color: #99E1D9; color: #705D56;">
<tr>
<th>ID</th>
<th>Name Client</th>
<th>Last Update</th>
<th style="padding-left: 30%;">Status</th>
</tr>
</thead>
<tbody id="hoverTable">
<?php
$connection = mysql_connect('localhost', 'root', '');
mysql_select_db('patientdb');
$query = "SELECT id, name, date FROM clients";
$result = mysql_query($query);
//status waarden uit
$status = "SELECT status FROM clients";
$status_ = mysql_query($status);
while($row = mysql_fetch_array($result)){ //Loop through results
echo "<tr>
<td>" . $row['id'] . "</td>
<td>" . $row['name'] . "</td>
<td>" . $row['date'] . "</td>
<td style='padding-left: 30%;'>";
if ($status_ > 60) {
echo "red";
} elseif ($status_ > 50) {
echo "yellow";
} else {
echo "green";
}
echo "</td>
</tr>";
}
mysql_close();
?>
</tbody>
</table>
You can't have an if statement (or any other statement, for that matter) in the middle of another statement like echo. If you want to concatenate different strings depending on a variable, you can use the conditional (AKA "ternary") operator.
echo "<tr>
<td>" . $row['id'] . "</td>
<td>" . $row['name'] . "</td>
<td>" . $row['date'] . "</td>
<td style='padding-left: 30%;'>" .
$status_ > 60 ? "red" : ($status_ > 50 ? "yellow" : "green" )
. "</td>
</tr>";
Try:
$status = "green";
if ($status > 50)
{
$status="yellow";
}
elseif($status>60)
{
$status="red";
}
echo "<tr>
<td>" . $row['id'] . "</td>
<td>" . $row['name'] . "</td>
<td>" . $row['date'] . "</td>
<td style='padding-left: 30%;'>" .$status. "</td>
</tr>";
You can't append to a string a conditional statement, assign to a variable first for example (like I posted)
This part isn't at the right place:
if ($status_ > 60){echo "red";
} elseif ($status_ > 50){echo "yellow";
} else{echo "green";}
should be:
echo "<tr>
<td>" . $row['id'] . "</td>
<td>" . $row['name'] . "</td>
<td>" . $row['date'] . "</td>
<td style='padding-left: 30%;'>";
if ($status_ > 60){
echo "red";
} elseif ($status_ > 50){
echo "yellow";
} else{
echo "green";
}
echo "</td></tr>";
Surely status_ would not come back with a number, but an array.
$status_ = mysql_query($status);
Without knowing what data is coming back, it is difficult to help.
mysql_query

Creating a function that contains a while loop

I am new to PHP and trying to learn it by creating a database of all my jobs (I'm a freelance designer). I have created the code below to generate a table to display all jobs where the description contains logo which works fine and generates several rows....
<?php
$logojobs = mysql_query("SELECT * FROM hlgd_projects WHERE description LIKE '%logo%'", $connection);
?>
View logo jobs
<?php
if ($report == 'logo') {
echo "<h1>Logo jobs</h1>";
echo "<table id='report'>
<tr>
<th></th>
<th>Status</th>
<th>Lead</th>
<th>Start</th>
<th colspan='2'>Codes</th>
<th>Client</th>
<th>Description</th>
<th>Fee</th>
<th>Contact</th>
<th colspan='2'>Invoice</th>
<th>Paid</th>
</tr>";
while ($logojob = mysql_fetch_array($logojobs)) {
echo "<tr>
<td class='id'>" . $logojob['id'] . "</td>
<td>" . $logojob['status_id'] . "</td>
<td>" . $logojob['lead_id'] . "</td>
<td>" . $logojob['date_start'] . "</td>
<td>" . $logojob['code_lead'] . "</td>
<td>" . $logojob['code_hlgd'] . "</td>
<td>" . $logojob['client'] . "</td>
<td>" . $logojob['description'] . "</td>
<td>£" . $logojob['fee'] . "</td>
<td>" . $logojob['contact'] . "</td>
<td>" . $logojob['invoice'] . "</td>
<td>" . $logojob['date_inv'] . "</td>
<td>" . $logojob['date_paid'] . "</td>
</tr>";
}
echo "</table>";
}
?>
However I would like to be able to generate reports for lots of different things and so would like to create a function to generate the table and pass the relevant arguments each time. I've done this as follows but it only generates the first row so I presume it's ignoring the while? Can anyone tell me where I'm going wrong or how to better put the code above into a function?
<?php
function report_bytype($title,$job_set,$job_name) {
$reporthead = "<h1>$title</h1>
<table id='report'>
<tr>
<th></th>
<th>Status</th>
<th>Lead</th>
<th>Start</th>
<th colspan='2'>Codes</th>
<th>Client</th>
<th>Description</th>
<th>Fee</th>
<th>Contact</th>
<th colspan='2'>Invoice</th>
<th>Paid</th>
</tr>";
while ($job_name = mysql_fetch_array($job_set)) {
$reportrows = "
<tr>
<td class='id'>" . $job_name['id'] . "</td>
<td>" . $job_name['status_id'] . "</td>
<td>" . $job_name['lead_id'] . "</td>
<td>" . $job_name['date_start'] . "</td>
<td>" . $job_name['code_lead'] . "</td>
<td>" . $job_name['code_hlgd'] . "</td>
<td>" . $job_name['client'] . "</td>
<td>" . $job_name['description'] . "</td>
<td>£" . $job_name['fee'] . "</td>
<td>" . $job_name['contact'] . "</td>
<td>" . $job_name['invoice'] . "</td>
<td>" . $job_name['date_inv'] . "</td>
<td>" . $job_name['date_paid'] . "</td>
</tr>";
}
$reportfoot = "</table>";
$reporttable = $reporthead . $reportrows . $reportfoot;
echo $reporttable;
return $reporttable;
}
?>
<?php
if($report == 'logo') {
report_bytype("logo",$logojobs,$logojob);
}
if($report == 'stationery') {
report_bytype("stationery",$stationeryjobs,$stationeryjob);
}
?>
Many thanks in advance,
Helen
The problem is this line:
while ($job_name = mysql_fetch_array($job_set)) {
$reportrows = "lots of html"
}
Every time this loops $reportrows is set to the html for that row only.
Use $reportrows .= "some html"; instead which will add each row to $reportrows rather than replace $reportrows with that row.
Edit: Replacing += with .=.
I can see why you have errors you are not concatenating your result
Please see http://php.net/manual/en/language.operators.string.php for more detailed explanations
Replace
$reportrows = "
With
$reportrows .= "
Full Script
function report_bytype($title, $job_set, $job_name) {
$reporthead = "<h1>$title</h1>
<table id='report'>
<tr>
<th></th>
<th>Status</th>
<th>Lead</th>
<th>Start</th>
<th colspan='2'>Codes</th>
<th>Client</th>
<th>Description</th>
<th>Fee</th>
<th>Contact</th>
<th colspan='2'>Invoice</th>
<th>Paid</th>
</tr>";
$reportrows = "";
while ( $job_name = mysql_fetch_array ( $job_set ) ) {
$reportrows .= "
<tr>
<td class='id'>" . $job_name ['id'] . "</td>
<td>" . $job_name ['status_id'] . "</td>
<td>" . $job_name ['lead_id'] . "</td>
<td>" . $job_name ['date_start'] . "</td>
<td>" . $job_name ['code_lead'] . "</td>
<td>" . $job_name ['code_hlgd'] . "</td>
<td>" . $job_name ['client'] . "</td>
<td>" . $job_name ['description'] . "</td>
<td>£" . $job_name ['fee'] . "</td>
<td>" . $job_name ['contact'] . "</td>
<td>" . $job_name ['invoice'] . "</td>
<td>" . $job_name ['date_inv'] . "</td>
<td>" . $job_name ['date_paid'] . "</td>
</tr>";
}
$reportfoot = "</table>";
$reporttable = $reporthead . $reportrows . $reportfoot;
echo $reporttable;
return $reporttable;
}
Thanks

Categories