Can not insert image in table <td> cell - php

I am trying to write a shopping cart for my site and I want to display a table with a row for each item, including the part #, name, quantity, price and a small image. Everything displays fine except for the image, which appears outside (above) the table and not in the cell where I've placed it. Here's the code:
//create a table for the items in the cart
print("<table class='cart_table'>");
print("<tr class='first_row'>
<td> Item No. </td>
<td> Item Name </td>
<td> Quantity </td>
<td> Price </td>
<td> Image </td>
</tr>");
//for each item in the cart
foreach ($_SESSION['cart'] as $value) {
//create a new product object for the item
$product = new LG_Product($_SESSION['cart'][$i]['item']);
print("<tr>");
print("<td> " . $product->itemID . " </td>");
print("<td> " . $product->productName . " </td>");
print("<td> " . $_SESSION['cart'][$i++]['qty'] . " </td>");
print("<td> $" . $product->productPrice . " </td>" );
print("<td>" . $product->showPrimaryImage('small') . "</td>");
print("</tr>");
}
//end the table
print("</table>");
And here's the function that gets the image:
public function showPrimaryImage($variant) {
if($variant == "medium") {
print ("<img style = \" max-width:400px;
max-height:400px;
display: block;
margin-left: auto;
margin-right: auto;\"
src=\"" . WEBSITE_URL . PATH_DYNAMIC . "/products_" . $this->productNumber . "_1_" . $variant . ".jpg\"
alt=\"" . $this->productName . "\">
");
}
else if($variant == "large") {
print ("<img style = \" max-width:600px;
max-height:600px;
display: block;
margin-left: auto;
margin-right: auto;\"
src=\"". WEBSITE_URL . PATH_DYNAMIC . "/products_" . $this->productNumber . "_1_" . $variant . ".jpg\"
alt=\"" . $this->productName . "\">
");
}
else if($variant == "small") {
print ("<img style = \" max-width:100px;
max-height:100px;
display: block;
margin-left: auto;
margin-right: auto;\"
src=\"". WEBSITE_URL . PATH_DYNAMIC . "/products_" . $this->productNumber . "_1_" . $variant . ".jpg\"
alt=\"" . $this->productName . "\">
");
}
}//end function showPrimaryImage()
When I view the source in the browser, it appears the code that renders the image is not inside the pair. When I view the red warning in the browser source, it says:
start tag "img" seen in "table"
Here's a screen capture of where the image appears:
And here's the source that's output from my PHP code (when viewed in the browser, the entire tag statement is in red):
<table class='cart_table'>
<tr class='first_row'>
<td> Item No. </td>
<td> Item Name </td>
<td> Quantity </td>
<td> Price </td>
<td> Image </td>
</tr>
<tr>
<td> BQ2819 </td>
<td> A WWII Period U.S. Theater-made Fighting Knife with Sheath </td>
<td> 1 </td>
<td> $270.00 </td>
<img style = " max-width:100px;
max-height:100px;
max-height:100px;
display: block;
margin-left: auto;
margin-right: auto;"
src="http://www.mywebsite.com/dynamic/products_2056_1_small.jpg"
alt="A WWII Period U.S. Theater-made Fighting Knife with Sheath">
<td></td>
</tr>
<tr>
<td> BQ2819 </td>
<td> A WWII Period U.S. Theater-made Fighting Knife with Sheath </td>
<td> 1 </td>
<td> $270.00 </td>
<img style = " max-width:100px;
max-height:100px;
display: block;
margin-left: auto;
margin-right: auto;"
src="http://www.mywebsite.com/dynamic/products_2056_1_small.jpg"
alt="A WWII Period U.S. Theater-made Fighting Knife with Sheath">
<td></td>
</tr>
</table>

For the line:
print("<td>" . $product->showPrimaryImage('small') . "</td>");
You have a string concatenation, which means you will concatenate whatever the return value of the call to showPrimaryImage is. However, showPrimaryImage doesn't return anything. Therefore the program first outputs the image's html (from the showPrimaryImage call) and then outputs <td></td> from the outer print.
You need to change print to a return statement for your showPrimaryImage function

function showPrimaryImage($variant) {
if($variant == "medium") {
return img;
} else if() {
//...
}
}

Related

$_SESSION problem - I have same ID on all <tr>

I don’t know, how I do this: I want to add $id from database to $_SESSION["dbID"] and after click, it shows me more information from database. But table generates in while function and $_SESSION["dbID"] every time set to the highest number of row from table. Please, Can you anyone change my code as I have $_SESSION["dbID"] on every <tr> of table different? Thank you
while($row = $result->fetch_assoc())
{
$id=$row['ID'];
$name=$row['Name'];
$subject=$row['Subject'];
$date=$row['Date'];
echo
'<tr class="trX" id="'.$id.'" href="google.com&id='.$row['ID'].'">
<td class="tdX"><a style="color:black; text-decoration: none;" href="page.php">' . $id . '</a></td>
<td class="tdX"><a style="color:black; text-decoration: none;" href="page.php">' . $name . '</td>
<td class="tdX"><a style="color:black; text-decoration: none;" href="page.php">' . $subject . '</td>
<td class="tdX"><a style="color:black; text-decoration: none;" href="page.php">' . $date . '</td>
</tr>';
}
$_SESSION["dbID"] = $id;
echo ' </table> ';
Explanation
You can do away with all of the a tags and use JavaScript to handle the redirect...
$url = "/path/to/file.php?id=" . $id;
Set the URL to the page that you want to link to. The line above shows the link to the file "file.php" on the server with the query string "id=$id".
onclick="window.location.href='...'"
The line above is a JS equivalent of href. If you want to navigate to a server outside of your domain remember to add the full url e.g. https://www.website.com
Code example
while ($row = $result->fetch_assoc()) {
$id = $row['ID'];
$name = $row['Name'];
$subject = $row['Subject'];
$date = $row['Date'];
$url = "/url/path.php?id=" . $id;
echo <<<EOT
<tr class="trX" onclick="window.location.href='{$url}'">
<td class="tdX">{$id}</td>
<td class="tdX">{$name}</td>
<td class="tdX">{$subject}</td>
<td class="tdX">{$date}</td>
</tr>
EOT;
}
echo ' </table> ';
if (mysqli_num_rows($sql) > 0) {
$row = mysqli_fetch_assoc($sql);
}
while($row = $result->fetch_assoc()){ ?>
<tr class="trX" id="'.<?php echo $row['ID']; ?>.'" href="google.com&id='.$row['ID'].'">
<td class="tdX"><a style="color:black; text-decoration: none;" href="page.php"><?php echo $row['ID']; ?></a></td>
<td class="tdX"><a style="color:black; text-decoration: none;" href="page.php"><?php echo $row['Name']; ?></td>
<td class="tdX"><a style="color:black; text-decoration: none;" href="page.php"><?php echo $row['Subject']; ?></td>
<td class="tdX"><a style="color:black; text-decoration: none;" href="page.php"><?php echo $row['Date']; ?> </td>
</tr>
<?php } ?>
Dont define the rows just make a call for them in the databse.

PHP Column Styling

I need my table to include submissions into three columns then a new row start with three more columns, etc. So submission 1, first column, submission 2, second column, submission 3, 3 column. Then a new row and the process starts again. (HTML Example Code below)
Every time I try with my php code my page comes up blank so I am missing something somewhere.
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, website, url, email, date, description FROM basic";
$result = $conn->query($sql);
if ($result->num_rows>0){
<tr>
while ($row=$result->fetch_assoc()) {
echo "<table><tr><th><b>Company:</b> " . $row["name"]. "</th></tr><tr><td>
<b>URL:</b> <a href='".$row["url"]."'>".$row["url"]."</a></td></tr><tr><td>
<b>Email:</b> " . $row["email"]. "</td></tr><tr><td><b>Launch Date:</b> " .
$row["date"]. "</td></tr><tr><td><b>Announcement:</b> " .
$row["description"]. "</td>
</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
Example: This is what I am trying to get it to look like.
<style>
table, td, th {
border: 10px solid #ffffff;
text-align: left;
}
table {
border-collapse: initial;
width: 100%;
}
td {
padding: 15px;
width: 25%;
line-height: 2;
}
th {
background-color: grey;
color: white;
padding: 5px;
width: 25%;
}
</style>
<body>
<table class="ex1">
<tr>
<th>Company</th>
<th>Company</th>
<th>Company</th>
</tr>
<tr>
<td>
<b>URL:</b><br>
<b>Location:</b><br>
<b>Inductry:</b><br>
<b>Start Date:</b><br>
<b>Announcement:</b><br>
<br>
</td>
<td>
<b>URL:</b><br>
<b>Location:</b><br>
<b>Inductry:</b><br>
<b>Start Date:</b><br>
<b>Announcement:</b><br>
<br>
</td>
<td>
<b>URL:</b><br>
<b>Location:</b><br>
<b>Inductry:</b><br>
<b>Start Date:</b><br>
<b>Announcement:</b><br>
<br>
</td>
</table>
Your PHP code is not generating HTML in proper format. Please try below:
// Query executed here and resultset returned
if ($result->num_rows>0){
echo "<table>";
while ($row=$result->fetch_assoc()) {
echo "<tr><th><b>Company:</b> " . $row["name"]. "</th></tr>
<tr><td><b>URL:</b> <a href='".$row["url"]."'>".$row["url"]."</a></td></tr>
<tr><td><b>Email:</b> " . $row["email"]. "</td></tr>
<tr><td><b>Launch Date:</b> " . $row["date"]. "</td></tr>
<tr><td><b>Announcement:</b> " . $row["description"]. "</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}

Displaying a progress bar in php file

I have a php file which selects a large amount of data from mutiple sql table. Naturally it takes a long time to complete the whole process. I want to display a progress bar which will express the progress of the script running. How to display a progress bar? The script below shows a portion of the php file.
<?php
//RIGHT(AdmitCode,1), PartCode, MID(AdmitCode,2,2), MID(AdmitCode,1,1) DESC, RollCode
$query = "SELECT * FROM students1 ORDER BY PartCode, AdmitCode, yearcode desc, RollCode";
$result = mysql_query($query);
// start a table tag in the HTML
echo "<table border='1' align='center' style='border-collapse:collapse' width='110%'>";
echo "<caption>
<h2>List of candidates for Three year Degree
(Honours/General) Programme Examination-".$bx1." (".$bx2.")
</h2>
</caption>";
//$row['index'] the index here is a field name
echo "<tr bgcolor=''>
<th> Sl. No </th>
<th>ID </th>
<th> Semester </th>
<th> Roll No </th>
<th> Registration No</th>
<th> Name </th>
<th> Honours </th>
<th> Elective-1 </th>
<th> Elective-2 </th>
<th> Elective-3 </th>
<th> MIL </th>
<th> Foundation </th>
<th> Soft studies </th>
<th> Syllabus </th>
</tr>";
$ty=0;
while($row = mysql_fetch_array($result)){ //Creates a loop to loop through results
$ty++;
if ($ty%2==0)
echo "<tr bgcolor='pink'>";
else
echo "<tr>";
echo "<td align='center'>$ty</td>
<td align='center'>" . $row['StudentID']." </td>
<td align='center'>" . $row['PartCode']."</td>
<td align='center'>" . $row['AdmitRollNo'] . "</td>
<td align='center'>" . $row['RegistrationNo']. "</td>
<td align='left'>" . $row['Name'] . "</td>
<td align='center'>" . $row['HonoursSubject'] . "</td>
<td align='center'>". $row['ElectiveSubject1'] . "</td>
<td align='center'>". $row['ElectiveSubject2'] . "</td>
<td align='center'>". $row['ElectiveSubject3'] . "</td>
<td align='center'>". $row['MIL'] . "</td>
<td align='center'>". $row['Foundation'] . "</td>
<td align='center'>". $row['SoftStudies'] . "</td>
<td align='center'>". $row['Syllabus'] . "</td>
</tr>";
}
echo "</table>"; //Close the table in HTML
Generally, to implement a good progress bar, you need a progress indicator from the layer which does the work, i.e. the mysql database. I am not aware, that mysql provides such a feature.
So you are stuck with estimating how long the operation will probably last (i.e. from past queries or derive it from the query parameters) and just implement a javascript progress bar (JQueryUI provides a good one), which is just time based.
Alternatively, you could just use a spinner to indicate, that you do not know how long this process really runs.
you can add div coantainer for the table and has id page and add css this show the loading image until page full load.
eg.
<div id="page">
<table>
</table>
</div>
css
<style>
#page {
display: none;
}
#loading {
display: block;
position: absolute;
top: 0;
left: 0;
z-index: 100;
width: 100vw;
height: 100vh;
// background-image: url(loading_spinner.gif);
background-image:url("loading_spinner.gif");
background-repeat: no-repeat;
background-position: center;
}
</style>
<script>
$(window).load(function() {
$('#page').show();
$('#loading').hide('slow');
});
</script>
add this js code in your page this will help you.
You can use the following simple code
<?php
//header('Content-Type: text/event-stream');
// recommended to prevent caching of event data.
header('Cache-Control: no-cache');
//long_process.php
for($i=1;$i<=3;$i++){
//do something
echo '<br>processing...';
ob_flush();
flush();
sleep(1);
}
echo 'CLOSE', 'Process complete';
?>
Or use as following
index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<br />
<input type="button" onClick="startTask()" value="Start Long Task" />
<input type="button" onClick="stopTask();" value="Stop Task" />
<br />
<br />
<p>Results</p>
<br />
<div id="results" style="border:1px solid #000; padding:10px; width:300px; height:250px; overflow:auto; background:#eee;"></div>
<br />
<progress id='progressor' value="0" max='100' style=""></progress>
<span id="percentage" style="text-align:right; display:block; margin-top:5px;">0</span>
</body>
</html>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
var es;
function startTask() {
es = new EventSource('bar2.php');
//a message is received
es.addEventListener('message', function(e) {
var result = JSON.parse( e.data );
addLog(result.message);
if(e.lastEventId == 'CLOSE') {
addLog('Received CLOSE closing');
es.close();
var pBar = document.getElementById('progressor');
pBar.value = pBar.max; //max out the progress bar
}
else {
var pBar = document.getElementById('progressor');
pBar.value = result.progress;
var perc = document.getElementById('percentage');
perc.innerHTML = result.progress + "%";
perc.style.width = (Math.floor(pBar.clientWidth * (result.progress/100)) + 15) + 'px';
}
});
es.addEventListener('error', function(e) {
addLog('Error occurred');
es.close();
});
}
function stopTask() {
es.close();
addLog('Interrupted');
}
function addLog(message) {
var r = document.getElementById('results');
r.innerHTML += message + '<br>';
r.scrollTop = r.scrollHeight;
};
</script>
Then create the following page. It has called in the index.php
bar.php
<?php
header('Content-Type: text/event-stream');
// recommended to prevent caching of event data.
header('Cache-Control: no-cache');
function send_message($id, $message, $progress) {
$d = array('message' => $message , 'progress' => $progress);
echo "id: $id" . PHP_EOL;
echo "data: " . json_encode($d) . PHP_EOL;
echo PHP_EOL;
ob_flush();
flush();
}
//LONG RUNNING TASK
for($i = 1; $i <= 10; $i++) {
send_message($i, 'on iteration ' . $i . ' of 10' , $i*10);
sleep(1);
}
send_message('CLOSE', 'Process complete');

how to select and echo an image from mysql

I am trying to get information from mysql including a blob image which i shall echo with php and will have an onclick event within the php, redirecting it to another page. The onlick event will contain a mysql result which it will carry with it as seen in the code below.
My main issue is with the syntax of the code or if there is another way to do it all together. please keep in mind the output when the script is run is similiar to that of google images, bing images etc. Thank you.
<?php
$con=mysqli_connect("localhost","root","*******","media");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM movies ORDER BY `movies`.`title` ASC");
echo "<table border='3' style='margin: auto; text-align: left;background: white; padding: 3em;'>
<tr>
<th><b>Movie Title</b></th>
<th><b>Language</b></th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td style='padding-right: 2em;'><img src="data:image/jpeg;base64,' . base64_encode( $row['image'] ) . '" width="160px" height="200px";" onclick="window.location='lookup.php?pattern=" . $row['title'] . "';>";
</td>
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
Untested but here is one way you could clean up your code move style and javascript (and use some jquery) into the head:
<?php
$con=mysqli_connect("localhost","root","*******","media") or die("Failed to connect to MySQL: " . mysqli_connect_error());
$result = mysqli_query($con,"SELECT * FROM movies ORDER BY `movies`.`title` ASC");
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('img').each(function() {
var img = $(this);
img.click(function() {
window.location="lookup.php?pattern=" + img.attr('title');
});
});
});
</script>
<style>
table {
margin: auto;
text-align: left;
background: white;
padding: 3em;
border: 2px solid #000000;
}
table tr td {
padding-right: 2em;
}
table tr td img {
width: 160px;
height: 200px;
}
</style>
</head>
<body>
<table>
<tr>
<th>Movie Title</th>
<th>Language</th>
</tr>
<?php
while($row = mysqli_fetch_array($result)) {
echo "
<tr>
<td>
<img src=\"data:image/jpeg;base64," . base64_encode( $row['image'] ) . "\" title=\"" . $row['title'] . "\">
</td>
</tr>
";
}
?>
</table>
</body>
</html>
<?php mysqli_close($con); ?>
Or if you don't want to use javascript, you could always wrap the image around the anchor tag instead:
<td>
<a href='lookup.php?pattern={$row['title']}'>
<img src=\"data:image/jpeg;base64," . base64_encode( $row['image'] ) . "\">
</a>
</td>
You could further separate PHP and HTML code:
<?php
$con=mysqli_connect("localhost","root","*******","media");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}
$result = mysqli_query($con,"SELECT * FROM movies ORDER BY `movies`.`title` ASC");
?>
<table border='3' style='margin: auto; text-align: left;background: white; padding: 3em;'>
<tr>
<th><b>Movie Title</b></th>
<th><b>Language</b></th>
</tr>
<?php
while($row = mysqli_fetch_array($result)) {
$img = 'data:image/jpeg;base64,'
. base64_encode( $row['image'] );
?>
<tr>
<td style='padding-right: 2em;'>
<img src="<?php echo $img; ?>"
style="width: 160px; height: 200px;"
onclick="window.location='lookup.php?pattern=<?php echo $row['title']?>;'"
/>
</td>
</tr>
<?php } ?>
</table>
<?php
mysqli_close($con);
?>
You could also use some sort of templating engine to do this, but the results would be pretty much the same - I don't see much point in writing, say,
<strong>{{ title }}</strong>
instead of
<strong><?php echo $title; ?></strong>

Border around specific table row

I am trying to create a border around the top row ONLY! Currently, a border will be displayed only around the outside of the table. But I also want a border around the first row. Can someone help me do this? I want the row with 'Team, Correct Picks, and Points' to have a border around it.
<body>
<?=$leaguename?>
<center><table cellspacing="0" style="width:400px; border:1px solid gray">
<?
echo "<tr border=\"1\"><td> Team </td><td>Correct Picks</td><td>Points</td></tr>";
while($row = mysql_fetch_array($memberslist)) {
if ($row['User_ID'] == $id) {
echo "<tr style=\"border:1px solid gray\" bgcolor=\"gray\"><td>" . $row['User_ID'] . "</td><td><b>" . $row['Correct_Picks'] . " </b> /" . $maxcorrectpicks . "</td><td>" . $row['Points'] . "</td></tr>";
} else {
echo "<tr><td>" . $row['User_ID'] . "</td><td><b>" . $row['Correct_Picks'] . " </b> /" . $maxcorrectpicks . "</td><td>" . $row['Points'] . "</td></tr>";
}
}
?>
</table></center>
</body>
This is presentational, so mixing it into the PHP is a bad idea. Instead, use CSS:
tr:first-child td { border-top: 1px solid black; border-bottom: 1px solid black; }
tr:first-child td:first-child { border-left:1px solid black; }
tr:first-child td:last-child { border-right:1px solid black; }
IE7+8 support for the *-child selectors can be a bit buggy. If it's not working in those browsers, consider using JavaScript polyfills.
You may also want to put the headers inside <thead> and <th> elements to make the <tr> with data the first row in a <tbody> element.
e.g.
<table>
<thead>
<tr>
<th>Team</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
</tr>
</tbody>
</table>

Categories