I have this function that gets a table from another site by finding each row of that table and, providing that row isn't a duplicate, echos it to my site. I want to add my own row to the bottom though so I thought it would be as simple as just echoing
<tr><td>TEXT</td></tr>
as you can see below. But when I load the page, this row isn't added. Anyone know what the cause may be?
Here is the website if that helps.
function getStats(){
$page = file_get_html(getPageURL());
$rows = array();
echo "<table id=statsTable>";
foreach($page->find('html/body/div/div[1]/center/table/tbody/tr[1]/td/table/tbody/tr/td[2]/table/tbody/tr/') as $key=>$element) {
if(!in_array($element, $rows)){
$rows[$key]=$element;
echo $rows[$key-1];
}
}
echo "<tr><td>Viewing old updates will be added soon</td></tr></table>";
}
Main problem was in key offset, when you work with arrays it's better to use keys in this case. So in order to that I've changed the in_array to array_key_exists, because we want to check if key exists, but if you want to work with element you have to know its key.
function getStats(){
$page = file_get_html(getPageURL());
$rows = array();
echo "<table id=statsTable>";
foreach($page->find('html/body/div/div[1]/center/table/tbody/tr[1]/td/table/tbody/tr/td[2]/table/tbody/tr/') as $key => $element) {
if(!array_key_exists($key, $rows)){
$rows[$key] = $element;
/* Echo only when it exists */
if(array_key_exists($key-1, $rows)){
echo $rows[$key-1];
}
}
}
echo "<tr><td>Viewing old updates will be added soon</td></tr></table>";
}
?>
<?php
include "getData.php";
include "simple_html_dom.php";
?>
<!DOCTYPE HTML>
<html>
<head>
<title>KSA Flight Tracker</title>
<link rel="stylesheet" type="text/css" href="KSAStyle.css"/>
</head>
<body>
<div id="page">
<div id="leftPanel">
<p id="missionsHeader">Active Missions</p>
<?php getList(); ?>
</div>
<div id="mainPanel">
<p id="infoHeader">
<?php getTitle(); ?>
</p>
<div id="info">
<center>
<?php
getInfo();
getImage();
getMap();
getStats();
?>
</center>
</div>
</div>
</div>
</body>
</html>
Related
I want to only display an item once in my PHP loop. So if there's multiple values which are the same in $item['name'], it should only display it 1 time.
This is my loop:
<?php
while ($item = $stmt->fetch(PDO::FETCH_ASSOC)) {
?>
<li>
<i class="fa fa-archive"></i>
<h5><?php echo $item['name']; ?></h5>
<h3><?php echo $item['displayname']; ?></h3>
Download
<div class="clearfix"></div>
</li>
<?php
}
?>
But I have no idea how I would hide the other items with the same name. I also can't find any info about this on Google (or I'm using the wrong search terms?). Hope someone got a suggestion for me!
$array=array();
foreach ($item['name'] as $i) {
if (!in_array($i, $array)) {
$array[] = $i;
}
}
print_r($array);
<?php
// Produce your prepared statement $stmt here...
// The list of unique item names.
$itemNames = array();
// The list of items to be displayed on screen.
$displayItems = array();
while ($item = $stmt->fetch(PDO::FETCH_ASSOC)) {
$itemName = $item['name'];
if (!in_array($itemName, $itemNames)) { // If item name not already appended to the unique names list.
// Append item name to the unique names list.
$itemNames[] = $itemName;
// Append item to the list of displayable items.
$displayItems[] = $item;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Demo</title>
<!-- Css/Js resources -->
</head>
<body>
<ul id="items">
<?php
foreach ($displayItems as $item) {
$name = $item['name'];
$displayName = $item['displayname'];
$downloadUrl = $item['downloadurl'];
?>
<li>
<i class="fa fa-archive"></i>
<h5>
<?php echo $name; ?>
</h5>
<h3>
<?php echo $displayName; ?>
</h3>
<a href="<?php echo $downloadUrl; ?>" class="btn btn-default pull-right">
Download
</a>
<div class="clearfix"></div>
</li>
<?php
}
?>
</ul>
</body>
</html>
Note:
I always maintain the code responsible for db data access on the upper part of the page. So, for example, if I need to fetch data from db, I save it into arrays. Later, in order to bring that data in html constructs, I work just with them, without having to mix data access commands like
while ($item = $stmt->fetch(PDO::FETCH_ASSOC)) {...}
with html code. Therefore gaining (highly) increased code readability. When you create a lot of files in this way, the advantages will become obvious.
There are also (rare) disadvantages though, like the one arised here: in order to avoid mixing the db codes with the html code, I had to apply an extra array iteration: the one for building the $displayItems array.
Otherwise, if you want to use your approach, then the solution would be:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Demo</title>
<!-- Css/Js resources -->
</head>
<body>
<ul id="items">
<?php
// Produce your prepared statement $stmt here...
// The list of unique item names.
$itemNames = array();
while ($item = $stmt->fetch(PDO::FETCH_ASSOC)) {
$name = $item['name'];
if (!in_array($name, $itemNames)) { // If item name not already appended to the unique names list.
// Append item name to the unique names list.
$itemNames[] = $name;
$displayName = $item['displayname'];
$downloadUrl = $item['downloadurl'];
?>
<li>
<i class="fa fa-archive"></i>
<h5>
<?php echo $name; ?>
</h5>
<h3>
<?php echo $displayName; ?>
</h3>
<a href="<?php echo $downloadUrl; ?>" class="btn btn-default pull-right">
Download
</a>
<div class="clearfix"></div>
</li>
<?php
}
}
?>
</ul>
</body>
</html>
Good luck.
Are you trying to do something like this? If I am understanding correctly, I think you are trying to do the same thing I was.
Other people gave you good solutions to solve your issue, but this thing is going to cost you more processing time through your app run-time.
You can use DISTINCT keyword in your sql select query so automatically you will get the name just once.
Chick this tutorial:
https://www.w3schools.com/sql/sql_distinct.asp
I have a list of names in a database that i want to display one by one
(also for bonus points, another column in the database is a Boolean value for if a task is completed or not. if this is true i want the css content box background to be green instead of red.)
so how can i select a name from row one, put it to a PHP variable, then select the value from the "Name" column in row 2 and put that to another PHP variable or the next item in the array?
thanks for any help!
<html>
<head>
<title>Title</title>
<link rel="stylesheet" type="text/css" href="mngPWinCSS.css"/>
</head>
<body>
<?php
$dsn ='mysql:host=****.******.com;dbname=o****_**n';
$username='********';
$password ='******';
mysql_connect('localhost',$username,$password);
$query=mysql_query("SELECT Name FROM CLOAS_Team LIMIT 0,1");
$bob="dkajfk";
$url=$_SERVER['REQUEST_URI'];
header("Refresh: 60; URL=$url");
$com[1]="i";
$com[2]="i";
$com[3]="i";
$com[4]="i";
$com[5]="i";
$com[6]="i";
$name=mysql_fetch_array($query);
?>
<div id="content">
<img src="logjpg.JPG" alt="Smiley face" height="50" width="200">
<h3>CLOAS Tracker</h3>
</div>
<div id="Content">
<?php
?>
<div id="complete">
<h3names>
<?php
echo $name['Name'];
?>
</h3names>
</div>
<div id="incomplete">
<h3names>Name2</h3names>
</div>
</div>
</body>
</html>
First you need to change your SELECT query to select all of the rows that you wish to display, perhaps by taking off the LIMIT clause. Something like this;
$result=mysql_query("SELECT Name FROM CLOAS_Team");
(This will get you all of the names in your table.)
Next, you need to loop through the results you got from this query, like so;
$names = array();
while($row = mysql_fetch_assoc($result))
{
$names[] = $row['Name'];
}
This will put them into the array $names for you, which you can then work with. Instead of putting them into the array, you might want to output them immediately, perhaps like this;
while($row = mysql_fetch_assoc($result))
{ ?>
<div>
<h3>
<?php
echo $row['Name'];
?>
</h3>
</div>
<?php } ?>
However, you have many more errors in your code. Such as;
You can't just invent html elements called <h3names>
I doubt that you want to set the id attribute to 'incomplete'. An id should be unique, I expect you should be putting this in as a class (class = "incomplete")
I don't think your line header("Refresh: 60; URL=$url"); will do anything as your headers have already been sent to the page. If you want this line to work, it needs to be right at the top, BEFORE any output has been sent to the browser.
And for the bonus point, include the 'Completed' field in your query (if that is what it is called) and use this to add a style to each <div> element that you display in your loop. So your query might become;
$result=mysql_query("SELECT Name, Completed FROM CLOAS_Team");
And your loop would now be like this;
while($row = mysql_fetch_assoc($result))
{ ?>
<div style = "background-color:<?php echo $row['Completed'] == true ? 'green' : ' red'; ?>">
<h3>
<?php
echo $row['Name'];
?>
</h3>
</div>
<?php } ?>
So I'm trying to make a page where i can display results from my database table. You should be able to search and there should be some pagination as there are thousands of results.
I've managed to make a page which just has the search, and works perfect. So now i need to know how would would integrate some pagination into that.
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="container">
<form action="" method="get">
<input type="text" name="search" id="search" placeholder="Search" />
<input type="submit" />
</form>
<?php include 'process.php'; ?>
</div> <!-- /container -->
<script src="js/jquery.js"></script>
<script src="js/script.js"></script>
</body>
</html>
process.php
<?php include 'dbconfig.php'; ?>
<?php include 'connect.php'; ?>
<?php
$search = $_GET['search'];
$result = mysql_query("SELECT * FROM oantkb WHERE Name LIKE '%$search%' ORDER BY `INDEX` DESC");
echo '<table class="table">';
echo '<thead>';
echo '<tr>';
echo '<th>#</th>';
echo '<th>Pic</th>';
echo '<th>Name</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
while($row = mysql_fetch_assoc($result)) {
$pic = $row['Pic'];
$name = $row['Name'];
echo '<tr>';
echo '<td>#</td>';
echo '<td><img src="'.$pic.'" height="50" width 50"></td>';
echo '<td>'.$name.'</td>';
echo '</tr>';
}
echo '</tbody>';
echo '</table>';
?>
Right now it works like it should. When i search it will say index.php?search=banana, but i need some pagination added so it will say for example index.php?search=banana&?page=2. Or something along those lines. Hope it makes sense...i'm a php newb :)
Include at the end of your sql query the following:
$resultsPerPage=10;
$page = ($_GET["page"]-1)*$resultsPerPage;
$query = $query." LIMIT $page,$resultsPerPage";
mysql_query($query);
By the way the mysql_ library is deprecated in favor of mysqli.
Also the above is susceptible to sql injection attacks because $_GET["page"] isn't first sanitized, but for simplicity I did it this way.
This assumes a paging scheme that starts at 1.
i've been using Pear Pagination for a long time. you can try it.
here is a good tutorial for setting it up
Simple Pagination in PHP tutorial
a good thing to add is clean your variable before using them in your query.
I would like to ask some help and ideas on how to implement a loop inside the template. I can do foearch below but how can i include it to the template and show it in the results.
foreach($results as $row) {
$name = $row['name'];
$address = $row['address'];
}
What i want to achieve the results is something like below and how do I put the $template->publish(); in a variable so I can use it to store that data to the DB. thanks a lot.
<html>
<head>
<title>My Template Class</title>
</head>
<body>
<table><tr>
<td>
<h3>Hello William!</h3>
<p>The time is: 03/10/04</p>
<p>Embedded PHP works too!</p>
<p>Name goes here</p>
<p>Address goes here </p>
</td>
<td>
<h3>Hello William!</h3>
<p>The time is: 03/10/04</p>
<p>Embedded PHP works too!</p>
<p>Name goes here</p>
<p>Address goes here </p>
</td>
<td>
<h3>Hello William!</h3>
<p>The time is: 03/10/04</p>
<p>Embedded PHP works too!</p>
<p>Name goes here</p>
<p>Address goes here </p>
</td>
</tr>
</table>
</body>
</html>
The template class
<?
class Template {
public $template;
function load($filepath) {
$this->template = file_get_contents($filepath);
}
function replace($var, $content) {
$this->template = str_replace("#$var#", $content, $this->template);
}
function publish() {
eval("?>".$this->template."<?");
}
}
?>
The template design.html
<html>
<head>
<title>#title#</title>
</head>
<body>
<h3>Hello #name#!</h3>
<p>The time is: #datetime#</p>
<? echo "<p>Embedded PHP works too!</p>"; ?>
</body>
</html>
the index.php
<?
include "template.class.php";
$template = new Template;
$template->load("design.html");
$template->replace("title", "My Template Class");
$template->replace("name", "William");
$template->replace("datetime", date("m/d/y"));
$template->publish();
?>
PHP itself is as good at templates as any other engine.
No need anything else
$pagetitle = "My Template Class";
foreach($results as $row) {
$row['date'] = date("m/d/y");
$data[] = $row;
}
$data = chunk_split($data,3);
Then in template
<html>
<head>
<title><?=$pagetitle?></title>
</head>
<body>
<table>
<?php foreach ($data as $chunk): ?>
<tr>
<?php foreach ($chunk as $row): ?>
<td>
<h3>Hello <?=$name?>!</h3>
<p>The time is: <?=$date?></p>
<p>Embedded PHP works in the template</p>
<p><b>But embed PHP in the data is a VERY BAD IDEA</b></p>
<p><?=$address?></p>
</td>
<?php endforeach ?>
</tr>
<?php endforeach ?>
</table>
</body>
</html>
I made your example a bit more complicated yet closer to the real life.
It will print your table in the rows by 3 columns in each
Just don't re-invent the wheel, PHP works wonderfully as a templating language:
The template class
<?
class Template
{
private $template;
private $vars;
function load($filepath) {
$this->template = $filepath;
}
function replace($var, $content)
{
$this->vars[$var] = $content;
}
function publish()
{
extract($this->vars);
include($this->template);
}
}
?>
The template design.phtml
<html>
<head>
<title><?php echo $title ?></title>
</head>
<body>
<?php foreach($rows as $row) { extract($row); ?>
<h3>Hello <?php echo $name; ?></h3>
<p>The time is: <?php echo $datetime; ?></p>
<?php echo "<p>Embedded PHP works too!</p>"; ?>
<?php } ?>
</body>
</html>
The use is pretty much the same, just assign more than one row to make use of it:
<?
include "template.class.php";
$template = new Template;
$template->load("design.phtml");
$template->replace("title", "My Template Class");
$rows = array();
$rows[] = array(
"name" => "William",
"datetime" => date("m/d/y"),
);
$template->replace("rows", $rows);
$template->publish();
?>
Hope this is helpful.
Your PHP code:
$htmldata ="";
($results as $row) {
$name = $row['name'];
$address = $row['address'];
$htmldata .="
<tr><td>
<h3>Hello William!</h3>
<p>The time is: 03/10/04</p>
<p>Embedded PHP works too!</p>
<p>".$name."</p>
<p>".$address." </p>
</td>
</tr>
";
}
Then in your template design.html, you will pass the $htmltable variable and embedd there:
<html>
<head>
<title>#title#</title>
</head>
<body>
<h3>Hello #name#!</h3>
<p>The time is: #datetime#</p>
<? echo "<p>Embedded PHP works too!</p>"; ?>
<table>
<?php echo $htmltable; ?>
</table>
</body>
</html>
Need to make $courseInfo and $row global so that they can be used for printing the row details in the header DIV.
Don't have a clue how to do this. Any help would be great.
<?php
// Get Course ID From Link
$ID = mysql_real_escape_string($_REQUEST['ID']);
// Check the Course ID exists
$courseCheck = mysql_query("SELECT * FROM Courses WHERE CourseID = '".$ID."'");
if (mysql_num_rows($courseCheck) == 1) {
$checkMember = mysql_query("SELECT * FROM CourseMembers WHERE CourseID = '".$ID."' AND UserID = '".$_SESSION['UserID']."'");
if (mysql_num_rows($checkMember) == 1) {
?>
<html>
<head>
<!-- Style Sheets -->
<link rel="stylesheet" href="style/reset.css" type="text/css" media=screen />
<link rel="stylesheet" href="style/style.css" type="text/css" media=screen />
</head>
<body>
<?php
if ($_SESSION['LoggedIn'] == 1){
$courseInfo = mysql_query("SELECT * FROM Courses WHERE CourseID = '".$ID."'");
$row = mysql_fetch_assoc($courseInfo);
?>
<div id="container">
<div id="side">
<?php include("lib/sidebar.php"); ?>
</div>
<div id="main">
<div id="mainbox">
<div id="header"><b><?php echo $row['CourseName']; ?></b></div>
<p>Hello world, this is a test.</p>
</div>
</div>
</div>
<div class="clear"></div>
<?php
}
else {
echo "Not logged in.";
}
}
else {
echo "You are not a member of this Course";
}
}
else {
echo "No Course Found";
}
?>
</body>
I think they're already global. "PHP does not have a block-level scope."
You could store them in session variables, similarly to your $_SESSION['LoggedIn']
You could also use php variable $GLOBALS for making your variables visible in all scopes but I would not recommend it for this kind of task. Also, beware - $GLOBALS contains superglobals like $_POST and $_GET, you should keep that in mind, when ie. iterating over it. Furthermore - when you can access $_GET and $_POST in functions, that have smaller scope you still have to use $GLOBALS to access custom ones.
Example for this kind behaviour:
<?php
error_reporting(-1);
$GLOBALS['_customVar'] = 'foobar';
$GLOBALS['_GET']['id'] = 'myId';
function myFnc() {
echo $_customVar;
}
function myFnc2() {
echo $_GET['id'];
}
myFnc();
myFnc2();
?>