Tycoon Talk
Become a Big fish!
The number 1 forum for online business!
Post topics, ask questions, share your knowledge.
Tycoon Talk is part of Freelancer.com - find skilled workers online at a fraction of the cost.

PHP Forum


You are currently viewing our PHP Forum as a guest. Please register to participate.
Login



Freelance Jobs

Reply
Help with small piece of code..
Old 06-11-2006, 05:59 PM Help with small piece of code..
Average Talker

Posts: 16
Trades: 0
Hi,

I'm not a programmer but I'm trying very hard to get something working. Perhaps someone knows the solution to the following problem.

I have this piece of code:

PHP Code:
<? 
$index 
strrpos$_SERVER['PHP_SELF'], "/" );
$dir substr$_SERVER['PHP_SELF'], 0$index );
$rating_game = new pkrating('test');
print 
$rating_game->get_booth_html();
?>
The first 2 lines were inserted later. They get the current path and strip it down. Works great when I do a echo for $dir

The last two lines are from the original script and independently, they work fine. The word test is stored in the database by the script.

My problem is that I want the output of $dir (the stripped path) replacing the word test in the 3rd line. So the stripped path should be what is stored in the database.

The ' ' should stay as they are needed by the original script. If I take them out, the script stops working. If I simply add $dir there, the text $dir is stored in the database.

Anyone have any idea? Help would be much appreciated!

Last edited by Falconer; 06-13-2006 at 04:13 PM..
Falconer is offline
Reply With Quote
View Public Profile
 
 
Register now for full access!
Old 06-11-2006, 10:56 PM Re: Help with small piece of code..
mgraphic's Avatar
Truth Seeker

Latest Blog Post:
JAMISONTUNES
Posts: 2,918
Name: Keith Marshall
Location: Connecticut
Trades: 0
Any chance of showing us the pkrating class script?
__________________

<mgraphic /> - I don't have a solution but I admire the problem.
mgraphic is offline
Reply With Quote
View Public Profile
 
Old 06-12-2006, 02:02 AM Re: Help with small piece of code..
Average Talker

Posts: 16
Trades: 0
Yup, it's a free script:

PHP Code:
<?
#############################################################################################
# PAGE:    rating.inc
# AUTHOR:  M. Shepanski
# PURPOSE: Allows you to have a user rating on your PHP Page
# LICENSE: FREE TO USE!, Don't let my hard work go to waste, include a plug to my page
#          on your site if you are nice if you plan on using this! :)
#############################################################################################

#--------------------------------------------------------------------------------------------
# EDIT THE OPTIONS BELOW
#--------------------------------------------------------------------------------------------
# Note: It is probably a good idea to use the PHP variable '$_SERVER['HTTP_HOST'] as seen
#       below.  This is because AJAX will only work if the request is coming from the 
#       same domain as it is sent from.  Without it, your script will NOT work for both
#       http://www.yourdomain.com and http://yourdomain.com.

$pkrating_HTTPFOLDER    "http://".$_SERVER['HTTP_HOST']."/php/review";        // FULL HTTP PATH TO SCRIPT FOLDER (NO trailing slash!)
$pkrating_dbserver      "localhost";                                              // Database Server
$pkrating_dbuser        "*******";                                             // Database Username
$pkrating_dbpass        "******";                                             // Database Password
$pkrating_dbname        "*****";                                             // Database Name
$pkrating_tbname        "********";                                              // Database Table

$pkrating_image_on      $pkrating_HTTPFOLDER."/pkstar-on.gif";                    // FULL Image
$pkrating_image_half    $pkrating_HTTPFOLDER."/pkstar-half.gif";                  // HALF Image
$pkrating_image_off     $pkrating_HTTPFOLDER."/pkstar-off.gif";                   // EMPTY Image
$pkrating_image_hover   $pkrating_HTTPFOLDER."/pkstar-hover.gif";                 // HOVER Image


#--------------------------------------------------------------------------------------------
# DO NOT EDIT BELOW THIS LINE - Unless you know PHP. :)
#--------------------------------------------------------------------------------------------
$included_js 0;                   // BOOLEAN Holds weather the JS File was included or not.


#############################################################################################
# CLASS:   pkrating
# AUTHOR:  M. Shepanski
# PURPOSE: Main PKRating Class.  Holds all the usefull functions to gather rating data
#   based on the rateid given to this object.  The Functions below should be documented
#   enough for you to understand. :)
#############################################################################################
class pkrating {
    var 
$rateid;                    // RateID for this current Rating Object
    
var $jsclassname;               // Javascript Variable Name for this Object
    
var $max_vote;                  // Maximum Vote Value (Stored to save DB Queries)
    
var $avg_vote;                  // Average Vote Value (Stored to save DB Queries)
    
var $min_vote;                  // Minimum Vote Value (Stored to save DB Queries)
    
var $user_vote;                 // Current User's Vote Value (Stored to save DB Queries)
    
var $num_votes;                 // Total Number of Votes (Stored to save DB Queries)

    #---------------------------------------------------------------------------------
    # FUNCTION: Constructor
    #---------------------------------------------------------------------------------
    
function pkrating($rateid) {
        GLOBAL 
$pkrating_dbserver$pkrating_dbuser$pkrating_dbpass;
        
$this->rateid $rateid;
        
$this->jsclassname "PKR{$this->rateid}";
        
mysql_connect($pkrating_dbserver$pkrating_dbuser$pkrating_dbpass) or die ('Cannot Connect: ' mysql_error());
        
$this->_create_dbtable();
    }

    
#---------------------------------------------------------------------------------
    # FUNCTION: get_required_hidden_html()
    # PURPOSE:  This function is required to be called before you can add a booth
    #   to your page.  It is placed in a function so that you have the power to easily
    #   place this code whereever you desire on your page.
    #---------------------------------------------------------------------------------
    
function get_required_hidden_html() {
        GLOBAL 
$pkrating_HTTPFOLDER$pkrating_image_on$pkrating_image_half$pkrating_image_off$pkrating_image_hover$included_js;
        
$html  "<script type='text/javascript' src='$pkrating_HTTPFOLDER/rating.js'></script>\n";
        
$html .= "<img src='$pkrating_image_on' alt='hidden' style='display: none;' />\n";
        
$html .= "<img src='$pkrating_image_half' alt='hidden' style='display: none;' />\n";
        
$html .= "<img src='$pkrating_image_off' alt='hidden' style='display: none;' />\n";
        
$html .= "<img src='$pkrating_image_hover' alt='hidden' style='display: none;' />\n";
        
$included_js 1;
        return 
$html;
    }

    
#---------------------------------------------------------------------------------
    # FUNCTION: get_average_rating()
    # PURPOSE:  returns the average rating for this object.
    #---------------------------------------------------------------------------------
    
function get_booth_html() {
        GLOBAL 
$pkrating_HTTPFOLDER$pkrating_image_on$pkrating_image_half$pkrating_image_off$pkrating_image_hover$included_js;
        if (
$included_js == 1) {
            
$average_rating $this->get_average_rating();
            
$remainder $this->get_average_rating() - floor($this->get_average_rating());
            
$jscalls "";
            
$html  "    <div class='pk_vote_booth'>\n";
            
$html .= "      <script type='text/javascript'>var {$this->jsclassname}=new pkrating('{$this->rateid}', '$pkrating_image_on', '$pkrating_image_half', '$pkrating_image_off', '$pkrating_image_hover')</script>\n";
            
$html .= "      <span id='pkr_{$this->rateid}_booth'>\n  ";
            for(
$i=1$i<6$i++) {
                
srand((double)microtime()*1000000); 
                
$link  "$pkrating_HTTPFOLDER/rating.php?rateid={$this->rateid}&amp;vote={$i}&amp;random=".rand(0,999999999);
                if(
$this->get_user_rating() == "null") {
                    
$jscalls "style='cursor: pointer' id='pkr_{$this->rateid}_{$i}' onclick=\"{$this->jsclassname}.pkclick('$link')\" onmouseout=\"{$this->jsclassname}.pkflipimages($average_rating)\" onmouseover=\"{$this->jsclassname}.pkmouseover($i)\"";
                }
                if (
floor($this->get_average_rating()) >= $i) {
                    
$html .= "<img $jscalls src='$pkrating_image_on' alt='' />";
                } elseif ((
floor($this->get_average_rating()) == $i-1) && ($remainder >= 0.5)) {
                    
$html .= "<img $jscalls src='$pkrating_image_half' alt='' />";
                } else {
                    
$html .= "<img $jscalls src='$pkrating_image_off' alt='' />";
                }
            }
            
$html .= "<br><b>total votes: ".$this->get_num_votes()."\n - </b>";
            if (
$this->get_user_rating() == "null") {
                
$html .= "<b>give us yours!</b> </span>\n";
            } else { 
                
$html .= "<b>your score: ".$this->get_user_rating()."/5</b> </span>\n";
            }
            
$html .= "</div>\n";
        } else {
            
$html "ERROR: You Must call <i>pkrating::get_required_hidden_html()</i> before you can include this code!";
        }
        return 
$html;
    }

    
#---------------------------------------------------------------------------------
    # FUNCTION: get_average_rating()
    # PURPOSE:  returns the average rating for this object.
    #---------------------------------------------------------------------------------
    
function get_average_rating() {
        GLOBAL 
$pkrating_dbname$pkrating_tbname;
        if (!isset(
$this->avg_vote)) {
            
$query "SELECT avg(user_rating) FROM `$pkrating_dbname`.`$pkrating_tbname`";
            
$query .= "  WHERE rateid='{$this->rateid}'";
            
$row mysql_fetch_array(mysql_query($query));
            if (
$row[0] == NULL) { return "0"; }
            
$this->avg_vote $row[0];
        }
        return 
$this->avg_vote;
    }

    
#---------------------------------------------------------------------------------
    # FUNCTION: get_users_rating()
    # PURPOSE:  Returns the rating selected by THIS user.
    #---------------------------------------------------------------------------------
    
function get_user_rating() {
        GLOBAL 
$pkrating_dbname$pkrating_tbname;
        if (!isset(
$this->user_vote)) {
            
$query  "SELECT user_rating FROM `$pkrating_dbname`.`$pkrating_tbname`";
            
$query .= "  WHERE rateid='{$this->rateid}'";
            
$query .= "  AND user_ip='".$_SERVER['REMOTE_ADDR']."'";
            
$row mysql_fetch_array(mysql_query($query));
            if (
$row[0] == NULL) { return "null"; }
            
$this->user_vote $row[0];
        }
        return 
$this->user_vote;
    }

    
#---------------------------------------------------------------------------------
    # FUNCTION: get_maximum_rating()
    # PURPOSE:  Returns the maximum rating for this object.
    #---------------------------------------------------------------------------------
    
function get_maximum_rating() {
        GLOBAL 
$pkrating_dbname$pkrating_tbname;
        if (!isset(
$this->max_vote)) {
            
$query "SELECT max(user_rating) FROM `$pkrating_dbname`.`$pkrating_tbname`";
            
$query .= "  WHERE rateid='{$this->rateid}'";
            
$row mysql_fetch_array(mysql_query($query));
            if (
$row[0] == NULL) { return "0"; }
            
$this->max_vote $row[0];
        }
        return 
$this->max_vote;
    }

    
#---------------------------------------------------------------------------------
    # FUNCTION: get_minimum_rating()
    # PURPOSE:  returns the minimum rating for this object.
    #---------------------------------------------------------------------------------
    
function get_minimum_rating() {
        GLOBAL 
$pkrating_dbname$pkrating_tbname;
        if (!isset(
$this->min_vote)) {
            
$query "SELECT min(user_rating) FROM `$pkrating_dbname`.`$pkrating_tbname`";
            
$query .= "  WHERE rateid='{$this->rateid}'";
            
$row mysql_fetch_array(mysql_query($query));
            if (
$row[0] == NULL) { return "0"; }
            
$this->min_vote $row[0];
        }
        return 
$this->min_vote;
    }

    
#---------------------------------------------------------------------------------
    # FUNCTION: get_num_votes()
    # PURPOSE:  Returns the number of votes found in the DB for this object
    #---------------------------------------------------------------------------------
    
function get_num_votes() {
        GLOBAL 
$pkrating_dbname$pkrating_tbname;
        if (!isset(
$this->num_votes)) {
            
$query  "SELECT count(*) FROM `$pkrating_dbname`.`$pkrating_tbname`";
            
$query .= "  WHERE rateid='{$this->rateid}'";
            
$row mysql_fetch_array(mysql_query($query));
            if (
$row[0] == NULL) { return "null"; }
            
$this->num_votes $row['count(*)'];
        }
        return 
$this->num_votes;
    }

    
#---------------------------------------------------------------------------------
    # FUNCTION: _submit_vote()
    # PURPOSE:  Submits the Users Vote if it has not allready been registered.
    #---------------------------------------------------------------------------------
    
function _submit_vote($rating) {
        GLOBAL 
$pkrating_dbname$pkrating_tbname;
        if (
$this->get_user_rating() == "null") {
            
$query  "INSERT INTO `$pkrating_dbname`.`$pkrating_tbname` SET";
            
$query .= "  `rateid`='".$_GET['rateid']."',";
            
$query .= "  `user_rating`=$rating,";
            
$query .= "  `user_ip`='".$_SERVER['REMOTE_ADDR']."'";
            
$result mysql_query($query);
            
//if (!$result) { print "SQL Error: ".mysql_error(); }
            //else { print "Vote Submitted: $rating"; }
            
print $this->get_num_votes().";";
            print 
$this->get_average_rating().";";
            print 
$rating;
        }
    }

    
#---------------------------------------------------------------------------------
    # FUNCTION: create_table($dbname, $tbname)
    # PURPOSE: Creates the DB Table if it doesn't allready exist.
    #---------------------------------------------------------------------------------
    
function _create_dbtable() {
        GLOBAL 
$pkrating_dbname$pkrating_tbname;
        
$query  "CREATE TABLE IF NOT EXISTS `$pkrating_dbname`.`$pkrating_tbname` (";
        
$query .= "  `voteid` int(9) NOT NULL auto_increment,";
        
$query .= "  `rateid` varchar(16) NOT NULL,";
        
$query .= "  `user_rating` int(1) NOT NULL,";
        
$query .= "  `user_ip` varchar(15) NOT NULL,";
        
$query .= "  PRIMARY KEY (`voteid`)";
        
$query .= ") ENGINE=MyISAM";
        
$result mysql_query($query);
        if (!
$result) { die('Invalid query: ' mysql_error()); }
    }

}


#---------------------------------------------------------------------------------
# THE CODE BELOW IS USED BY THE HTTP_REQUEST OBJECT CREATED IN THE JAVASCRIPT
# FUNCTIONS FOR THIS RATER (AJAX).  IF YOU REMOVE IT, NO VOTES WILL BE PROCESSED.
#---------------------------------------------------------------------------------
if((isset($_GET['rateid'])) && (isset($_GET['vote'])))  {
    print 
"{$_GET['rateid']};";
    
$pkrater = new pkrating($_GET['rateid']);
    
$pkrater->_submit_vote($_GET['vote']);
}

EDIT: (0beron) password scrubbed.

Last edited by 0beron; 06-13-2006 at 08:01 PM..
Falconer is offline
Reply With Quote
View Public Profile
 
Old 06-12-2006, 02:09 PM Re: Help with small piece of code..
cdwhalley.com's Avatar
Skilled Talker

Posts: 75
Trades: 0
Falconer - I sure hope you haven't just told us all your MySQL username and password...


But anyway -
Quote:
The ' ' should stay as they are needed by the original script.
Can you elaborate on this? It doesn't make sense to me.

Last edited by cdwhalley.com; 06-12-2006 at 02:12 PM..
cdwhalley.com is offline
Reply With Quote
View Public Profile Visit cdwhalley.com's homepage!
 
Old 06-13-2006, 12:17 AM Re: Help with small piece of code..
mgraphic's Avatar
Truth Seeker

Latest Blog Post:
JAMISONTUNES
Posts: 2,918
Name: Keith Marshall
Location: Connecticut
Trades: 0
I noticed that the function _create_dbtable() is only allowing 16 charatures for the filed rateid. This *may* have something to do with it.
__________________

<mgraphic /> - I don't have a solution but I admire the problem.
mgraphic is offline
Reply With Quote
View Public Profile
 
Old 06-13-2006, 07:52 AM Re: Help with small piece of code..
Ultra Talker

Posts: 256
Location: Auckland, New Zealand
Trades: 0
OK, seems simple to me:

PHP Code:
<?php 
$index 
strrpos$_SERVER['PHP_SELF'], "/" );
$dir substr$_SERVER['PHP_SELF'], 0$index );
$rating_game = new pkrating("$dir");
print 
$rating_game->get_booth_html();
?>
You should look at PHP's manual for interpolation to get an understanding of using double quotes and single quotes. Also try to use the long way of writing <?php instead of the short hand <? this was certainly a bad mistake and causes many incompatibilities with transfer the script to other servers.

Cheers,

MC
__________________
#------------------------------signature---------------------------------------------------------------------------------#
Quote:
I am well recognised for what I don't do than what I do. Chores are just one of those things.
mastercomputers is offline
Reply With Quote
View Public Profile Visit mastercomputers's homepage!
 
Old 06-13-2006, 03:51 PM Re: Help with small piece of code..
Average Talker

Posts: 16
Trades: 0
Hi!

@cdwhalley.com: bummer, I did too Fortunately I have the habit to change passes when I'm done with the work, but... I'm not done yet so that was live for a while. *blush*

What I mean is that if I change or remove the ' ' around $dir, the script stops to work. (I just tried mastercomputers suggestion of using "$dir" instead but that gives the same result: the hover/select function stops working.

@mgraphic: Sound plausible, not sure if I can solve this, but I'll see if I can.

@mastercomputers: Thanks for your reponse. However... it doesn't work.

Even with my meager skills (I haven't written the code myself), I already tried that. The result is this:
http://www.hookedgamers.com/reviews/...ace_rangers_2/

See the 5 orange hooks on the right? It should let you vote for the game by hovering over and clicking on the score you'd like to award it.

The working example with the manual input can be found here:
http://www.hookedgamers.com/reviews/...official_game/

note: currently testing so sometimes the first one will work too

Last edited by Falconer; 06-13-2006 at 04:23 PM..
Falconer is offline
Reply With Quote
View Public Profile
 
Old 06-13-2006, 04:46 PM Re: Help with small piece of code..
Average Talker

Posts: 16
Trades: 0
Okay, another hour of testing and I've learned a little more, but haven't fixed it.

@mrgraphic: Your 16 chars idea didn't solve the current problem but it will probably have become a problem if you hadn't mentioned it. Thank you.

The idea also started me thinking about characters that the script might not accept. I tried the output of $dollar and stuck it in manually. It did not work (at this time I had increased the # of characters that the database would accept) until I stripped all the / out of the path.

So, now I need to solve two problems.

1) How to get the $dir in the 3rd line to be recognized as code (right now it assumes it is text, it doesn't recognize it as php code)
2) How do I alter the first 2 lines so that the it strips the slashes (/) from the path.

Any guru's out there who can help?
Falconer is offline
Reply With Quote
View Public Profile
 
Old 06-13-2006, 05:08 PM Re: Help with small piece of code..
mgraphic's Avatar
Truth Seeker

Latest Blog Post:
JAMISONTUNES
Posts: 2,918
Name: Keith Marshall
Location: Connecticut
Trades: 0
To help with understanding of quoting in php, different methods will produce different results.

PHP Code:
$rating_game = new pkrating($dir); 
Will send the actual string

PHP Code:
$rating_game = new pkrating("$dir"); 
Will send the actual string

PHP Code:
$rating_game = new pkrating('$dir'); 
Will send the string literally
__________________

<mgraphic /> - I don't have a solution but I admire the problem.
mgraphic is offline
Reply With Quote
View Public Profile
 
Old 06-13-2006, 10:21 PM Re: Help with small piece of code..
Ultra Talker

Posts: 256
Location: Auckland, New Zealand
Trades: 0
Because the problem is the characters, not that they are being stipped but it's unacceptable for MySQL, so you must escape those characters.

Code:
<?php 
$index = strrpos( $_SERVER['PHP_SELF'], "/" );
$dir = substr( $_SERVER['PHP_SELF'], 0, $index + 1 );
$dir = mysql_real_escape_string($dir);
$rating_game = new pkrating($dir);
print $rating_game->get_booth_html();
?>
And that 16 varchar would be a problem if the string is larger than 16 characters, so you must change this either dynamically, or set it larger to hold your string.

Other than these things, I would have to look further into your problem but these are the most noticable ones.

Cheers,

MC
__________________
#------------------------------signature---------------------------------------------------------------------------------#
Quote:
I am well recognised for what I don't do than what I do. Chores are just one of those things.
mastercomputers is offline
Reply With Quote
View Public Profile Visit mastercomputers's homepage!
 
Old 06-14-2006, 01:55 AM Re: Help with small piece of code..
Average Talker

Posts: 16
Trades: 0
@mastercomputers: Using your last suggestion had no result. The $dir was still outputting the slashes. Removing the ' ' around $dir caused the script to malfunction again, in the exact same way.

So, I think that officially means I'm stuck. I understand mgraphics' explanation of using quotes, it makes perfect sense, but the script will only accept code that is between the single quotes, anything else (no quotes or double quotes) will cause it to malfunction.

Thanks for your suggestions so far though guys. It's appreciated.
Falconer is offline
Reply With Quote
View Public Profile
 
Reply     « Reply to Help with small piece of code..
 

Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are Off
Pingbacks are Off
Refbacks are Off





   
RSS Feed  Feeds: RSS   JS   XML
RSS Feed  Feeds for this forum: RSS   JS   XML



Page generated in 0.33742 seconds with 12 queries