Displaying a progress bar in php file - php

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');

Related

save values from editable table using php

Hi I have a table generated from php, it is editable, I want to save edited values to database. I have no Idea how can I do this as there are many rows(dynamic) on a page.
Here is a screen-shot:-
Please suggest
Edit:-
My code is
echo "<table border='1'>
<tr>
<th>Sl Number</th>
<th>Product Id</th>
<th>Product Name</th>
<th>Product Catagory</th>
<th>Retal Price</th>
<th>Max Price</th>
<th>Min Price</th>
<th>Initial Stock</th>
<th>Quantity Sold</th>
<th>Current Stock</th>
<th>Last Order</th>
<th>Edit/Update</th>
</tr>";
while($row = $result->fetch_assoc())
{
echo "<tr contenteditable>";
echo "<td>" . $row["Row Number"]. "</td>";
echo "<td>" . $row["Product Id"]. "</td>";
echo "<td>" . $row["Product Name"]. "</td>";
echo "<td>" . $row["Product Catagory"]. "</td>";
echo "<td>" . $row["Retal Price"]. "</td>";
echo "<td>" . $row["Max Price"]. "</td>";
echo "<td>" . $row["Min Price"]."</td>";
echo "<td>" . $row["Initial Stock"]."</td>";
echo "<td>" . $row["Quantity Sold"]. "</td>";
echo "<td>" . $row["Current Stock"]."</td>";
echo "<td>" . $row["Last Order"]."</td>";
echo "<td contenteditable = 'false'><button href = '#'>Update</a></td>";
echo "</tr>";
}
Let me give you with the best way
First your database tables have spaces: correct that e.g.
from $row["Initial Stock"] to $row["Initial_Stock"]
Then i will propose you use ajax instead of wasting time clicking buttons
The HTML Page
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
<script>
$(function(){
$("#loading").hide();
//acknowledgement message
var message_status = $("#status");
$("td[contenteditable=true]").blur(function(){
var field_userid = $(this).attr("id") ;
var value = $(this).text() ;
$.post('update.php' , field_userid + "=" + value, function(data){
if(data != '')
{
message_status.show();
message_status.text(data);
//hide the message
setTimeout(function(){message_status.hide()},1000);
}
});
});
});
</script>
<style>
table.zebra-style {
font-family:"Lucida Sans Unicode", "Lucida Grande", Sans-Serif;
text-align:left;
border:1px solid #ccc;
margin-bottom:25px;
width:100%
}
table.zebra-style th {
color: #444;
font-size: 13px;
font-weight: normal;
padding: 5px 4px;
}
table.zebra-style td {
color: #777;
padding: 4px;
font-size:13px;
}
table.zebra-style tr.odd {
background:#f2f2f2;
}
#status { padding:10px; position:fixed; top:10px; border-radius:5px; z-index:10000000; background:#88C4FF; color:#000; font-weight:bold; font-size:12px; margin-bottom:10px; display:none; width:100%; }
#loading { padding:10px; position:absolute; top:10px; border-radius:5px; z-index:10000000; background:#F99; color:#000; font-weight:bold; font-size:12px; margin-bottom:10px; display:none; width:100%; }
</style>
<div id="status"> </div>
<div id="loading"></div>
<table id="tableID" border="0" class="sortable table zebra-style">
<thead>
<tr>
<th>Sl Number</th>
<th>Product Id</th>
<th>Product Name</th>
<th>Product Catagory</th>
<th>Retal Price</th>
<th>Max Price</th>
<th>Min Price</th>
<th>Initial Stock</th>
<th>Quantity Sold</th>
<th>Current Stock</th>
<th>Last Order</th>
<th>Edit/Update</th>
</tr>
</thead>
<tbody class="list">
<?php do { ?>
<tr>
<td contenteditable="true" id="Row_Number:<?php echo $row["Row_Number"]; ?>"><?php echo $row["Row_Number"]; ?></td>
<td contenteditable="true" id="Product_Id:<?php echo $row["Product_Id"]; ?>"><?php echo $row["Product_Id"]; ?></td>
<td contenteditable="true" id="Product_Name:<?php echo $row["Product_Name"]; ?>"><?php echo $row["Product_Name"]; ?></td>
<td contenteditable="true" id="Product_Catagory:<?php echo $row["Product Id"]; ?>"><?php echo $row["Product_Catagory"]; ?></td>
<td contenteditable="true" id="Retal_Price:<?php echo $row["Retal_Price"]; ?>"><?php echo $row["Retal_Price"]; ?></td>
<td contenteditable="true" id="Max_Price:<?php echo $row["Max_Price"]; ?>"><?php echo $row["Max_Price"]; ?></td>
<td contenteditable="true" id="Min_Price:<?php echo $row["Min_Price"]; ?>"><?php echo $row["Min_Price"]; ?></td>
<td contenteditable="true" id="Initial_Stock:<?php echo $row["Initial_Stock"]; ?>"><?php echo $row["Initial_Stock"]; ?></td>
<td contenteditable="true" id="Quantity_Sold:<?php echo $row["Quantity_Sold"]; ?>"><?php echo $row["Quantity_Sold"]; ?></td>
<td contenteditable="true" id="Last_Order:<?php echo $row["Last_Order"]; ?>"><?php echo $row["Last_Order"]; ?></td>
<td contenteditable="true" id="Last_Order:<?php echo $row["Last_Order"]; ?>"><?php echo $row["Last_Order"]; ?></td>
<td contenteditable = 'false'></td>";
</tr>
<?php } while($row = $result->fetch_assoc()) ?>
</tbody>
</table>
And the update php page
<?php
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF-8',
'username',
'password',
array(PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
?>
<?php
if(!empty($_POST))
{
//database settings
foreach($_POST as $field_name => $val)
{
//clean post values
$field_id = strip_tags(trim($field_name));
//from the fieldname:user_id we need to get user_id
$split_data = explode(':', $field_id);
$product_id = $split_data[1];
$field_name = $split_data[0];
if(!empty($product_id) && !empty($field_name) && !empty($val))
{
$affected_rows = $db->exec("UPDATE yourtable SET $field_name = '$val' WHERE product_ID = $product_id");
echo $affected_rows;
echo "Updated";
} else {
echo "Invalid Requests";
}
}
}
else {
echo "Invalid Requests";
}
?>
To save the whole table, you could leave the row-level update buttons out, and have a single save button:
<button id="save">Save</button>
<div id="msg"></div>
The msg area is to display feed-back from the server when the save-operation is performed.
Then you would add this JavaScript to handle the click of the save button:
$('#save').click(function() {
var data = [];
$('td').each(function() {
var row = this.parentElement.rowIndex - 1; // excluding heading
while (row >= data.length) {
data.push([]);
}
data[row].push($(this).text());
});
$.post('savetable.php', {table: data}, function (msg) {
$('#msg').text(msg);
});
});
This will transform the HTML table contents, without header row, to a JavaScript matrix, which then is sent to savetable.php for processing.
In PHP you would then use $_POST['table'] to access that array. When you implement this, first debug, and do a var_dump($_POST['table']) to make sure the data was transferred correctly, and it has the array structure you expect.
Then loop over that array to insert the rows into your database. You can use mysqli or PDO for this.
The PHP script savetable.php should only echo one message: a confirmation ("the table was saved successfully") or an error message ("a problem occurred. Your data was not saved.").
It should not reproduce the HTML of the table, since that is already displayed in the browser. Whatever PHP prints will be used by the JavaScript code to be displayed below the save button.
Here is how savetable.php could look like. But please debug carefully, I did not test this code. And before it works, you first need to set up your database model of course:
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8mb4',
'username', 'password');
// Configure that all database errors result in an exception:
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
// Make a transaction: this allows to rollback any of the changes
// if anything goes wrong before the end of it.
$db->beginTransaction();
// First delete all rows.
$db->exec("DELETE FROM mytable");
// Prepare a statement that will be executed for each row.
// Needs to be extended for all columns:
$stmt = $db->prepare("INSERT INTO mytable (sl_num, product_id, product_name)
VALUES (?, ?, ?)");
foreach ($_POST('table'] as $row) {
$stmt->execute($row); // the columns are passed to the prepared statement.
}
// All went well: commit the changes.
$db->commit();
echo "Table saved successfully";
} catch(PDOException $e) {
// Something went wrong: roll back any changes made
$db->rollback();
echo "An error occurred: " . $e->getMessage();
}
What you can do is ajax call to a php with the id of the row you want to save and the new data. Then use PDO to connect to the database and update the information. After that is done, use javascript to edit the table itself.
So what you need to do is look up how to use ajax calls and use PDO. I suggest when you echo the table itself
<button href = '#' onclick="updateRow('. $row['Row Number'] .')">Update</a></td> where Row Number is the ID in the database and updateRow() is the javascript function you will create to get the new information and send it via ajax. Don't use mysql_*, because it is not supported in php 7 and it will die soon. Look up PDO instead.

How to show selected table row id in the address bar with ajax

I have this below script that load the selected table row details in a div in the same page with ajax.
$('.positiontitle-link').click(
function(){
var durl = $(this).attr('ref');
$('#details').load(durl)
}
)
This is my Table where it have two column. First column used to list the jobs from MySQL database and the second used to view the selected row full details.
<table class="table1" width="100%" cellpadding="0" cellspacing="0" style="height: 100%; z-index:1; top:0; position: absolute;">
<tr>
<td width="30%" style=" min-width:40px;padding:0; background-color:rgba(255, 255, 255, 0.9); height: 100%; bottom: 0; top:0;" valign="top">
<div style="margin: 0; padding: 0; overflow-x:hidden; height: 100%; position: inherit; bottom: 0; top:0;">
<?php
require "module/call.php";
?>
</div>
</td>
<td width="60%" style="min-width:40px;padding:0; background-color:rgba(255, 255, 255, 0.9); height: 100%; bottom: 0; top:0;" valign="top"><div id="details" style="overflow:auto; width:100%; border-left-width: thin; border-right-width: 0; border-top-width: thin; border-bottom-width: 0; height: 100%; bottom: 0; top:0;"></div></td>
<td width="20%" style="padding:0;"> </td>
</tr>
</table>
This is the imageof the table
This is the call.php codes
<?php
$result = mysqli_query($conn,"SELECT * FROM job where approved='1' ORDER BY `CreatedTime` DESC");
echo "<table id='maintable' class='table-fill' border='0' cellpadding='0' cellspacing='0'>
<tr>
<th position='fixed' overflow='hidden' width='10%'>Job Title</th>
<th position='fixed' width='5%'>Company Name</th>
<th width='5%'>Closing Date</th>
</tr>";
while($row = mysqli_fetch_array($result) )
{
if (strlen($row['positiontitle']) > 20) $row['positiontitle'] = substr($row['positiontitle'], 0, 60) . "...";
echo "<tr onclick='get_data(123)' ref='job.details.php?id=".$row['id']."' target='content' class='positiontitle-link'>";
echo "<td data-id='<?php echo $row['id']?>'><font style='text-shadow: none;'>" . $row['positiontitle'] . "</font></a></td>";
echo "<td data-id='<?php echo $row['id']?>'>" . $row['companyname'] . "</td>";
echo "<td data-id='<?php echo $row['id']?>'>" . $row['closingdate'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($conn);
?>
and this is the details.php codes
<?php
$result = mysqli_query($conn,"SELECT * FROM job WHERE id = '".$_GET['id']."' ORDER BY `CreatedTime` DESC");
$jobdetails = mysqli_fetch_assoc($result);
echo ''.$jobdetails['positiontitle'].'';?>
</title>
</br>
<div style="width:100%; margin-top:-20px;">
<!-------------------------------------------Start of Right Sidebar---------------------------------------------------------------->
<div style="float:left; font-size: 14px; width:20%;"class="ara-form">
<header style="padding-top: 25px; font-size: 14px; color:#666666; padding-left:7px; padding-right:7px;">
<?php
$result = mysqli_query($conn,"SELECT * FROM job WHERE id = '".$_GET['id']."' ORDER BY `CreatedTime` DESC");
$jobdetails = mysqli_fetch_assoc($result);
echo '<strong>Job Title</strong><hr class="style-six"> '.$jobdetails['positiontitle'].'</p></br>';
echo '<strong>Company Name</strong><hr class="style-six"> '.$jobdetails['companyname'].'</p></br>';
echo '<strong>Location</strong><hr class="style-six"> '.$jobdetails['location'].'</p></br>';
echo '<strong>Closing Date</strong><hr class="style-six"> '.$jobdetails['closingdate'].'</p></br>';
echo '<strong>Number of Vacancy</strong><hr class="style-six"> '.$jobdetails['numberofvacancy'].'</p></br>';
echo '<strong>Job Category</strong><hr class="style-six"> '.$jobdetails['jobcategory'].'</p></br>';
echo '<strong>Duration</strong><hr class="style-six">'.$jobdetails['duration'].'</p></br>';
echo '<strong>Employment Type</strong><hr class="style-six"> '.$jobdetails['employmenttype'].'</p></br>';
echo '<strong>Salary</strong><hr class="style-six"> '.$jobdetails['salary'].'</p></br>';
echo '<strong>Timing</strong><hr class="style-six"> '.$jobdetails['timing'].'</p></br>';
echo '<strong>Nationality</strong><hr class="style-six"> '.$jobdetails['nationality'].'</p></br>';
echo '<strong>Gender</strong><hr class="style-six">'.$jobdetails['gender'].'</p></br>';
echo '<strong>Experience</strong><hr class="style-six">'.$jobdetails['experience'].'</p></br>';
echo '<strong>Education</strong><hr class="style-six"> '.$jobdetails['education'].'</p></br>';
echo '<strong>Gender</strong><hr class="style-six"> '.$jobdetails['gender'].'</p></br>';
echo '<strong>Gender</strong><hr class="style-six"> '.$jobdetails['gender'].'</p></br>';
?>
</header>
</div>
<!---------------------------------------------End of Right Sidebar------------------------------------------->
<div style="float:left; font-size: 14px; width:80%;" class="ara-form">
<fieldset style="font-size: 14px; color:#666666;">
<!-------------------------------------------------Start Time viewed Button------------------------------------------------>
<div style="width:100px; float:right; padding-left:2px; padding-top: 10px;">
<?php
include "module/button/job.views.php";
?>
</div>
<!---------------------------------------------------End Time viewed Button------------------------------------------------->
<!-----------------------------------------------Start Main Content----------------------------------------------->
<?php
echo '<p><strong>Company Background</strong><hr class="style-six"> '.$jobdetails['background'].'</p></br>';
echo '<p><strong>Job Summary</strong><hr class="style-six"> '.$jobdetails['summary'].'</p></br>';
echo '<p><strong>Job Duties and Responsibilities</strong><hr class="style-six"> '.$jobdetails['duty'].'</p></br>';
echo '<p><strong>Qualification</strong><hr class="style-six"> '.$jobdetails['qualification'].'</p></br>';
echo '<p><strong>Skills</strong><hr class="style-six"></br> '.$jobdetails['skill'].'</p></br>';
echo '<p><strong>Submission Guideline</strong><hr class="style-six"> '.$jobdetails['submission'].'</p></br>';
echo '<p><strong>Words to search this job</strong><hr class="style-six"> '.$jobdetails['search'].'</p></br>';
?>
<!-------------------------------------------------End Main Content----------------------------------------------->
</fieldset></div>
My Question is
1- I want to show the selected row id in the address bar
2- I want to show unclicked.php in the details div when no row selected
If you want to change the content of the address bar without refreshing the page, you'll either need to use the HTML5 History API or a hashbang URL.
HTML5 History API: This will allow you to change the content of the address bar to whatever you like, but the browser support is limited. An example is as follows:
history.pushState(null, "", "/test");
This will change the page URL to yoursite.com/test.
You can use this to add a row-related extension to the URL, eg. yoursite.com/table/row/20.
See here for a more in-depth explanation of how the API works.
Hashbang URL: This is a less clean solution, but is somewhat simpler and will work on all browsers. Your URL will look like yoursite.com/table#row20. (If you already have a # in the page URL, this will not work). Just call window.location = "#row20" to add #row20 to the current page URL.
If you are going to change the URL when a new row is selected, then you should also check the URL on page load and preselect a row if required. Eg. requesting yoursite.com/table#row20 would return the page with row 20 already selected.
$('#details').load('path/to/unclicked.php') will load the file's contents into the div. If you want this to occur on page load, just wrap it in a call to $(document).ready(). Simply make the AJAX request again if the user is able to deselect all rows.

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>

How can I pass the chosen value on a modal-box to PHP?

I've the code to initialize the modal-box:
<script>
var grid_modal_options = {
height: 'auto',
width: '80%',
modal: true
};
function showProductsModalBox() {
$("#products_modal_box").dialog(grid_modal_options);
$("#products_modal_box").parent().appendTo('form:first');
}
</script>
<div id="products_modal_box" title="Products" style="display: none;">
<div class="in">
<div class="grid-12-12">
<form id="products_modal_box_form" action="#" method="post">
<table>
<thead>
<tr>
<th> </th>
<th>Product</th>
</tr>
</thead>
<!-- Query for read mysql goes here (I skipped this line because it's not the main thing I'm gonna ask since it's run well) /-->
<tbody>
<?php
//read the results
while($fetch = mysqli_fetch_array($r)) {
print "<tr>";
print " <td><a href='#'>Choose</a></td>"; //--> How to return the value of $fetch[0]?
print " <td>" . $fetch[0] . "</td>"; //$fetch[0] == Product ID
print "</tr>";
}
?>
</tbody>
</table>
</form>
</div>
</div>
</div>
And:
<input type='text' id='products_id_textbox' name='products_id_textbox' />
<a href='#' onclick='showProductsModalBox(); return false;'>Choose products</a>
The code succeeds to show the modal box. But how to return the "Product" chosen by the user to the textbox "products_id_textbox"? Thanks.
add inline javascript:
<?php
while($fetch = mysqli_fetch_array($r)) {
print "<tr>";
print " <td>Choose</td>"; //--> How to return the value of $fetch[0]?
print " <td>" . $fetch[0] . "</td>"; //$fetch[0] == Product ID
print "</tr>";
}
?>
Instead using inline JS, you can write so (or something like this);
// php
while($fetch = mysqli_fetch_array($r)) {
print "<tr>";
print " <td><a rel='dialog' data-id='{$fetch[0]}'>Choose</a></td>";
print " <td>{$fetch[0]}</td>";
print "</tr>";
}
// js
$(document).ready(function(){
...
$("a[rel=dialog]").each(function(){
var id = this.getAttribute("data-id");
$('#products_id_textbox').val(id);
$('#products_modal_box').dialog('close');
});

onmouseover showing same data over all rows in table

im having trouble getting a popup using javascript to show table data onmouseover when mousing over images returned in a table from the DB, now the problem i have isnt with actualy getting the onmouseover working (a previous question solved that) but getting the data displayed onmouseover the change for each image moused over.
the query's im using works fine and and display the correct data but on the onmouseover only ever shows the data which should only show for the first row in the table, the 2nd and subsequent rows should show different data as the query calls (which works, just doesnt show onmouseover)
keep in mind this page is included in my index.php which has all my .js and .css calls
page code:
<table border='0' cellpadding='0' cellspacing='0' class="center2">
<tr>
<td width='60'><img src="images/box_tl.png"></td>
<td style="background: url(images/box_tm.png)" align="center"><img src="images/news.png"></td>
<td width='25'><img src="images/box_tr.png"></td>
</tr>
<tr>
<td style="background: url(images/box_ml.png)"><h2>.</h2></td>
<td style="background: url(images/box_mm.png)">
<?php
include 'connect.php';
$query = mysql_query("SELECT * FROM tbl_img") or die(mysql_error());;
echo "<table border='0' cellpadding='1' cellspacing='1' width'90%' id='1' class='tablesorter'><thead>";
echo "<tr> <th> </th> <th>Mob Name</th> <th>Id</th> <th>Health</th> <th>Body</th> <th>Effects</th> <th>Spawn</th></tr></thead><tbody>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $query )) {
$mob_id = $row['mob_id'];
$mob = $row['mob'];
$body = $row['body'];
$mob_name = $row['mob_name'];
$health = $row['health'];
$level = $row['level'];
// Print out the contents of each row into a table
echo "<tr><td>";
echo "<img src='/testarea/include/mobs/$mob' />";
echo "</td><td>";
echo $mob_name;
echo "</td><td>";
echo $level;
echo "</td><td>";
echo $health;
echo "</td><td>";
echo "
<a onmouseover='ShowPop()' href=''><img src='/testarea/include/mobs/dead/$body' /></a>
";
echo "
<div id='hidden-table' style='display:none;'>
<table border='0' cellpadding='0' cellspacing='0' class='center3'>
<tr>
<td width='14'><img src='images/info_tl.png'></td>
<td style='background: url(images/info_tm.png)' align='center'></td>
<td width='14'><img src='images/info_tr.png'></td>
</tr>
<tr>
<td style='background: url(images/info_ml.png)'><h2>.</h2></td>
<td style='background: url(images/info_mm.png)'>
";
$query2 = mysql_query("SELECT * FROM tbl_drop WHERE mob_name='$mob_name'") or die(mysql_error());
echo "<table border='0' cellpadding='1' cellspacing='1' width='250' id='2' class='tablesorter'><thead>";
echo "<tr> <th> </th> <th>Item Name</th> <th>Qty</th></thead><tbody>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $query2 )) {
$id = $row['id'];
$item_img = $row['item_img'];
$qty = $row['qty'];
$item_name = $row['item_name'];
// Print out the contents of each row into a table
echo "<tr><td width='50'>";
echo "<img src='/testarea/item/$item_img' />";
echo "</td><td width='150'>";
echo $item_name;
echo "</td><td width='50'>";
echo $qty;
echo "</td></tr>";
}
echo "</tbody></table>";
echo "
</td>
<td style='background: url(images/info_mr.png)'><h2>.</h2></td>
</tr>
<tr>
<td width='14'><img src='images/info_bl.png'></td>
<td style='background: url(images/info_bm.png)' align='center'><h2>.</h2></td>
<td width='14'><img src='images/info_br.png'></td>
</tr>
</table>
</div>"
;
echo "</td><td>";
echo "test";
echo "</td><td>";
echo "test";
echo "</td></tr>";
}
echo "</tbody></table>";
?>
</td>
<td style="background: url(images/box_mr.png)"><h2>.</h2></td>
</tr>
<tr>
<td width='60'><img src="images/box_bl.png"></td>
<td style="background: url(images/box_bm.png)" align="center"><h2>.</h2></td>
<td width='25'><img src="images/box_br.png"></td>
</tr>
</table>
</html>
popup.js code:
// create the popup box - remember to give it some width in your styling
document.write('<div id="pup" style="position:abolute; display:none; z-index:200;"></div>');
var minMargin = 15; // set how much minimal space there should be (in pixels)
// between the popup and everything else (borders, mouse)
var ready = false; // we are ready when the mouse event is set up
var default_width = 200; // will be set to width from css in document.ready
function ShowPop()
{
popup($('#hidden-table').html(), 400);
}
/* Prepare popup and define the mouseover callback */
jQuery(document).ready(function(){
$('#pup').hide();
css_width = $('#pup').width();
if (css_width != 0) default_width = css_width;
// set dynamic coords when the mouse moves
$(document).mousemove(function(e){
var x,y;
x = $(document).scrollLeft() + e.clientX;
y = $(document).scrollTop() + e.clientY;
x += 10; // important: if the popup is where the mouse is, the hoverOver/hoverOut events flicker
var x_y = nudge(x,y); // avoids edge overflow
// remember: the popup is still hidden
$('#pup').css('top', x_y[1] + 'px');
$('#pup').css('left', x_y[0] + 'px');
});
ready = true;
});
/*
The actual callback:
Write message, show popup w/ custom width if necessary,
make sure it disappears on mouseout
*/
function popup(msg, width)
{
if (ready) {
// use default width if not customized here
if (typeof width === "undefined"){
width = default_width;
}
// write content and display
$('#pup').html(msg).width(width).show();
// make sure popup goes away on mouse out
// the event obj needs to be gotten from the virtual
// caller, since we use onmouseover='popup(msg)'
var t = getTarget(arguments.callee.caller.arguments[0]);
$(t).unbind('mouseout').bind('mouseout',
function(e){
$('#pup').hide().width(default_width);
}
);
}
}
/* Avoid edge overflow */
function nudge(x,y)
{
var win = $(window);
// When the mouse is too far on the right, put window to the left
var xtreme = $(document).scrollLeft() + win.width() - $('#pup').width() - minMargin;
if(x > xtreme) {
x -= $('#pup').width() + 2 * minMargin;
}
x = max(x, 0);
// When the mouse is too far down, move window up
if((y + $('#pup').height()) > (win.height() + $(document).scrollTop())) {
y -= $('#pup').height() + minMargin;
}
return [ x, y ];
}
/* custom max */
function max(a,b){
if (a>b) return a;
else return b;
}
/*
Get the target (element) of an event.
Inspired by quirksmode
*/
function getTarget(e) {
var targ;
if (!e) var e = window.event;
if (e.target) targ = e.target;
else if (e.srcElement) targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;
return targ;
}
All of the hidden tables have the same id, but IDs have to be unique.
provide the link as argument to ShowPop()
<a onmouseover='ShowPop(this)' ....>
then you'll be able to access the intended target inside ShowPop():
function ShowPop(o)
{
popup($(o).next('div').html(), 400);
}
Edit:
Regarding to the comment:
Currently I think the popup will not disapear onmouseout in any browser(except IE), because you didn't provide an argument to ShowPop() , what in other browsers is needed to return anything from getTarget, because they didn't know window.event.
Change this line:
var t = getTarget(arguments.callee.caller.arguments[0]);
to
var t = arguments.callee.caller.arguments[0];
...because when you take on my suggestion the link is already provided as argument to ShowPup(), there is no need to call getTarget() .

Categories