How to call a function in PHP - php

I have been following some courses on how to create a session object, which has worked out fine, If I place the complete code onto a PHP file, all works great!
What I would like to do is place this in another module (PHP file) and just use one line (or equivalent) to do this, such as GetSessiondata();
<?php
$SqlCon = new DBConnect("Databaselocation","Database","Usr","Pss");
$UserDataSet = $SqlCon->GetUserList("SELECT * FROM Users");
echo "<br /><br />";
echo "<br /><br />";
if ($UserDataSet)
{
echo "<table>" . "<thead>" ;
echo "<tr><th scope=\"col\">" . 'Usr' . "</th>";
echo "<th scope=\"col\">" . 'Lvl' . "</th></tr></thead><tbody>";
foreach($UserDataSet as $data)
{
echo "<td>" .$data->GetUsrName()."</td>" ;
echo "<td>" .$data->GetUsrLevel()."</td></tr>" ;
}
echo "<tfoot><tr><th scope=\"row\" colspan=\"2\">" . 'Total Users = 2' . "</th></tr></tfoot>";
echo "</tbody>" . "</table>" ;
}
else
echo "Nothing Found in DB!";
?>

You need to "require" your file, where you want to use it.
Here an example
Working with classes:
Whatever.php
class Whatever {
public function __construct() {
// Ever when the code is instantiated, this will be called too!
}
public function myMethod() {
echo 'hello';
}
}
index.php
require_once('./Whatever.php');
$whatever = new Whatever();
$whatever->myMethod();
Without classes:
functions.php:
function whatever(){ echo 'hello'; }
index.php:
require_once('./functions.php');
whatever();
Read more:
Require: http://php.net/manual/es/function.require.php
Require_once: http://php.net/manual/es/function.require-once.php

My advise is to split this refactoring process into 2 steps:
1.Wrap your code into function:
function someFunctionName() {
$SqlCon = new DBConnect("Databaselocation","Database","Usr","Pss");
$UserDataSet = $SqlCon->GetUserList("SELECT * FROM Users");
echo "<br /><br />";
echo "<br /><br />";
if ($UserDataSet)
{
echo "<table>" . "<thead>" ;
echo "<tr><th scope=\"col\">" . 'Usr' . "</th>";
echo "<th scope=\"col\">" . 'Lvl' . "</th></tr></thead><tbody>";
foreach($UserDataSet as $data)
{
echo "<td>" .$data->GetUsrName()."</td>" ;
echo "<td>" .$data->GetUsrLevel()."</td></tr>" ;
}
echo "<tfoot><tr><th scope=\"row\" colspan=\"2\">" . 'Total Users = 2' . "</th></tr></tfoot>";
echo "</tbody>" . "</table>" ;
}
else
echo "Nothing Found in DB!";
}
// and call your function
someFunctionName();
2.Create another file, let's say functions.php, in the same dir and move function into it. Now you can require this file inside your php page:
require_once 'functions.php';
// and call your function
someFunctionName();

I think you are looking for include
Save your file, and then you can include it in another file as:
include 'my_file.php';
You can also use:
include_once
require
require_once
Read the documentation for further explanations or see this question

Related

How can i display my preg_match results in various divs so they can have multiple results under the correct heading?

Forgive me if this is simple but I have a for each loop that searches JSON data for results from a search. I then have some preg_match statements that will look at some of the tags within the JSON and if their is a match display the thumbnail in a div. and currently this all works. But it currently displays every result in its own Div and i want just five divs with multiple images within if there is a match.
foreach ($hits as $hit)
{
$target = $hit->metadata->baseName;
$target1 = $hit->metadata->cf_imageType;
if(preg_match("/_cm/i",$target)) {
echo '<div id="div5">';
echo '<h2>Creative</h2>';
echo "<img src='" . $hit->thumbnailUrl . "' alt='error'>";
echo $hit->metadata->baseName;
echo '</div>';
}
if(preg_match("/_SS/i",$target)) {
echo '<div id="div6">';
echo '<h2>Styled</h2>';
echo "<img src='" . $hit->thumbnailUrl . "' alt='error'>";
echo $hit->metadata->baseName;
echo '</div>';
}
if(preg_match("/_SH/i",$target)) {
echo '<div id="div7">';
echo '<h2>Group</h2>';
echo "<img src='" . $hit->thumbnailUrl . "' alt='error'>";
echo $hit->metadata->baseName;
echo '</div>';
}
if(preg_match("/still life/i",$target1) && preg_match("/_sm_00|_sd_00/i",$target)) {
echo '<div id="div8">';
echo '<h2>Cutout</h2>';
echo "<img src='" . $hit->thumbnailUrl . "' alt='error'>";
echo $hit->metadata->baseName;
echo '</div>';
}
if(preg_match("/worn/i",$target1)) {
echo '<div id="div9">';
echo '<h2>Worn</h2>';
echo "<img src='" . $hit->thumbnailUrl . "' alt='error'>";
echo $hit->metadata->baseName;
echo '</div>';
}
}
I cant quite figure out how to accomplish this, would it be the case of putting the results into an array and then displaying the results within the div?
Any help would be greatly appreciated.
You are right and answered the question yourself :)
Collect the results in a first step and create the markup in a second step. Something like this will do it:
$creative = [];
$styled = [];
/* ... */
function getHitInfos($theHit)
{
return [
"url" => $theHit->thumbnailUrl,
"name" => $theHit->metadata->baseName
];
}
function printResults($results, $title) {
echo '<div>';
echo '<h2>'.$title.'</h2>';
foreach ($results as $key => $val) {
echo "<img src='" . $val["url"] . "' alt='error'>";
echo $val["name"];
}
echo '</div>';
}
foreach ($hits as $hit)
{
$target = $hit->metadata->baseName;
$target1 = $hit->metadata->cf_imageType;
echo '<div>';
if(preg_match("/_cm/i",$target)) {
$creative[] = getHitInfos($hit)
}
if(preg_match("/_SS/i",$target)) {
$styled[] = getHitInfos($hit)
}
/* ... */
}
printResults($creative, "Creative");
printResults($styled, "Styled");
/* ... */
Disclaimer: My last contact with php is some years ago, but I hope you will see the point here.
(I also created some helping functions to DRY the code)

Using php to find the first element of an array and add it the class active to create a tab system with bootstrap.js

I'd like to add an active class with PHP instead of using javascript.
But I probably broke the code somewhere.
I'm using bootstrap.js version 3 and I'm building my tabs using PHP because I need to use my tabs on the control panel in my app.
So essentially I didn't add any javascript or jquery so far, I'm just using the native functions for tabs in bootstrap.js (and jquery):
<?php foreach ($database as $item): ?>
<?php
if (isset($item['associations'])) {
foreach ($item['associations'] as $value) {
echo "<div class='modal' id='des_" . $value['des_id'] . "'>";
echo "<div class='modal-sandbox'></div>";
echo "<div class='modal-box'>";
echo "<div class='modal-body'>";
echo "<div class='close-modal'>✖</div>";
echo "<h3>Credit and values</h3>";
echo "<h5>" . $value["designation_name"] . " - Credit: " . $value["designation_credits"] . "</h5>";
echo "<ul class='nav nav-pills'>";
if (isset($value['credits']) && !is_string($value['credits'])) {
foreach ($value['credits'] as $credits) {
$first_element = reset($value["credits"]);
if (isset($value['credits'])) {
if ($first_element[4] == $credits[4]) {
echo "<li class='active'><a href='tab_" . $credits[4] . "' data-toggle='tab'>Identifier: " . $credits[0] . "</a></li>";
} else {
echo "<li><a href='tab_" . $credits[4] . "' data-toggle='tab'>Identifier: " . $credits[0] . "</a></li>";
}
}
}
}
echo "</ul>";
echo "<div class='tab-content clearfix'>";
if (isset($value['credits']) && !is_string($value['credits'])) {
foreach ($value['credits'] as $credits) {
if (isset($value['credits'])) {
if ($first_element[4] == $credits[4]) {
echo "<div class='tab-pane active' id='tab_" . $credits[4] . "'>";
} else {
echo "<div class='tab-pane' id='tab_" . $credits[4] . "'>";
}
echo "<div class='single-credit'>";
?>
<?=form_open();?>
<?php
echo "<input type='hidden' name='id' value='" . $credits[4] . "'>";
echo "<div>Identifier: <span>" . $credits[0] . "</span></div>";
echo "<input name='edit_credits' type='submit' value='Edit' class='submit'>";
echo "</div>";
echo "</div>";
echo "</div>";
?>
<?=form_close()?>
<?php
}
}
}
echo "</div>";
echo "</div>";
echo "</div>";
echo "</div>";
}
}
?>
<?php endforeach;?>
To explain my code I will start from the list:
Since it's a really complex array, I'm taking the first element with the reset function to add the active class only on that very element.
Then I added the href element to point to the id of the matching div later on, and then I close my list.
Later on, I create another loop and I use the id to match both the list and the div and I used the trick that I used before to add the class active only on my first element of my array.
Everything works except for the fact that, if I click another element of the list, the matching div won't work, the very first element of the array will keep the class active, so I can't switch beteween element.
I need to spot the error.
UPDATE:
The problem that I have with jquery, in this case, is that if I use a toogleClass for example like that:
$(".nav-pills li").click(function(e) {
e.preventDefault();
tab = $(this).find('a').attr('href');
$("#" + tab).toggleClass('active');
});
It won't be able to toggle properly the class on the first element, that one to which I added the class active with php.
I think you miss to change the URL when click it, in the backend (PHP) you need to know where the user is, so, you check the "parameter" and mark active or not the current tab.
For example:
printf("<div class='tab-pane %s' id='...'>", $credits[4] == $_GET['tab'] ? 'active':'');

Output xml result into table using PHP

I have successfully put together a PHP script to read content of an xml file and output the result to HTML page. The only bit I am struggling with is how to format the output into a table.
PHP Script:
<?php
// Loading the XML file
$xml = simplexml_load_file("ftpxml.xml");
echo "<h2>".$xml->getName()."</h2><br />";
foreach($xml->children() as $ftpxml)
{
echo "PID : ".$ftpxml->attributes()->pid."<br />";
echo "Account : ".$ftpxml->attributes()->account." <br />";
echo "Time : ".$ftpxml->attributes()->time." <br />";
echo "<hr/>";
}
?>
HTML Result:
PID : 279
Account : account001
Time : 137
----------------------------------------------------------------
PID : 268
Account : account002
Time : 301
----------------------------------------------------------------
PID : 251
Account : account003
Time : 5
----------------------------------------------------------------
I am lost as to how to display each table headings and the corresponding contents. I am new to PHP so please guide me or if already answered else where, please provide link so I can learn from it.
Thanks
<?php
// Loading the XML file
$xml = simplexml_load_file("ftpxml.xml");
echo "<h2>".$xml->getName()."</h2><br />";
echo "<table>";
foreach($xml->children() as $ftpxml)
{
echo "<tr><td>PID : ".$ftpxml->attributes()->pid."</td></tr>";
echo "<tr><td>Account : ".$ftpxml->attributes()->account." </td></tr>";
echo "<tr><td>Time : ".$ftpxml->attributes()->time." </td></tr>";
}
echo "</table>";
?>
echo '<table>';
echo '<thead><tr><th>PID</th><th>Account</th><th>Time</th></tr></thead><tbody>';
foreach($xml->children() as $ftpxml)
{
echo '<tr>';
echo "<td>PID : ".$ftpxml->attributes()->pid."</td>";
echo "<td>Account : ".$ftpxml->attributes()->account."</td>";
echo "<td>Time : ".$ftpxml->attributes()->time." </td>";
echo '</tr>';
}
echo '</tbody></table>';
I assume you want to make the different values different fields in the table:
// Loading the XML file
$xml = simplexml_load_file("ftpxml.xml");
echo "<h2>".$xml->getName()."</h2><br />";
echo "<table><thead><tr><th>PID</th><th>Account</th><th>Time</th></tr></thead><tbody>";
foreach($xml->children() as $ftpxml)
{
echo '<tr>';
echo '<td>' . $ftpxml->attributes()->pid . "</td>";
echo '<td>' . $ftpxml->attributes()->account . "</td>";
echo '<td>' . $ftpxml->attributes()->time . "</td>";
echo '</tr>';
}
echo '</tbody></table>';

Delete index session in PHP

I have question referring to the session in PHP.
I've coded in PHP for setting the session and I want to delete it , but I got some errors and confusing with using the UNSET(variable $_SESSION). Perhaps anyone could help me to show what should I do with this matter. Thanks in advance
$_SESSION['chart'] = array();
$_SESSION['chart'][0]['index'] = 0
$_SESSION['chart'][0]['type'] = $type;
$_SESSION['chart'][0]['idanimal'] = $iddog;
$_SESSION['chart'][0]['price'] = $price;
printdata(); // <== this is the function to print out the data
All I want to do is just delete based on the index in this session
Here's the function :
function printdata()
{
$totalharga = 0;
if(is_array($_SESSION['chart']))
{
echo "<h3>"."Berikut adalah keranjang belanja anda" . "</h3>". "<br>";
$max = count($_SESSION['chart']);
$th1 = "<th>" . "No" . "</th>";
$th2 = "<th>" . "Animal Type" . "</th>";
$th3 = "<th>" . "ID Binatang" . "</th>";
$th4 = "<th>" . "Harga" . "</th>";
$th5 = "<th>" . "Hapus Data" . "</th>";
echo "<table border=1>";
echo "<tr>";
echo $th1 ;
echo $th2;
echo $th3;
echo $th4;
echo $th5;
echo "</tr>";
for ($indexo = 0; $indexo < $max; $indexo++)
{
echo "<tr>";
echo "<td>" . $indexo."</td>";
echo "<td>" . $_SESSION['chart'][$indexo]['type']."</td>";
echo "<td>" . $_SESSION['chart'][$indexo]['idanimal']."</td>";
echo "<td>" . "Rp. " . $_SESSION['chart'][$indexo]['harga']. ",-" ."</td>";
echo "<td>" . "<a href='deletesession.php?session=$indexo'>" ."Proses ". "</a>"."</td>";
$totalharga += $_SESSION['chart'][$indexo]['harga'];
echo "</tr>";
}
echo "</table>" . "<br/>";
echo "<blockquote>" . "Total Pembelian Item Yang Anda Pesan =". "<h2>". "Rp." . $totalharga . ",-" ."</h2>" . "</blockquote>";
}else
{
echo "Chart is still Empty";
}
}
I've already tried this :
Suppose that there is a chart already filled by the contents then I tried to delete within this code, I've received error with the unset variable
unset($_SESSION['chart'][1])
Thank you
I spot several things that could be improved in your code:
Don't echo in your functions, return instead (then echo what the function returns). This gives you more flexibility regarding what you do with your result.
PHP has a built-in loop for iterating arrays, the foreach loop. You should be using that instead of for.
So here's what I have:
function print_session_data($session) {
if (!is_array($session)) {
return "Array is empty";
}
$table_data = "";
$total_harga = 0;
foreach ($session as $index => $data) {
$table_data .= <<<TABLE_DATA
<tr>
<td>$index</td>
<td>{$data["type"]}</td>
<td>{$data["idanimal"]}</td>
<td>Rp. {$data["harga"]}</td>
<td>Proses</td>
</tr>
TABLE_DATA;
$total_harga += $data["harga"];
}
$result = <<<RESULT
<h3>Berikut abalah keranjang belanja anda</h3>
<table border="1">
<thead>
<tr>
<th>No</th>
<th>Animal Type</th>
<th>ID Binatang</th>
<th>Harga</th>
<th>Hapus Data</th>
</tr>
</thead>
<tbody>
$table_data
</tbody>
</table>
<blockquote>Total Pembelian Item Yang Anda Pesan = <strong>Rp. $total_harga</strong></blockquote>
RESULT;
return $result;
}
$_SESSION['chart'] = array();
$_SESSION['chart'][0]['type'] = "Type";
$_SESSION['chart'][0]['idanimal'] = 6;
$_SESSION['chart'][0]['price'] = '$25';
$_SESSION['chart'][0]['harga'] = 25;
echo print_session_data($_SESSION["chart"]); // <== this is the function to print out the data
Suppose that there is a chart already filled by the contents then I
tried to delete within this code, I've received error with the unset
variable unset($_SESSION['chart'][1])
From what I can see from your code the best way to unset the data correctly is as follow:
DEMO.
You have to check if the $_SESSION['chart'][0] was set before using the session variable index again. If it $_SESSION['chart'] array still contains other indexes then you can call printdata(); else indicate that the session was empty.

AJAX add data to table without resetting table.

I have a php page that will grab data from an SQL database and print it into a table, now if certain rows from the database have a certain parameter, a hidden row is inserted below that with a button to expand the row. This all works fine and I can query it with ajax into a div on a different page, but if someone were to expand the hidden row (with jquery) and the ajax update timer were to come along, it would reset and hide that row.
Here is the page that it is filled into and the ajax code to go with it:
<script type="text/javascript">
$(document).ready(function() {
$("#query").load("query.php");
var refreshId = setInterval(function() {
$("#query").load('query.php');
}, 5000);
$.ajaxSetup({ cache: false });
});
</script>
<div id="query"></div>
And from the query.php:
while($row = mysql_fetch_array($result))
{
$decoded = json_decode($row['B'],true);
$r = $decoded['r'];
$t = $decoded['t'];
$l = $decoded['l'];
$g = $decoded['g'];
$tp = (int)$t + 3;
echo "<tr>";
echo "<td>" . $row['ID'] . "</td>";
echo "<td align=\"center\"><font color=\"red\">[$t]</font></td>";
echo "<td align=\"center\"><font color=\"blue\">[$r]</font></td>";
echo(((int)$t != 0) ? '<td><button class="expand stylebutton">+</button>' : '<td>');
echo $row['Name_'] . "</td>";
echo "<td>" . $row['Date_'] . "</td>";
echo "<td>" . $row['IP'] . "</td>";
echo "<td>" . $row['G'] . "</td>";
echo "<td>" . $row['A'] . "</td>";
echo "<td>" . $row['Add'] . "</td>";
echo "<td>" . $row['Remove'] . "</td>";
echo "<td>" . $row['Comments'] . "</td>";
echo "</tr>";
if((int)$t != 0)
{
echo "<tr class=\"b\"style=\"display: none;\">";
echo "<td></td><td colspan=\"$tp\"><div style=\"color: #FC0;\"> Local:</div>";
foreach($l as $ll)
{
echo $ll . "<br>";
}
echo "<br><div style=\"color: #F00;\">Global:</div>";
foreach($g as $gg)
{
echo $gg . "<br> ";
}
echo "</td></tr>";
}
}
echo "</table>";
echo "<script type=\"text/javascript\">";
echo "$(document).ready(function() {
$(\".stylebutton\").click(function(){
$(this).parent().parent().next().toggle();
if($(this).text() == \"+\")
{
$(this).text('-');
}
else
{
$(this).text('+');
}
});
});
</script>";
Here's an image of what one of the rows looks like when expanded.
So basically I don't want the rows to contract when the ajax update rolls through, but instead just add more data on to the page. Thanks for any help!
You should have the php file return the data in json format to be used by your jQuery. Instead of replacing the html tags and causing your UI to retract, you will replace the data.
For Example
Your php code:
$data_array = array();
while($row = mysql_fetch_array($sql)) {
array_push( $row['some_row'] , $data_array ); // add the data to an array that will later be json encoded
}
echo json_encode($data_array);
jQuery
$.ajax({
url: 'query.php',
success: function(data) {
alert('This is the JSON: ' + JSON.stringify(data));
$('#selector').text(data.some_row); // place the data inside the element with id = 'selector'
}
});

Categories