For my new project i want the so modern approach of not needing to reload a page on every database request. :) I want the script to query the database and create a table with the query information.
I have tried different scripts i have found on the internet. The one below was closest to my needs.
index.php
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>
<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
<title>Display Page</title>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<script language='JavaScript' type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script>
</head>
<body>
<button type='button' name='getdata' id='getdata'>Get Data.</button>
<div id='result_table'>
</div>
<script type='text/javascript' language='javascript'>
$('#getdata').click(function(){
$.ajax({
url: 'getdata.php',
type:'POST',
dataType: 'json',
success: function(output_string){
$('#result_table').append(output_string);
} // End of success function of ajax form
}); // End of ajax call
});
</script>
</body>
</html>
getdata.php
<?php
include('conn.inc.php');
//Query of facebook database
$facebook = mysql_query('SELECT * FROM users')
or die(mysql_error());
//Output results
if(!$facebook)
{
mysql_close();
echo json_encode('There was an error running the query: ' . mysql_error());
}
elseif(!mysql_num_rows($facebook))
{
mysql_close();
echo json_encode('No results returned');
}
else
{
$output_string = '';
$output_string .= '<table border="1">';
while($row = mysql_fetch_assoc($facebook))
{
$output_string .= '<tr>';
foreach($row as $value)
{
$output_string .= '<td>{$value}</td>';
}
$output_string .= '</tr>';
}
$output_string .= '</table>';
}
mysql_close();
// This echo for jquery
echo json_encode($output_string);
?>
But i only get a table with a bunch of {$value} inside the table. I've tried with only $value but got a bunch of zeros.
I tried a simple script
$query = "SELECT users_name, users_password FROM users WHERE users_name = 'name'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
echo $row['users_name'];
And then i get som results but with this script i have to refresh the page on every search. To be clear i want to be able to create a table with the information from a mysql database and display it on screen with reloading the page.
Any ideas?
You should just use $value instead of {$value}. You don't need another foreach loop inside the while loop.
$output_string = '';
$output_string .= '<table border="1">';
while($row = mysql_fetch_assoc($facebook))
{
$output_string .= '<tr>';
$output_string .= '<td>'.$row['Your table column name here'].'</td>';
$output_string .= '</tr>';
}
$output_string .= '</table>';
Instead of
$output_string .= '<td>{$value}</td>';
try
$output_string .= "<td>{$value}</td>";
i.e. replace the single quotes with double quotes.
See the doc here, which says:
When a string is specified in double quotes ... variables are parsed within it.
and
variables ... will not be expanded when they occur in single quoted strings.
You may invert the logic, and do it on client side, using a library that does that automatically, like http://phery-php-ajax.net
Instead of creating the table on the server side, send it as JSON to the browser, which is faster, and build your table:
Phery::instance()->set(array(
'load' => function(){
/* rest of mysql code */
$rows = array();
while($row = mysql_fetch_assoc($facebook)) { $rows[] = $row; }
return PheryResponse::factory()->json($rows);
})->process();
then in the client side inside $(function(){});
$(function(){
var $result_table = $('#result_table');
$result_table.phery('make', 'load');
$result_table.bind('phery:json', function(e, data){
var $this = $(this);
for (var i = 0; i < data.length; i++) {
$this.append($('<tr/>', {
'html': '<td>' + data[i].row_name + '</td>'
}));
}
});
$result_table.phery('remote');
});
100% WORKING
Just remove closing tags. E.g when opening a tag and store it in $output_string NEVER include the closing part...
Then don't include $value in quotation marks...
Put it outside quotation mark and then separate $value and closing quotation mark with dot the semi colon.
Related
I have created a drop down menu in php that is displayed however, when a value has been clicked, I don't know how to collect this information.
<html>
<body>
<?php
$mydb = new mysqli('localhost','root','','TestTimeTableSolution');
$rows = $mydb->query("SELECT DISTINCT TeacherID FROM Teacher;")->fetch_all(MYSQLI_ASSOC);
$teachers = array();
foreach ($rows as $row) {
array_push($teachers, $row["TeacherID"]);
}
$dropdownMenu = "<select name='TeacherID' form='Teacher'><option value='Null' selected>All</option>";
foreach ($teachers as $topic) {
$dropdownMenu .= "<option value='" . $topic . "'>" . $topic . "</option>";
}
$dropdownMenu .= "</select>";
echo $dropdownMenu;
?>
</body>
</html>
Based on your last comment, "i want it to be dynamic so as soon as the user clicks on something the relevant information will pop up", it sounds like you will probably want to use Ajax/JavaScript (I will demonstrate a simple jQuery example, notating for clarity):
<?php
$mydb = new mysqli('localhost','root','','TestTimeTableSolution');
?>
<html>
<!-- Add the jQuery library -->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
// Act when the document is ready
$(function(){
// listen for the select to change
$('select[name=TeacherID]').on('change',function(){
// Run the ajax – you can also use the shortcut $.post method found at:
// https://api.jquery.com/jquery.post/
$.ajax({
// This is the page that is going to do the data lookup/display action
url: '/lookup.php',
// This is how it's sending the data to that page
type: 'post',
// This is what is being sent ($_POST['submit'] in this case)
data: {
// Use $(this) to isolate the current selected element and get value (.val())
// The value is represented as $topic in your php
'submit': $(this).val()
},
// If all goes well and the page (lookup.php) returns a response
success: function(response) {
// Place the response into the div (see html snippet)
$('#loadspot').text(response);
}
});
});
});
</script>
<body>
<?php
$rows = $mydb->query("SELECT DISTINCT TeacherID FROM Teacher;")->fetch_all(MYSQLI_ASSOC);
$teachers = array();
foreach ($rows as $row) {
array_push($teachers, $row["TeacherID"]);
}
$dropdownMenu = "<select name='TeacherID' form='Teacher'><option value='Null' selected>All</option>";
foreach ($teachers as $topic) {
$dropdownMenu .= "<option value='" . $topic . "'>" . $topic . "</option>";
}
$dropdownMenu .= "</select>";
echo $dropdownMenu;
?>
<!---------------------------------------------->
<!-- THIS IS WHERE THE CONTENT WILL LOAD INTO -->
<!---------------------------------------------->
<div id="loadspot"></div>
</body>
</html>
In order for this to work, you need the page lookup.php in the domain root (you can make it whatever/where ever you want, but you need to match in the javascript url):
/lookup.php
<?php
# This is what will get placed into the parent page <div id="loadspot"></div>
# Do you your php here in place of this line and return whatever "relative information" you want
print_r($_POST);
You should review the jQuery page I have linked to to get more information and direction for that library and make sure you use your browser's developer tools to monitor javascript errors in the console. Ideally, you want to understand all this via the documentation instead of just copy and paste and move on...
I'm currently having 2 pages that is "index.php", "retrieve_search_forklift.php" and "search_forklift.php".
I try to passing the "txtSearch" input from index.php using jQuery $.post method to "retrieve_search_forklift.php" for execute the select query and echo the $output.
In "search_forklift.php" will use a function to load the "retrieve_search_forklift.php" when page is load and display the $output in a table.
Index.php
$('#txtSearch').keydown(function(e) {
var code = (e.keyCode || e.which);
if((code == 13)){
txtSearch = $('#txtSearch').val();
$.post('php/retrieve_search_forklift.php',{
txtSearch : txtSearch
},
function(data){
//alert(data);
window.location.replace("search_forklift.php");
})
}
});
Retrieve_search_forklift.php
<?php
require('../database_connection.php');
if($txtSearch = $_POST['txtSearch']){
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "SELECT f_brand, f_ftype, f_image, f_code, f_description, f_sale, f_rental FROM tblforkliftdetail WHERE f_brand='Toyota'";
$result = mysqli_query ($mydatabase, $query);
$counter = 0;
while($info = mysqli_fetch_array( $result ))
{
if( $counter % 3 == 0 )
$output .= "<tr>";
$output .= "<td style='background-color:yellow; '><img src=".$info['f_image'] ." width=210px height=210px ></img></p></td>";
$output .= "<td style='background-color:black;'>";
$output .= "</td>";
if( $counter % 3 > 1)
$output .= "</tr>";
$counter++;
}
echo $output;
}
#mysqli_close($mydatabase);
?>
Search_forklift.php
$(document).ready(function(){
loadsearchtblForklift();
});
function loadsearchtblForklift(){
$('#tblsearchForklift').load('php/retrieve_search_forklift.php');
}
<table id="tblsearchForklift">
<tbody>
</tbody>
</table>
I shall simplify this.
You are making a request from A to B; then asking C to show the data that B has generated earlier. This boy, is not possible unless you store the data of B somewhere(DB/file system).
why?
A --> B is a separate request and C --> B is separate. The server does not know that it has to store the data for future request use. You have to change the approach to fulfill this logic.
My Suggestion -
Discard 'Search_forklift.php' and directly show the results in the 'index.php' page directly.
changed index.php file
$('#txtSearch').keydown(function(e) {
var code = (e.keyCode || e.which);
if((code == 13)){
txtSearch = $('#txtSearch').val();
$.post('php/retrieve_search_forklift.php',{
txtSearch : txtSearch
},
function(data){
$('#tblsearchForklift').html(data);
})
}
});
<table id="tblsearchForklift">
<tbody>
</tbody>
</table>
Or, store the result of 'Retrieve_search_forklift.php' in a txt file or into a CLOB column in database with a session key and retrieve it using the same key to display in the 'Search_forklift.php'.
This approach shall ensure that, the person after you who is going to curse everyday of their life maintaining it. May be you yourself may do that after an year or two. :) Don't get me wrong here. but i just want to make you understand the way web and programming life works.
EDIT: reading again, i got another approach (bad) idea. You can do this in one more way.
Once your ajax call in index.php is returned, POST the results to the 'Search_forklift.php' page and in there just say
<table id="tblsearchForklift"><?php echo $_POST[results]; ?></table>
ok so I have this in my HTML code:
<script type="text/javascript" src="load2.php"> </script>
I saw somewhere you could call a php file like that and the javascript contained in it will be rendered on the page once echoed.
So in my PHP file i have this:
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$storeArray[] = $row['DayNum']; }
$length = count($storeArray);
I connected to my database and stuff and pulled those records and stored them in an array. Now my problem is alerting them using js. This is what I have:
echo " function test() {
for(var i = 0; i<$length; i++){
alert($storeArray[i]);
}
}
";
The test() function is being onloaded in my HTML page, but for nothing the values in the array won't alert. Any help please?
echo " function test() {
for(var i = 0; i<$length; i++){
alert($storeArray[i]);
}
}
";
This code is literally writing what you have written above. It's not completely clear, but I believe your intent is to loop over the contents of your database data, and alert that to the browser with alert() function.
You can achieve this in a couple of ways.
Write multiple alert statements
echo "function test() {"; //Outputting Javascript code.
for($i = 0; $i<$length; $i++){ //Back in PHP mode - notice how we aren't inside of a string.
$value = $storeArray[$i];
echo "alert($value)"; //Outputting Javascript code again.
}
echo "}"; //Outputting Javascript code to close your javascript "test()" function.
Write a Javascript array, then loop over it in Javascript
echo "function test() {";
echo " var storeArray = ['" . implode("','", $storeArray) . "'];";
echo " for (var i = 0; i < storeArray.length; i++) {";
echo " alert(storeArray[i]);";
echo " };";
echo "}";
Finally, you could use AJAX and JSON to load the data, rather than outputting a JS file from PHP. That is an entirely different topic, though, and you should search StackOverflow for more examples as there are numerous questions and answers involving it.
Unless your array contains only number, you probably have JS error. You should put your $storeArray[i] in quotes in the alert function so it considered as a string in js.
alert('$storeArray[i]');
Once printed out, the JS will look something like this
alert('foo');
alert('bar');
Whereas with your code, it would've printed it like this
alert(foo);
alert(bar);
in your php file include load2.php
header("Content-Type: text/javascript");
in the in the top. so your browser get what it wants.
$i=0;
$storeArray = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$storeArray[$i] = $row['DayNum'];
$i++;
}
echo "var arr = Array();";
echo "function test() {";
foreach ($storeArray as $key=>$item) {
echo "arr[".$key."] = ".$item.";";
}
echo "}";
echo "alert(arr);";
actually you can comment out the two echos containing the <script></script> part when including the file as <script src="load2.php" type="text/javascript" ...
I am unsure of what path I should take for what I am wanting to do. The page loads some data from a mysql database with php. I made it so that a check box is generated with an incremented value starting wit 0 and so on for every value it finds in the database. What I am wanting to do is have that check box be so that when it is checked and they push the trashcan icon it will delete that row from the database. Where I am unsure is how to go about deleting it on button click and then reload the page. What would be the best way to do this? I am not needing the code or anything I just cant think of the best path to take to accomplish this.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Print Run</title>
<style type="text/css">
.openRun{
width:500px;
}
.openRun th{
text-align:center;
background-color:#CCC;
}
</style>
</head>
<body>
<div>
<?php
$totals = 0;
$i = 0;
$companyName = "";
$quantity = "";
$cardSize = "";
$dateAdded = "";
require("serverInfo.php");
$printRun = mysql_query("SELECT * FROM `printRun` WHERE status = 'Open'");
$row = mysql_fetch_array($printRun);
echo 'Print Run #: ' . $row['Run'];
$result = mysql_query("SELECT * FROM `printRun` WHERE status = 'Open'");
while($row = mysql_fetch_array($result)){
$companyName[$i] = $row['Company'];
$quantity[$i] = $row['Quantity'];
$cardSize[$i] = $row['Size'];
$dateAdded[$i] = $row['Date'];
$totals = intval($row['Quantity']) + $totals;
$i++;
}
$arraySize = count($companyName);
echo '<table class="openRun">';
echo '<tr><th>Company</th><th>Quantity</th><th>Size</th><th>Date Added</th><th></th></tr>';
for($i = 0; $i < $arraySize; $i++){
echo '<tr>';
echo '<td>' . $companyName[$i] . "</td>";
echo '<td>' . $quantity[$i] . "</td>";
echo '<td>' . $cardSize[$i] . "</td>";
echo '<td>' . $dateAdded[$i] . "</td>";
echo '<td><input type="checkbox" name="box'. $i .'" value="'. $i .'" /></td>';
echo '</tr>';
}
echo '<tr>';
echo '<td style="font-weight:bold; border-style:solid; border-top-width:1px;">Totals</td>';
echo '<td style="font-weight:bold; border-style:solid; border-top-width:1px;">' . $totals . "</td>";
echo '<td></td>';
echo '<td></td>';
echo '<td><img src="images/trash.png" /></td>';
echo '</tr>';
echo '</table>';
mysql_close($link);
?>
<br />
</div>
</body>
</html>
There's two ways of doing this. If you're not familiar with AJAX, or are scared about engaging with it, I'd suggest having a quick read of this tutorial just to get an overview.
With AJAX
If you don't want the page to reload, you're going to need to use AJAX to asynchronously send and receive data from the server. A typical example would be:
$('.trash_link').on('click', function() {
$.ajax({
url: 'path/to/script.php',
data: 'variable='+$('.input_class').val(),
dataType: 'html',
success: function(response) {
$('.container').html(response);
}
});
});
The crucial thing I'd advise is to put all of your layout logic in a controller or model function so that you don't repeat yourself. When data is sent to your server it can use this function to send back all your layout via the AJAX function. You can then insert the HTML inside your container element.
Without AJAX
All you do here is submit a form and your page reloads. For that reason you need to make sure you've already specified tags on your page. It really depends on what style you want your page to have - some people prefer reloads, some prefer the seamlessness of AJAX. Here is what you'd need if you chose to omit AJAX:
$('.trash_link').on('click', function() {
$('form').submit();
});
You can also add a pop-up confirmation if you want to:
$('.trash_link').on('click', function() {
if(confirm("Are you REALLY sure?") {
$('form').submit();
}
});
If you have an identifier in the table structure, you can just put
<input type='checkbox' name='ids[]' value='<?php echo $row['id']; ?>' />
Against every line of your table. Wrap the whole table in a form, make a submit button, in your script put something along these lines
if (isset($_POST['ids']) && is_array($_POST['ids'])) {
// some input sanitizing required.
$ids = array();
foreach ($_POST['ids'] as $id) if (intval($id) > 0) $ids[] = intval($id);
// $ids now hold the identifiers for the records to be deleted
if (count($ids)) $query = mysql_query("DELETE FROM `printRun` WHERE id IN (" . implode(', ', $ids) . ")");
// Then make a page refresh via HTTP 303 or otherwise to keep
// to the POST-redirect-GET policy.
header("HTTP/1.1 303 See Other");
header("Location: http://whate.ver/your_page_is.php");
}
If you just want a trash can that when clicked on, reloads the page and deletes the item, then just have that image in a link that passes along the id or whatever unique identifier the row has.
Delete
Have it hit a new php file that handles pulling off the unique identifier and deleting the record, then forwards back to the listing page.
$recordToDelete = is_numeric($_GET['id']) ? $_GET['id'] : null;
if($recordToDelete != null) {
$sql = "DELETE FROM `printRun` WHERE id = " . $recordToDelete;
//execute sql
}
//redirect back to listing page
header('Location: /yourpage.php');
I'm making a table of games and times but I want to use javascript to show/hide part of the list. Once 5 games have been listed, all the games following that are to be encompassed within the div that will be showed/hidden by hitting a button. The trouble is, my div does not encompass ANY of the rows of the table, which is weird because the code says otherwise.
Am I not allowed to make a div that encompasses part of a table?
Thanks as always.
<table>
<?php
$result = #mysql_query('QUERY REMOVED');
$rows = mysql_num_rows($result);
$count = 0;
if ($rows == 0) {
echo '<h3> No games on this day </h3>';
} else {
while ($row = mysql_fetch_array($result)) {
**a bunch of variable assignments**
if($count == 5) echo '<tbody class="moreLess">';
echo '<tr><td>' . $awayteam . ' # ' . $hometeam . '</td><td>' . $time . '</td></tr>';
$count++;
}
if($count >= 6) echo '</tbody>';
}
?>
</table>
<div class="moreLessSwitch"><span>More [+]</span></div>
In case you wanted it, the javascript I use (tested and working)
$(function() {
$(".moreLess").hide();
$(".moreLessSwitch").toggle(function() {
$(this).html("<span>Less [-]</span>");
$(this).prevAll(".moreLess").slideDown();
}, function() {
$(this).html("<span>More [+]</span>");
$(this).prevAll(".moreLess").slideUp();
});
});
The table output HTML: http://pastebin.com/raw.php?i=99iUYq6j
No, a div can't exist between the table and tr tags.
However, you can (and should) use a tbody to delineate groups of tr.
Check out this fiddle.
[edit]
New fiddle.
tbody is correct way to define group of rows...
This test code works for me:
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="../jquery/jquery.js"></script>
<script type="text/javascript">
$(function(){
$(".moreLess").hide();
$(".moreLessSwitch").toggle(function() {
$(this).html("<span>Less [-]</span>");
$(".moreLess").slideDown();
}, function() {
$(this).html("<span>More [+]</span>");
$(".moreLess").slideUp();
});
})
</script>
</head>
<body>
<table>
<?php
$rows = array(array(1,2,3),array(1,2,3),array(1,2,3),array(1,2,3),array(1,2,3),array(1,2,3),array(1,2,3),array(1,2,3),array(1,2,3),array(1,2,3));
$count = 0;
if ($rows == 0) {
echo '<h3> No games on this day </h3>';
} else {
while ($row = array_pop($rows)) {
//**a bunch of variable assignments**
if($count == 5) echo '<tbody class="moreLess">' . "\r\n";
echo '<tr><td>' . $awayteam . ' # ' . $hometeam . '</td><td>' . $time . '</td></tr>' . "\r\n";
$count++;
}
if($count >= 6) echo "</tbody>\r\n\r\n";
}
?>
</table>
<div class="moreLessSwitch"><span>More [+]</span></div>
</body>
</html>
Your HTML is invalid. A <div> cannot occur inside a <table> unless inside a <td> cell, while yours spans several <tr> rows. A better solution would be to assign the .moreLess class to the table rows:
<tr class='moreLess'>
Your jQuery function then slides the table rows in and out of view.