Include same file multiple times in PHP - php

Basically I have a list of particular members that I am calling with their member ID, and displaying the td's afterwards on each one..
So I have the table like this
<table id="sortable" class="tablesorter" width="100%">
<thead>
<tr>
<th class="header"><strong>Game Username</strong></th>
<th class="header"><strong>Rank</strong></th>
<th class="header"><strong>Game Played</strong></th>
<th class="header"><strong>Playing On</strong></th>
<th class="header"><strong>Age</strong></th>
<th class="header"><strong>Time On</strong></th>
<th class="header"><strong>Location</strong></th>
</tr>
</thead>
<tbody>
<?php include ("users.php"); ?>
</tbody>
And the users.php file looks like this, but right now at over 50 lines of the same code as below, with only the $id= number changed..
<tr><td class="username"><a href="<?php $id='1'; include ("fields.php"); ?>
<tr><td class="username"><a href="<?php $id='2'; include ("fields.php"); ?>
<tr><td class="username"><a href="<?php $id='3'; include ("fields.php"); ?>
<tr><td class="username"><a href="<?php $id='4'; include ("fields.php"); ?>
<tr><td class="username"><a href="<?php $id='5'; include ("fields.php"); ?>
The fields.php file is the remainder of the table rows etc., starting with the below code to close off this td.
<?php echo $domain; $member_id = $id; $user_info = get_userdata($id);echo $user_info-> user_login.""; ?>"><?php echo xprofile_get_field_data( "$field_gamename" , $member_id); ?></a>
</td>
I'm trying to avoid including the fields.php file over 50 times in the users.php file. Anyone got an idea of the most efficient way?
Thanks!

This should work:
<?php for ($i=0; $i<50; $i++): ?>
<tr><td class="username"><a href="<?php $id=$i; include ("fields.php"); ?>
<?php endfor; ?>
On the other hand, you should probably re-factor your code so that you do not need to include the file on each loop, probably by either putting the code inline or (much better) by creating a function that does whatever you need to be done, something like this:
<?php for ($i=0; $i<50; $i++): ?>
<tr><td class="username"><a href="<?php do_some_stuff($i); ?>
<?php endfor; ?>
EDIT:
Since you want this to work for a defined list of IDs, you should create an array with that list and loop through it using the foreach() statement, like this:
<?php
$IdArray = array(1, 2, 25, 38);
foreach ($IdArray as $id): ?>
<tr><td class="username"><a href="<?php include ("fields.php"); ?>
<?php endforeach; ?>
Notice that I have removed the "$id = $i", since I am feeding the $id variable directly inside the foreach statement! ;)
BTW, you should close the tr, td and a tags before the "endforeach", ok?
Good luck!

Yes, a loop.
for ($i = 1; $i <= 50; $i++) {
//Do stuff with $i.
}

<?php
for($i = 0; $i <= 50; $i++) {
?>
<tr>
<td class="username">
<?php $href = $domain . $user_info->get_userdata($i) . $user_info->user_login;?>
<?php echo xprofile_get_field_data( "$field_gamename" , $i); ?>
</td>
</tr>
<?php
}
?>

Related

Give Unique Class to each table row in loop

I have an PHP for loop; which looks at a number in database and outputs the tables rows to number of times.
Here is my HTML:
<?php
for($x=0; $x < 5; $x++){
$row_count =1;
?>
<table class="table table-bordered" id="ticktable">
<tr class=" <?php echo $row_count; ?>">
<?php
for($w=0; $w < 5; $w++){
?>
<td>
<img class="yellow-sign" src="http://www.backgroundsy.com/file/large/yellow-sign.jpg" width="100">
</td>
<?php
}
?>
</tr>
</table>
<?php
$row_count ++;
}
?>
The above code display this:
How I can assign unique class to each of the rows?
Labelled Image
Example:
<?php foreach($data as $row) { ?>
<tr id="data<?php echo $row['id']; ?>"> </tr>
<?php } ?>
I hope it will help you.
If you are trying to get unique class to tr then do this
for ($x = 0; $x < 5; $x++) {
$row_count = 1;
$randClass = rand(1111,9999).$row_count;
?>
<table class="table table-bordered" id="ticktable">
<tr class="<?php echo $randClass; ?>">
<?php
for ($w = 0; $w < 5; $w++) {
?>
<td>
<img class="yellow-sign <?php echo $randClass; ?>" src="http://www.backgroundsy.com/file/large/yellow-sign.jpg" width="100">
</td>
<?php
}
?>
</tr>
</table>
<?php
$row_count++;
}
rand(1111,9999) will generate random number between 1111 and 9999
EDIT
i have also added $row_count so that the number can not be repeated even if there is large data. What I've done is: <tr class="<?php echo rand(1111,9999).$row_count; ?>">
UPDATE
first store the random string in a variable $randClass = rand(1111,9999).$row_count;
then echo out where you want the variable like this:
$randClass = rand(1111,9999).$row_count;
and <img class="yellow-sign <?php echo $randClass; ?>" >
Here is the updated code for you. Check this
<?php
$color_class[] = array("yellow-sign","red-sign","green-sign","blue-sign","black-sign");
$row_count = 0;
for($x=0; $x < 5; $x++){
?>
<table class="table table-bordered" id="ticktable">
<tr class=" <?php echo $row_count; ?>">
<?php
for($w=0; $w < 5; $w++){
?>
<td>
<img class="<?php echo $color_class[$row_count]; ?>"
src="http://www.backgroundsy.com/file/large/yellow-sign.jpg" width="100">
</td>
<?php
}
?>
</tr>
</table>
<?php
$row_count ++;
}
?>

Foreach display only first result

How can I make this foreach line only go through the first result?
<?php foreach ($collection as $product) : ?>
I tried the following, but that does not work. It than does not display any results:
<?php foreach (array_slice($collection, 0, 1) as $product) : ?>
EDIT:
The following works perfect:
<?php
$i = 0;
foreach ($collection as $product) :
if($i < 1) {
Inner content
}
$i++;
endforeach;
?>
Total current code:
<tbody>
<tr>
<td class="image" rowspan="3">
<?php $i = 0; foreach ($collection as $product) : if($i < 1) {?>
<img src="<?php echo $this->helper('catalog/image')->init($product, 'thumbnail')->resize(75) ?>" alt="<?php echo $this->htmlEscape($product->getName()) ?>" width="75" height="75" />
<?php } $i++; endforeach ?>
</td>
<td class="order" colspan="2">order</td>
<td class="exclTax">excl. vat</td>
<td class="inclTax">incl. vat</td>
</tr>
<?php foreach ($collection as $product) : ?>
<tr>
<td class="select"><input type="radio" name="featured_1807" id="featured_1807_1349567899" value="3071895, IM" data-product-id="3071895" data-product-sup="IM"></td>
<td class="title"><?php echo $this->htmlEscape($product->getName()) ?></td>
<td class="price"><?php echo $abstractBlock->getPriceHtml($product, true, '-related') ?></td>
<td class="priceIncl"><?php echo $abstractBlock->getPriceHtml($product, true, '-related') ?></td>
</tr>
<?php endforeach ?>
</tbody>
How can I achieve that?
Why bother with a loop if you are only interested in the first occurance of $collection
You could do this instead and probably not have to change any code you currently have inside your loop
<?php
$product = $collection[0];
Code you had in the loop
?>
If its not a numeric key then you can use
<?php
reset($collection); // make sure you are on first occ
$product = $collection[key($collection)];
... html stuff
// and then do again for your second loop
// if you only want the first occ of that as well
reset($collection); // make sure you are on first occ
$product = $collection[key($collection)];
reset($collection); // Resets the array's internal pointer to the first element
$product = current($collection); // Returns the current element which is now first element
As far as I'm concerned, this is the best solution I would ever go for if I need to only extract the first element from an array.

Table doesn't align vertically

So I want to do something very simple, which I can't figure out properly. I'm currently making a forum and where I normally have errors (the back end) it all works now, probably through the black magic I used ;D,
So now, the thing is: I want to show all my subcategories, so I'm using the following table:
<div id="content_big">
<div class="content_top_oranje">
<p class="koptekst">
<?php echo 'Name';?>
</p>
<p style="float:left; margin-left:70%; margin-top:-30px; color:#fff; font-size:11px;font-family:Ubuntu;">
<?php echo 'Description';?>
</p>
</div>
<div class="content_mid">
<?php $kop='algemeen' ;
$query=$ db->conn->prepare("SELECT * FROM ht_forum_categorien WHERE kop = ?");
$query->bind_param('s', $kop);
$query->execute();
$result = $query->get_result();
while ($row = $result->fetch_assoc()) { ?>
<table style="width:100%;" border="1" cellspacing="0">
<tr>
<td>
<?php echo $row[ 'name']; ?>
</td>
<td style="margin-left:50px;">
<?php echo $row[ 'description]; ?>
</td>
</tr>
</table>
<?php
}
?>
</div>
</div>
But when I use that, this is the output I get:
How is it possible that all of the rows won't vertically align? And how to solve it?
Thanks. (I'm sorry the screenshot is in dutch, but I can't change the values in the DB, since it isn't mine
You have two fairly big problems in your code:
most importantly, and the problem you ran into: you're not generating a table. You're generating lots of tables. If you want one table, move your <table> and </table> tags outside of your loop and only generate <tr> with their content in your while loop.
a problem you didn't realise you had: the HTML you're using isn't faithful to the promise that your markup is semantic: that heading should be a heading element (h1, h2, h3, what have you), and as a table, really this shouldn't be divs and p and table at all, this should be a single table, with a heading row, styled as your heading, and then data rows.
So let's rewrite this to something that makes sense both from a PHP and from an HTML perspective:
<?php
...query your data. Do this first...
$result = ...;
if($result isn't empty) {
?>
<table>
<?php
echo "<thead><th>$kop</th><th>$description</th></thead>";
?>
<tbody>
<?php
while ($row = $result->fetch_assoc()) {
$name = $row['name'];
$desc = $row['description'];
echo "<tr><td>$name</td><td>$desc</td></tr>\n";
}
?>
</tbody>
</table>
<?php } ?>
So don't do the querying inside the table, do it first, then if there are results to show, decide whether or not to write the single table, generating the dynamic content in the tbody as table rows. And use CSS to style the thead cells the way you need.
For that matter, don't use all those inline style="..." bits. They're all identical, so you're just needlessly repeating static CSS. Use class="rowclass" or whatever name you think is appropriate, and then in your stylesheet or <style> block, define
.rowclass {
background-color: ...;
color: ...;
...
}
Try this
<div id="content_big">
<div class="content_top_oranje">
<p class="koptekst">
<?php echo 'Name';?>
</p>
<p style="float:left; margin-left:70%; margin-top:-30px; color:#fff; font-size:11px;font-family:Ubuntu;">
<?php echo 'Description';?>
</p>
</div>
<div class="content_mid">
<?php $kop='algemeen' ;
$query=$ db->conn->prepare("SELECT * FROM ht_forum_categorien WHERE kop = ?");
$query->bind_param('s', $kop);
$query->execute();
$result = $query->get_result();
?>
<table style="width:100%;" border="1" cellspacing="0">
<?php while ($row = $result->fetch_assoc()) { ?>
<tr>
<td>
<?php echo $row[ 'name']; ?>
</td>
<td style="margin-left:50px;">
<?php echo $row[ 'description']; ?>
</td>
</tr>
<?php
}
?>
</table>
</div>
</div>

Sorting a HTML table with PHP after input from database

I'm creating a HTML table with data-rows from a MySQL database and some calculated values, like this:
<?php
$connection = mysql_connect('localhost','root','') or die('Connection failed!');
mysql_select_db('MyDB', $connection);
$result = mysql_query('SELECT * FROM DB_TABLE');
?>
<table>
<tr>
<th scope="col">Heading 1</th>
<th scope="col">Tariefplan</th>
<th scope="col">Abonnementskost</th>
<th scope="col">Maandelijkse korting</th>
<th scope="col">Contractduur</th>
<th scope="col">Inbegrepen in bundel</th>
<th scope="col">Tarieven buiten bundel</th>
<th scope="col"></th>
<th scope="col">Bereken minuten</th>
<th scope="col">Bereken SMS'en</th>
<th scope="col">Bereken MB's</th>
<th scope="col"></th>
<th scope="col">Totale prijs normaal</th>
<th scope="col">Totale prijs promotie</th>
<th scope="col">Totale prijs contract</th>
</tr>
<?php
while ($data = mysql_fetch_assoc($result)) {
?>
<tr>
<th scope="row"><?php echo $data['provider']; ?></th>
<td><?php echo $data['planname']; ?></td>
<td>€ <?php echo $data['price_normal']; ?> per maand<br />
<sub>gedurende <?php echo ($data['contract_duration']-$data['promo_duration']); ?> maanden</sub></td>
<td>- € <?php echo $data['promo_discount']; ?> per maand<br />
<sub>gedurende <?php echo $data['promo_duration']; ?> maanden</sub><br />
<sub>promotie geldig tot <?php echo $data['promo_valid']; ?></sub></td>
<td><?php echo $data['contract_duration']; ?> maanden</td>
<td>
<ul>
<li><?php echo $data['included_min']; ?> minuten</li>
<li><?php echo $data['included_sms']; ?> SMS'en</li>
<li><?php echo $data['included_mb']; ?> MB's</li>
<li>€ <?php echo $data['included_value']; ?> belwaarde</li>
</ul>
</td>
<td>
<ul>
<li>€ <?php echo $data['price_min']; ?> per minuut</li>
<li>€ <?php echo $data['price_sms']; ?> per SMS</li>
<li>€ <?php echo $data['price_mb']; ?> per MB</li>
</ul>
</td>
<td></td>
<td>
<?php
if ($_POST['used_min'] <= $data['included_min']) {
$calc_min = 0;
}
else {
$calc_min = ($_POST['used_min'] - $data['included_min']) * $data['price_min'];
}
echo '€ ' . $calc_min;
?>
</td>
<td>
<?php
if ($_POST['used_sms'] <= $data['included_sms']) {
$calc_sms = 0;
}
else {
$calc_sms = ($_POST['used_sms'] - $data['included_sms']) * $data['price_sms'];
}
echo '€ ' . $calc_sms;
?>
</td>
<td>
<?php
if ($_POST['used_mb'] <= $data['included_mb']) {
$calc_mb = 0;
}
else {
$calc_mb = ($_POST['used_mb'] - $data['included_mb']) * $data['price_mb'];
}
echo '€ ' . $calc_mb;
?>
</td>
<td></td>
<td>
<?php
$used_total = ($calc_min + $calc_sms + $calc_mb);
if ($data['included_value'] > $used_total) {
$total_price_normal = $data['price_normal'];
}
else {
$total_price_normal = ($data['price_normal'] + $used_total);
}
echo '€ ' . $total_price_normal . ' per maand';
?>
</td>
<td>
<?php
$total_price_discount = ($total_price_normal - $data['promo_discount']);
echo '€ ' . $total_price_discount . ' per maand';
?>
</td>
<td>
<?php
$total_price_contract = ($total_price_normal * ($data['contract_duration']-$data['promo_duration'])) + ($total_price_discount * $data['promo_duration']);
echo '€ ' . $total_price_contract . ' per maand ' . $data['contract_duration'] . ' na maanden';
?>
</td>
</tr>
<?php } ?>
</table>
The last column in the table is a variable value witch calculates a total amount. This is NOT listed in the database.
I want to output this table to an browserpage and let is be sort on that last column.
With PHP sort() or asort() function that doesn't work fine.
Does someone have a solution?
Do the calculation in the SQL query, and let the database handle the sorting
You have calculate the values first and then create the table. Or use some javascript. So you have to go trough $result and put calculated values in array and after that you may sort and print to table with values, sorted by that last value.
I think it would be better if you first iterate through your results, do your calculations and put everything into an array. Then you can sort the array like you want with any PHP function and output it. The best thing with this approach is, you will have a cleaner output of the table because do all calculations and stuff away from the HTML output ;)
The other idea is, that you do it like you do above and then use a tablesorter in i.e. Javascript/jQuery to sort your rows afterwards.
It is possible but it might be tricky to do this using PHP. For a quick fix you could try this jquery solution which does what you want and get you up and running very quickly.
http://tablesorter.com/docs/#Demo
With PHP sort() or asort() function that doesn't work fine.
if you meant it sort like this 1, 10, 12, 2 you can use natsort();.

using CMS to open page

this is the index.php
<table align="center" border="0" cellpadding="0" cellspacing="0">
<tbody>
<?php include 'header.php'; ?>
<tr>
<td class="row_2">
<!-- header_eof //-->
<!-- body //-->
<table class="main_table" border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<?php
if($cond)
include 'left.php'; ?>
<!-- body_text //-->
<?php get_page(); ?>
<!-- body_text_eof //-->
<?php
if($cond)
include 'right.php'; ?>
</tr>
<tr>
<?php
if(!$cond)
include 'contents/contact_us.php';?>
</tr>
</tbody>
</table>
<!-- body_eof //-->
<!-- footer //-->
</td>
</tr>
<?php include 'footer.php'; ?>
</tbody>
</table>
This is header.php . I have created link from database
<?php
$menus = db_query("select * from menus where type=0 order by weight");
$sr = 0;
while($menu = mysql_fetch_object($menus)) { ?>
<?php if(($sr++) > 0){ ?>
<td class="menu_separator"><img src="<?php echo SROOT;?>images/menu_separator.png" alt="" class="png" width="2" border="0" height="49"></td>
<?php } ?>
<td id="<?php echo get_id($menu->page_name); ?>" <?php echo get_event($menu->page_name); ?> onClick="document.location='<?php echo SROOT . $menu->page_name;?>'" nowrap="nowrap"><?php echo $menu->title; ?></td>
<?php } ?>
this is the get_page function
function get_page() {
$page = arg(0);
$page = (empty($page)) ? 'home' : $page;
$cat = db_query("select * from mb_category where title='".$page."'");
$page = (mysql_num_rows($cat)) ? 'brands' : $page;
include 'contents/'. $page .'.php';
}
I have everything in the right place.The same code is working for my friend but we are unable to understand the problem here. I get error cannot find page. His is working fine.
When i click link it says cannot find page..but his goes to page
Can anyone please help and tell me what i am doing wrong
Edited:
The part I don't understand is this:
$page = arg(0);
$page = (empty($page)) ? 'home' : $page;
$cat = db_query("select * from mb_category where title='".$page."'");
What is "arg(0)?, so how do you get $page?
Ok, I understand this is a drupal function or alike.
But, pls, verify that arg(0) returns sth.
If you are not sure of the path the include is taken, I would change this line:
include 'contents/'. $page .'.php';
for:
include $_SERVER["DOCUMENT_ROOT"]."/contents/'. $page .'.php';

Categories