PHP: Class not found - php

I'm getting this annoying error and haven't been able to fix it yet.
<b>Fatal error: Class 'Console' not found in /home/serellyn/public_html/HEIM/php/nieuwbeheer/console_overview.php on line 45.</b>
Let's first start with the hierarchy which is like this.
index (main page)
console_overview (section of page)
include/connect (connect to DB)
include/console.class (the class)
The index.php requires the connect.php and the console.class.php and loads the console_overview.php. Here's the code:
<?php
require_once('include/connect.php');
require_once('include/console.class.php');
var_dump(file_exists('include/connect.php'));
var_dump(file_exists('include/console.class.php'));
?>
<div id="mainpage" class="main-container inner">
<?php
if (isset($_GET['page'])) {
$page = $_GET['page'];
} else {
$page = "console_overview";
}
?>
</div>
<!-- end: MAIN CONTAINER -->
<script>
var page = "<?php echo $page;?>";
$( "#mainpage" ).load( page + ".php" );
</script>
I've used var_dumps to check if both file exists (and they do). The console_overview.php loads correctly. Now in the console_overview.php I'm trying to get data from the Console class, as following:
<?php
foreach(Console::getAllConsoles() as $aConsole) {
$consoleID= $aConsole->getID();
$consoleName = $aConsole->getName();
$consoleHostname = $aConsole->getHostname();
$consoleGameID = $aConsole->getGameID();
$consolePowerState = $aConsole->getPowerState();
echo "<tr>";
echo "1";
}
?>
The error I'm getting is caused by the foreach... but I can't find out what's wrong...
The Console class looks like this (I'm pasting the most important parts, otherwise the code would be too long).
<?php
class Console{
private $ID, $hostname, $mac, $ip, $roomID, $gameID, $register, $powerState, $dateUpdated;
public function Console($tID, $tHostname, $tMac, $tIp, $tRoomID, $tGameID, $tRegister, $tPowerState, $tDateUpdated) {
$this->ID = $tID;
$this->hostname = $tHostname;
$this->mac = $tMac;
$this->ip = $tIp;
$this->roomID = $tRoomID;
$this->gameID = $tGameID;
$this->register = $tRegister;
$this->powerState = $tPowerState;
$this->dateUpdated= $tDateUpdated;
}
...
public static function getAllConsoles() {
$sql = "SELECT * FROM `console` ORDER BY `hostname` ASC";
$result = mysql_query($sql);
$theResults = array();
while ($row = mysql_fetch_array($result)) {
$theResults[] = new Console($row[0],$row[1],$row[2],$row[3],$row[4],$row[5],$row[6],$row[7],$row[8],$row[9],$row[10]);
}
return $theResults;
}
}
?>
So can anyone see what the problem is?
Thank you for your help.
Edit: O and yes, I know MySQL is deprecated and will change this whenever the issue of not finding the console is fixed =).

Your console_overview.php does not include the required files. When you make an AJAX call with JavaScript from the client it is a separate HTTP request to the server, so you have to add the require() call again there:
<?php
require_once('include/connect.php');
require_once('include/console.class.php');
foreach(Console::getAllConsoles() as $aConsole) {
$consoleID= $aConsole->getID();
$consoleName = $aConsole->getName();
$consoleHostname = $aConsole->getHostname();
$consoleGameID = $aConsole->getGameID();
$consolePowerState = $aConsole->getPowerState();
echo "<tr>";
echo "1";
}
?>

Related

Modify form using a dropdown (select) menu

So I'm trying to get records from database by using this code, but I'm only getting else alert message. Can somebody say what I am doing wrong or where is an error in the code? It populates the dropdown, but like I said I don't get the result only the alert message:
<form method='post' action='grafikastest.php'>
<select id="name">
<?php
include_once ('inc\connect.php');
echo "Pasirinkite datą: &nbsp";
$date = strtotime("+0 day");
$dtt=date('Y-m-d', $date);
echo "<option value=$dtt>$dtt</option>";
$date = strtotime("+1 day");
$dtt=date('Y-m-d', $date);
echo"<option value=$dtt>$dtt</option>";
$date = strtotime("+2 day");
$dtt=date('Y-m-d', $date);
echo "<option value=$dtt>$dtt</option>";
$date = strtotime("+3 day");
$dtt=date('Y-m-d', $date);
echo "<option value=$dtt>$dtt</option>";
$date = strtotime("+4 day");
$dtt=date('Y-m-d', $date);
echo "<option value=$dtt>$dtt</option>";
$date = strtotime("+5 day");
$dtt=date('Y-m-d', $date);
echo "<option value=$dtt>$dtt</option>";
$date = strtotime("+6 day");
$dtt=date('Y-m-d', $date);
echo "<option value=$dtt>$dtt</option>";
$sql = "SELECT ID, data, laikas, laikas2 FROM vizitai4 WHERE darb_stat NOT LIKE 'Atlikta' and data LIKE '%" . $dtt . "%' OR
darb_stat IS NULL and data LIKE '%" . $dtt . "%' GROUP BY laikas";
$result = mysql_query($sql);
//rodymas lenteleje
echo $dtt;
echo "<table id=t01>
<tr>
<th>Data</th>
<th>Remonto pradžia</th>
<th>Remonto pabaiga</th>
</tr>";
if(mysql_num_rows($result) > 0) {
while( $row=mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['data'] . "</td>";
echo "<td>Remontas prasideda nuo " . $row['laikas'] . " </td>";
echo "<td>Numatomas remonto baigimo laikas " . $row['laikas2'] . " </td>";
echo "<td style='display: none;'><form method=post>
<input name=id type=hidden value='".$row['id']."';>
</form></td>";
echo "</tr>";
}
}else{
echo "<script>alert('Šios dienos įrašų nėra');</script>";
}
echo "</table>";
?>
</select>
<input type="submit" name="submit" value="Ieskoti">
</form>
</body>
</html>
From our exchange, the core of the issue is that you want interaction with the form to change the form itself and that you are trying to accomplish this with only PHP. Since PHP runs once to generate the page, you can not interact with the form elements after and have PHP react to those changes. You need a triggering effect that will re-query PHP. This is a job for a client-side language such as JavaScript.
Since you asked for an example here is a basic one. It is no easy task and has a bunch of moving parts, so I have a feeling that if you "barely know these things..." with what you have now, you will really be in the dark with this answer.
Follow the instruction and it should work for you. I have tested most of this (or have copied snippets from scripts I use) so pay attention to what things are called and where they are placed and read the notation. I suggest you create this directory/file structure as I have it, then test it out there before you attempt to do any modification to your working document(s). Once you do this stuff, if you don't know what you are doing it's near impossible to troubleshoot. Also take note I can not, in good conscience, answer this question without removing the reference to mysql_, those functions are deprecated or removed completely (php7):
/config.php
<?php
// This page goes on every main page of your site
// Comment out the error lines when live,
// you don't want errors showing on your page except in test
session_start();
ini_set("display_errors",1);
error_reporting(E_ALL);
define('DB_HOST','yourdbhost');
define('DB_USERNAME','yourdbusername');
define('DB_PASSWORD','yourdbpass');
define('DB_NAME','yourdbname');
define('SITE_ROOT',__DIR__);
define('DS', DIRECTORY_SEPARATOR);
define('CLASS_DIR', SITE_ROOT.DS.'core'.DS.'classes');
define('FUNCTION_DIR', SITE_ROOT.DS.'core'.DS.'functions');
require_once(FUNCTION_DIR.DS.'autoloader.php');
// This will help to autoload your classes
// **RESOURCE:** http://php.net/manual/en/function.spl-autoload-register.php
spl_autoload_register('autoloader');
// put whatever else you want on this page to make available to your site.
// You don't need the database connection however
/core/functions/makeOptions.php
<?php
/*
** #description This function uses a for loop to make your options
** You need to think how to use php to make your script(s)
** for you
** **RESOURCE:** http://php.net/manual/en/control-structures.for.php
** #param $max [int] This is how many options the function will make
*/
function makeOptions($max = 6)
{
for($i = 0; $i <= $max; $i++) {
$date = strtotime("+".$i." day");
$dtt = date('Y-m-d', $date);
echo '<option value="'.$dtt.'">'.$dtt.'</option>'.PHP_EOL;
}
}
/core/functions/autoloader.php
<?php
/*
** #description This function is used to autoload classes
** #param $class [string] This is automated and is populated by spl_autoload_register()
** **RESOURCE:** http://php.net/manual/en/function.spl-autoload-register.php
*/
function autoloader($class)
{
if(class_exists($class))
return true;
if(is_file($inc = CLASS_DIR.DS.$class.".php"))
include_once($inc);
}
/page1.php
<?php
// Include our config file
require_once(__DIR__.DIRECTORY_SEPARATOR.'config.php');
// Include the function to create our options
include_once(FUNCTION_DIR.DS.'makeOptions.php');
?><!DOCTYPE html>
<html>
<head>
<!-- include in head with anything else you need -->
<!-- **RESOURCE:** http://www.jquery.com/ -->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script>
$(document).ready(function(){
// Observe any change made to select with name=name
$(this).on('change','select[name=name]',function() {
// get the value of that selection
var thisVal = $(this).val();
// Use ajax to query page2.php
// **RESOURCE:** http://api.jquery.com/jquery.ajax/
$.ajax({
// This is the link that will load the contents of the form
url: '/page2.php',
data: {
// This is equivalent to $_POST['name']
"name":thisVal
},
type: 'POST',
success: function(response) {
// On success of the ajax, this will post the contents of
// page2.php into the div with id=loadspot
$("#loadspot").html(response);
}
});
});
});
</script>
</head>
<body>
<form method='post' action='grafikastest.php'>
<!--
I am not sure the placement of this text, but it can not be
in the middle of a drop down
-->
Pasirinkite datą: &nbsp
<select id="name" name="name">
<option value="">Select</option>
<!-- Apply the options function -->
<?php makeOptions(); ?>
</select>
<!-- This is where you will load the contents of the dropdown via ajax -->
<div id="loadspot"></div>
<input type="submit" name="submit" value="Ieskoti">
</form>
</body>
</html>
/core/classes/Database.php
<?php
/*
** #description This class is your new database which replaces your `mysql_`
** **RESOURCE:** http://php.net/manual/en/pdo.connections.php
*/
class Database
{
// static elements are kind of like a global
private static $singleton;
private static $con;
// This will save the class for reuse
public function __construct()
{
if(self::$singleton instanceof Database)
return self::$singleton;
self::$singleton = $this;
}
// This is the connection to the database
public function connect()
{
if(self::$con instanceof PDO)
return self::$con;
// Review the PDO class for instruction how to make this
// connection better using some PDO presets (Emulation of prepares, etc)
// **RESOURCE** http://php.net/manual/en/pdo.constants.php
self::$con = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME,DB_USERNAME,DB_PASSWORD);
return self::$con;
}
}
/core/classes/qEngine.php
<?php
/*
** #description This class is what you use to safely query your database
** **RESOURCE:** http://php.net/manual/en/pdo.prepare.php
** **RESOURCE:** http://php.net/manual/en/pdo.query.php
** **RESOURCE:** http://php.net/manual/en/pdostatement.fetch.php
**
*/
class qEngine
{
private static $con;
private $query;
public function query($sql = false,$bind = false)
{
// This checks if the connection is already saved
// You can also use "dependency injection" to pass your
// database connection to this class. I prefer to use
// a static connection but here is how that dependency works:
// **RESOURCE** http://code.tutsplus.com/tutorials/dependency-injection-in-php--net-28146
// **RESOURCE** https://en.wikipedia.org/wiki/Dependency_injection
if(!(self::$con instanceof PDO)) {
// Makes connection
$dbEngine = new \Database();
self::$con = $dbEngine->connect();
}
// Creates a bind array
// **RESOURCE** http://php.net/manual/en/pdostatement.bindvalue.php
// **RESOURCE** http://php.net/manual/en/pdostatement.execute.php (Example #2)
// **RESOURCE** http://php.net/manual/en/pdostatement.bindparam.php
if(!empty($bind)) {
$bArray = false;
foreach($bind as $key => $value) {
$bKey = ":{$key}";
$bArray[$bKey] = $value;
}
}
// If there is a bind array, it will run a prepare
if(!empty($bArray)) {
$this->query = self::$con->prepare($sql);
$this->query->execute($bArray);
}
// If no bind, it will run a straight query
else {
$this->query = self::$con->query($sql);
}
// This returns the object for method chaining
// **RESOURCE** http://stackoverflow.com/questions/3724112/php-method-chaining
return $this;
}
public function getResults()
{
// This will check that a query has been made
if(empty($this->query))
return 0;
// This will loop through the results and save to 1D array
while($result = $this->query->fetch(PDO::FETCH_ASSOC))
$row[] = $result;
// This will return either the array or a "0"
return (!empty($row))? $row : 0;
}
}
/core/functions/getListByDate.php
<?php
/*
** #description This function will query your database safely
** #param $date [string] Receives a date by string
*/
function getListByDate($date)
{
$bind = array('%'.$date.'%','%'.$date.'%');
return (new \qEngine()) ->query("SELECT `ID`,`data`,`laikas`,`laikas2`
FROM `vizitai4`
WHERE `darb_stat`
NOT LIKE 'Atlikta'
AND `data`
LIKE :0
OR `darb_stat`
IS NULL AND `data`
LIKE :1
GROUP BY `laikas`",$bind)
->getResults();
}
/page2.php
<?php
// Include our config file
require_once(__DIR__.DIRECTORY_SEPARATOR.'config.php');
// Include the function to query the database
include_once(FUNCTION_DIR.DS.'getListByDate.php');
// This is the page that the AJAX queries from page1.php
// See if the post has been made
if(!empty($_POST['name'])) {
// Fetch data from database
$vizitai4 = getListByDate($_POST['name']);
?>
<table id="t01">
<tr>
<th>Data</th>
<th>Remonto pradžia</th>
<th>Remonto pabaiga</th>
</tr>
<?php
if($vizitai4 != 0) {
foreach($vizitia4 as $row) {
?> <tr>
<td><?php echo $row['data']; ?></td>
<td>Remontas prasideda nuo <?php echo $row['laikas']; ?></td>
<td>Numatomas remonto baigimo laikas <?php echo $row['laikas2']; ?> </td>
<td style="display: none;"><input name="id[]" type="hidden" value="<?php echo $row['id']; ?>" /></td>
</tr>
<?php
}
}
else {
?>
<script>
alert('Šios dienos įrašų nėra');
</script>
<?php
}
?>
</table>
<?php
}
Here is the basic construct of what is happening:

How to call a function with database data inside another function?

EDITED: with new code after help from Sgt AJ.
Ok, so I am learning all the time, but since my coder stopped coding for our website, I am now having to learn PHP fully myself.
And I see all the time the coding where my coder made function calls inside other function calls.
So first of all the setup, we have a file for pretty much 95% of all functions in our site. That functions file basically has about 40-50 functions in it.
So I'm asking if someone can explain to me how is this possible to call a function inside another which works in the below instance, but when I try replicate it, it doesn't work? displays no data when I try to echo out the $user_info?
Like for example this function below: So Sgt AJ helped me solve the user avatar issue, so that will be removed from this question!
function showComments($v)
{
$mysqli = db_connect();
$v = mysqli_real_escape_string($mysqli,$v);
$sql = "SELECT * FROM `cl45-tbn_dir`.`comments` WHERE `v` = ? ORDER BY `id` ASC";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s",$v);
$stmt->execute();
$result = $stmt->get_result();
while ($myrow = $result->fetch_assoc()) {
if ($myrow['post_approved']==1){
$user_info = getUserInfo($myrow['poster_id']);
if ($user_info['user_avatar_type']==1) {
$avatar = "https://www.tubenations.com/forum/download/file.php?avatar=".$user_info['user_avatar'];
} else {
$avatar = "https://www.tubenations.com/forum/styles/Flato%20-%20LightBlue%20-%20Main%20Style/theme/images/no_avatar.gif";
}
echo '<div class="comment">
<div class="avatar">
<a href="https://www.tubenations.com/users.php?id='.$myrow['poster_id'].'">
<img src="'.$avatar.'" />
</div>
<div class="name"><a class ="myaccount'.$user_info['group_id'].'" href="https://www.tubenations.com/users.php?id='.$myrow['poster_id'].'">'.$user_info['username'].'</a></div>
<div class="date" title="report this post">'.date("d M Y",$myrow['post_time']).'<form action="" class="flag" method="post"><button type="submit" value="'.$myrow['id'].'" name="vote" id="votebutton" alt="vote"><img src="/images/flag.png" alt="report this post!" /></button></form></div>
<p>'.stripslashesFull(clean($myrow['post_text'])).'</p>
</div>';
}
}
$stmt->close();
$mysqli->close();
}
As you can see, there is a line where it calls another function getUserInfo, $user_info = getUserInfo($myrow['poster_id']); that is another function inside this file, and that basically connects to our forum database and gets data.
But when I try to replicate this method by using this type of call within another, it doesn't work.
So basically what I was trying to play with was trying to make a function for displaying X users data with this below function
function getYouTubeInfo($page)
{
#$id = $_GET['id'];
print_r ($userdata['user_id']);
echo $myrow['user_id'];
echo $userdata['user_id'];
$db_link = mysqli_connect ('localhost', 'HIDDEN', 'HIDDEN', 'HIDDEN');
if ( !$db_link )
{
die('following error occured: '.mysqli_error());
}
$query = "SELECT user_id, yt_channelTitle, channel_id FROM points WHERE channel_id IS NOT NULL AND yt_channelTitle IS NOT NULL ORDER BY channel_id DESC;";
if($result = mysqli_query($db_link, $query)){
echo "";
$i = -1;
$objectsPerPage = 14;
$show_records = FALSE;
while ($row = $result->fetch_assoc())
{
if (!isset($_SESSION['last_slide'])) { $_SESSION['last_slide'] = $row['channel_id']; }
if ($row['channel_id'] == $_SESSION['last_slide']) { $show_records = TRUE; }
if ($show_records)
{
$i = $i+1;
if ($i > $objectsPerPage) { $_SESSION['last_slide'] = $row['channel_id']; echo 'BREAK: ', $row['channel_id']; break; }
$page = abs(floor($i/$objectsPerPage));
$youtube_info = $row;
$userdata = getUserInfo($row['user_id']);
if ($userdata['user_avatar_type']==1) {
$avatar = "/forum/download/file.php?avatar=".$userdata['user_avatar'];
} else {
$avatar = "/images/no_image.png";
}
if (($i/$objectsPerPage)==$page)
{
if ($page !=0) {
echo "</div></div>";
}
echo '<div class="cslide-slide">
<div class="slideTitles">Youtube Users Slide '.$page.'</div>
<div class="sections grouped">';
}
echo '
<div class="cols span_1_of_2">
<div class="memberTitles">'.$youtube_info['yt_channelTitle'].''.$i.';</div>
<div class="memberPicture"><img src="'.$avatar.'" title="Tube Nations Profile Picture" alt="Tube Nations Profile Picture"/></div>
<div class="memberTwitter"><div class="g-ytsubscribe" data-channelid="'.$youtube_info['channel_id'].'" data-layout="full" data-count="default" data-onytevent="onYtEvent"></div></div>
</div> ';
}
}
echo '</div></div>';
}
mysqli_free_result($result);
echo $_SESSION['last_slide'];
session_destroy();
mysqli_close($db_link);
}
So basically in the page in question, youtube.php, I just echo this getYouTubeInfo function.
This function I need to try get the users profile pictures that are in the forum database which is from the getUserInfo($id).
Also on a side note, I also can not work out how to re arrange the $i and $objectsPerPage variables and if statements so I can then use the $page inside the query LIMIT $page; because at the moment the page crashes with no limit, so I have had to put limit to 16 for now.
I use a jQuery slide script for displaying X per slide, so if I can just somehow work out how to make the query further down after the variables and if statements for the page stuff or get any help, I would appreciate it.
EDIT UPDATED REPLY: So now the problem is it now displays X per slide/page, but it now displays a gap after 8 results are displayed when it shows 10, but with a gap, and then on the the next slide button isn't showing up? so Sgt AJ said we need to somehow connect it to the jquery?, so I now will add a tag for jquery. (But can i say a big thanks to Sgt AJ for his help, really appreciate it) :)
Wow, you've got several things going on here.
First, your query right now says LIMIT 0;, which means you should get zero rows returned. Are you getting data back from this query??
Second, to get the page and items per page working right, you could go with something like this:
In your loop, keep your i=i+1 line
Add this if:
if ($i == $objectsPerPage)
{
++$page;
i = 1;
}
This will increment the page counter once the page is full, then reset the item count for the next page.
I just wanted to add more to my question, I think now the answer is with AJAX, so I think I need to somehow make the cslide jquery code recall the getYoutubeInfo($page) function
the jquery code for the cslide is this:
(function($) {
$.fn.cslide = function() {
this.each(function() {
var slidesContainerId = "#"+($(this).attr("id"));
var len = $(slidesContainerId+" .cslide-slide").size(); // get number of slides
var slidesContainerWidth = len*100+"%"; // get width of the slide container
var slideWidth = (100/len)+"%"; // get width of the slides
// set slide container width
$(slidesContainerId+" .cslide-slides-container").css({
width : slidesContainerWidth,
visibility : "visible"
});
// set slide width
$(".cslide-slide").css({
width : slideWidth
});
// add correct classes to first and last slide
$(slidesContainerId+" .cslide-slides-container .cslide-slide").last().addClass("cslide-last");
$(slidesContainerId+" .cslide-slides-container .cslide-slide").first().addClass("cslide-first cslide-active");
// initially disable the previous arrow cuz we start on the first slide
$(slidesContainerId+" .cslide-prev").addClass("cslide-disabled");
// if first slide is last slide, hide the prev-next navigation
if (!$(slidesContainerId+" .cslide-slide.cslide-active.cslide-first").hasClass("cslide-last")) {
$(slidesContainerId+" .cslide-prev-next").css({
display : "block"
});
}
// handle the next clicking functionality
$(slidesContainerId+" .cslide-next").click(function(){
var i = $(slidesContainerId+" .cslide-slide.cslide-active").index();
var n = i+1;
var slideLeft = "-"+n*100+"%";
if (!$(slidesContainerId+" .cslide-slide.cslide-active").hasClass("cslide-last")) {
$(slidesContainerId+" .cslide-slide.cslide-active").removeClass("cslide-active").next(".cslide-slide").addClass("cslide-active");
$(slidesContainerId+" .cslide-slides-container").animate({
marginLeft : slideLeft
},250);
if ($(slidesContainerId+" .cslide-slide.cslide-active").hasClass("cslide-last")) {
$(slidesContainerId+" .cslide-next").addClass("cslide-disabled");
}
}
if ((!$(slidesContainerId+" .cslide-slide.cslide-active").hasClass("cslide-first")) && $(".cslide-prev").hasClass("cslide-disabled")) {
$(slidesContainerId+" .cslide-prev").removeClass("cslide-disabled");
}
});
// handle the prev clicking functionality
$(slidesContainerId+" .cslide-prev").click(function(){
var i = $(slidesContainerId+" .cslide-slide.cslide-active").index();
var n = i-1;
var slideRight = "-"+n*100+"%";
if (!$(slidesContainerId+" .cslide-slide.cslide-active").hasClass("cslide-first")) {
$(slidesContainerId+" .cslide-slide.cslide-active").removeClass("cslide-active").prev(".cslide-slide").addClass("cslide-active");
$(slidesContainerId+" .cslide-slides-container").animate({
marginLeft : slideRight
},250);
if ($(slidesContainerId+" .cslide-slide.cslide-active").hasClass("cslide-first")) {
$(slidesContainerId+" .cslide-prev").addClass("cslide-disabled");
}
}
if ((!$(slidesContainerId+" .cslide-slide.cslide-active").hasClass("cslide-last")) && $(".cslide-next").hasClass("cslide-disabled")) {
$(slidesContainerId+" .cslide-next").removeClass("cslide-disabled");
}
});
});
// return this for chainability
return this;
}
}(jQuery));
I also tweaked the code that Sgt AJ helped me with again, By adding a session_destroy() just before the closing brace. And also a few other bits, because I noticed that when you refreshed the page over and over, it just loaded the next 14 results, instead of the same first 14 results, so the actual code and logic seems to be working. so it is basically now down to we need to find a way to use AJAX and recall the function from the onclick event of the next/previous buttons.

Menu created with MySQL only works within website not outside

I hope somebody can help me, because i got an menu that is auto generated via my MySQL db.
Because i got the menu to work inside the website and with that i mean it works with "test.dk/about" but the a href is empty when it's going out of the website like "http://google.com"...
btw it's just a very simple UL LI menu no dropdown or something.
Here is my script
static function build_menu()
{
$result = mysql_query("SELECT * FROM menu");
$menu = array();
while ($row = mysql_fetch_assoc($result)) {
if ($row["is_external"]) {
$url = $row["url"];
} else if (empty($row["is_external"])) {
$url = get_page_url($row["page_id"]);
}
$menu[] = array("name" => $row["name"], "page_id" => $row["page_id"], "is_external" => $row["url"], "url" => $url);
}
return $menu;
}
static function get_page_url($page_id)
{
$result = mysql_query("SELECT view_id FROM page WHERE id = '$page_id'");
$result = mysql_fetch_assoc($result);
$view_id = $result["view_id"];
$result = mysql_query("SELECT listen_path FROM view WHERE id = '$view_id'");
$result = mysql_fetch_assoc($result);
$listen_path = $result["listen_path"];
return $listen_path;
}
static function render()
{
$result = mysql_query("SELECT * FROM menu"); ?>
<div class="menu">
<ul><?php while ($item = mysql_fetch_assoc($result)) { ?>
<li><?php echo $item["name"] ?>
</li> <?php } ?></ul></div><?php
}
How can i fix it, so it works both internal and external?
<div class="menu"> <ul> <li>Homepage</li> <li>About</li> <li>Develop</li> <li>Support</li>
This should be <li>Support</li>; </ul> </div>
You only check for an external link in the function build_menu(), but this function isn't called anywhere from your render() function.
The render() function only calls get_page_url() which doesn't distinguish between internal and external links.
Href parameter of external URL must start with protocol declaration, so with "http://" in your case.
So change your code in condition inside the function "build_menu", if the URL is external, add "http://" to it, something like this:
$url = 'http://'.$row["url"];
I got it work after a while!
I simply just created an If else statement in the render function
static function render(){
$menu_items = self::get();
?><div class="menu"><ul><?php while ($item = mysql_fetch_assoc($menu_items)) { ?>
<li><a href="<?php
if(empty($item["is_external"]))
{
echo self::get_page_url($item["page_id"]);
}
else if($item["is_external"] = 1)
{
echo $item["url"];
}
?>"><?php echo $item["name"] ?></a>
</li> <?php } ?></ul></div><?php
}

PHP + Javascript parent function not getting called

Alright I've been trying to find an answer to this for hours already but I couldn't resolve it myself.
I'm trying to call a Javascript parent function from a PHP function, however, it is not getting called.
When using the onclick method onclick='parent.dosomething(); everything seems to work fine but if I try to call the function by echo'ing it out, it would just fail for some reason.
echo "<script>parent.reloadprofmessages();</script>"; //this is what is not getting called
Here's the PHP function:
function checkactivity($username)
{
//These are just queries being executed (irrelevant)
$querystats = "SELECT users.fullname, activity.id, activity.sender, activity.receiver, activity.type, activity.dateposted, activity.seen, activity.related FROM activity, users WHERE activity.receiver = '$username' && activity.seen = '0' ORDER BY id DESC LIMIT 1";
$resultstats = mysql_query($querystats);
$num_stats = mysql_num_rows($resultstats);
$rowactivity = mysql_fetch_assoc($resultstats);
//End of queries
if($num_stats > 0) //If there are registries
{
$user = $_SESSION['Username'];
$activity_date = $rowactivity["dateposted"];
$activity_type = $rowactivity["type"];
$activity_sender = $rowactivity["sender"];
$timeactivity = strtotime( "$activity_date" );
$actualtime = time();
$timetoseconds = $actualtime - $timeposted;
$timetominutes = floor($timepassedtoseconds/60);
if($timetominutes < 2)
{
if($activity_sender != $user)
{
if($activity_type == 1) //Messages
{
echo "<script>parent.reloadprofmessages();</script>"; //this is what is not getting called
}
}
}
}
}
And this is my Javascript function at the parent page:
function reloadprofmessages()
{
$('#friendrequests').load('showprofmessages.php?username=<?php echo $actualuser; ?>').fadeIn("slow");
} //refreshes messages
I pressed CTRL + Shift + I in Google Chrome to get to the developer tools, Network > page that does the request that calls the PHP function > Preview and this was what I received:
<script>parent.reloadprofmessages();</script>
However, the function is not getting called.
Resolving this would solve me a lot of problems, to me it is actually still a mystery to know why it doesn't work since it has worked in other cases.
Thank you for your help in advance.
It's not a good idea to fetch javascript and execute it with AJAX. What I would suggest is to firstly change your PHP to this:
if($activity_type == 1) //Messages
{
echo "1";
}
else {
echo "0";
}
Then change your Javascript to this:
function reloadprofmessages()
{
var can_reload = $.ajax({ url: "showprofmessages.php?username=<?php echo $actualuser; ?>" });
if (can_reload) {
parent.erloadprofmessages();
}
}
Hope that helps
Add the type attribute for script tag
echo "<script type='text/javascript' >parent.reloadprofmessages();</script>";
and remember to define the javascript function before this line
So here is what was wrong: (Showing errors)
function checkactivity($username)
{
//These are just queries being executed (irrelevant)
$querystats = "SELECT users.fullname, activity.id, activity.sender, activity.receiver, activity.type, activity.dateposted, activity.seen, activity.related FROM activity, users WHERE activity.receiver = '$username' && activity.seen = '0' ORDER BY id DESC LIMIT 1";
$resultstats = mysql_query($querystats);
$num_stats = mysql_num_rows($resultstats);
$rowactivity = mysql_fetch_assoc($resultstats);
//End of queries
if($num_stats > 0) //If there are registries
{
$user = $_SESSION['Username'];
$activity_date = $rowactivity["dateposted"];
$activity_type = $rowactivity["type"];
$activity_sender = $rowactivity["sender"];
$timeactivity = strtotime( "$activity_date" ); //$timeactivity was not being used
$actualtime = time();
$timetoseconds = $actualtime - $timeposted; //$timeposted doesn't even exist, in other words I wasn't even converting the $activity_date timestamp to time.
$timetominutes = floor($timepassedtoseconds/60);
if($timetominutes < 2)
{
if($activity_sender != $user)
{
if($activity_type == 1) //Messages
{
echo "<script>parent.reloadprofmessages();</script>"; //this was not the correct way of calling a function from the parent page.
}
}
}
}
}
About the Javascript function:
This is what I ended with:
var auto_refresh = setInterval(
function reloadstring()
{
$.get("checknewactivity.php?vprofile=<?php echo $actualuser; ?>", function(activity){
if (activity == 1)
{
$('#profcommentsdiv').load('showprofmessages.php?vprofile=<?php echo $actualuser; ?>').fadeIn("slow");
}
});
}, 1000); // refresh every 1000 milliseconds
And now it works, thank you for your help, I really appreciate it, and as usual, I always get to a safer solution after asking it here.

Weird problem with PHP Breadcrumb Script

I'm using Mick Sears' php breadcrumb script - found here:
http://www.roscripts.com/PHP_breadcrumbs-118.html
I've used this script several times with no problems. But with this one site I'm having the weirdest problem... Home page - fine. Level 1 page - fine. But every time I move to a level2 page, the correct level1 crumb is replaced by "Help". The link on the crumb is the correct one for the help page. This happens even if I clear all browser caches and don't go to the Help section of the site at all.
The site is http://www.fastexas.org. The script is there, but I gave the breadcrumb div display:none; until I can figure this out.
This script seems to have been around awhile and I'm wondering if anyone else has seen this problem.
The Breadcrumb Script:
<?php
class Breadcrumb{
var $output;
var $crumbs = array();
var $location;
function Breadcrumb(){
if ($_SESSION['breadcrumb'] != null){
$this->crumbs = $_SESSION['breadcrumb'];} }
function add($label, $url, $level){
$crumb = array();
$crumb['label'] = $label;
$crumb['url'] = $url;
if ($crumb['label'] != null && $crumb['url'] != null && isset($level)){
while(count($this->crumbs) > $level){
array_pop($this->crumbs); }
if (!isset($this->crumbs[0]) && $level > 0){
$this->crumbs[0]['url'] = "/index.php";
$this->crumbs[0]['label'] = "Home";}
$this->crumbs[$level] = $crumb;}
$_SESSION['breadcrumb'] = $this->crumbs;
$this->crumbs[$level]['url'] = null;}
function output(){
echo "<ul>";
foreach ($this->crumbs as $crumb){
if ($crumb['url'] != null){
echo "<li> <a href='".$crumb['url']."' title='".$crumb['label']."'>".$crumb['label']."</a></li> ";} else {
echo "<li class='last'>".$crumb['label']."</li> ";}}
echo "</ul>";}}
?>
Each page begins with something like:
<?php session_start();
$level= '1';
$label= 'Honors Circle';
$url= '/honors/'; include($_SERVER['DOCUMENT_ROOT']."/includes/Breadcrumb.php");
$trail = new Breadcrumb();
$trail->add($label, $url, $level); ?>
or
<?php
session_start();
$level= '2';
$label= 'Districts';
$url= '/honors/district.php';
include($_SERVER['DOCUMENT_ROOT']."/includes/Breadcrumb.php");
$trail = new Breadcrumb();
$trail->add($label, $url, $level);
?>
And to print the breadcrumb trail:
<div id="breadcrumb"><?php $trail->output(); ?></div>

Categories