Jump to content

Recommended Posts

I am debuggin my code and I have realized that $varItem is not passing through this method called RateItem can any body help?

 

<?php 
public static function RateItem($varItem, $varRating, $varClasses)
  {
    
    $newClassNames = $varClasses;
        
        // Verify $varName was provided
        
	 if ($varItem != null && strlen(trim($varItem)) != 0
          && $varRating != null && strlen(trim($varRating)) != 0 && is_numeric($varRating) 
          && $varClasses != null && strlen(trim($varClasses)) != 0)
        {
          // Check if Magic Quotes is ON
        
	  if (!get_magic_quotes_gpc())
          {
            $varItem = addslashes($varItem);
          }
          
          // Check to see that the user has not already rated this item
	  

          if (Rating::CheckRatingsByIp($varItem) == 0)
          {
            $ipAddress = $_SERVER['REMOTE_ADDR'];
            
            Database::ExecuteQuery("INSERT INTO `rating` (`item_name`, `rating`, `ip_address`, `date_rated`) VALUES ('{$varItem}', {$varRating}, '{$ipAddress}', NOW())", "InsertRating");
            Database::FetchResults("InsertRating");
            Database::FreeResults("InsertRating");
            Database::RemoveSavedResults("InsertRating");
            
            // Information for the Output
            $averageStars  = Rating::CalculateAverageRating($varItem);

            $newClassNames = "rated " . Rating::ShowStars($averageStars);
          }
        }
        else
        {

          // This is a major issue. NOT enough information was sent to log the item
          Error::LogError("Variable(s) Missing", "You must provide all of the information to log the rating of this item.");
        }
        
        // Build Name/Value Pair to return
        $nameValue = "classes={$newClassNames}&item={$varItem}";
        return $nameValue;
      }
?>

 

 

The value of the $varItem variable found as the argument for the RateItem function is not passing Inside to the function.

 

I use this little test script to evaluate weather or not is passing.

<?php
if($varItem){
      echo "yea";
      }
      else {echo "colo";}?>

 

The class where this method is has the $varItem variable and it's passing to all the other method except to this one.

 

Can anybody help here?

 

 

it is called in ajax.rate.item.php as:

 

<?php 
echo Rating::RateItem($_POST['item'], $_POST['rating'], $_POST['classes']);
?>

 

Aww, I swear to GOD i was thinking this method was not called anywhere but yes, this function is required_once in ajax.rate.item.php as follows:

 

ajax.rate.item.php

<?php
  require_once("classes/include.all.php");
  
  // Check that the data was sent
  if (sizeof($_POST) == 0
    || $_POST['item'] == null
    || strlen(trim($_POST['item'])) == 0
    || $_POST['rating'] == null
    || strlen(trim($_POST['rating'])) == 0
    || $_POST['classes'] == null
    || strlen(trim($_POST['classes'])) == 0)

  {
    die("You shouldn't be attempting to access this file in this manner.");
  }
  
  echo Rating::RateItem($_POST['item'], $_POST['rating'], $_POST['classes']);
?>

 

 

At the top you will see that  include.all.php is required and inside the include.all.php the rating.class.php file is included, which rating.class.php contains the method RateItem posted in the first post.

 

 

 

yes it is passing as the first argument, and the issue is some how it is not rating string values that has especial characters inside it's string such as apostrophes.

 

Below is what I believe to be sequence the rating script uses to complete the process.

 

I am working in a rating system which use php and javascript to work. right now the java/php script won't INSERT any item that has apostrophes or especial characters in its string.

 

That's the main problem.

 

The INSERT is a php query used as below inside the RateItem php method

<?php
public static function RateItem($varItem, $varRating, $varClasses)
      {
        $newClassNames = $varClasses;
        
        // Verify $varName was provided
        if ($varItem != null && strlen(trim($varItem)) != 0
          && $varRating != null && strlen(trim($varRating)) != 0 && is_numeric($varRating) 
          && $varClasses != null && strlen(trim($varClasses)) != 0)
        {
          // Check if Magic Quotes is ON
          if (!get_magic_quotes_gpc())
          {
            $varItem = addslashes($varItem);
          }
          
          // Check to see that the user has not already rated this item
          if (Rating::CheckRatingsByIp($varItem) == 0)
          {
            $ipAddress = $_SERVER['REMOTE_ADDR'];
            
            Database::ExecuteQuery("INSERT INTO `rating` (`item_name`, `rating`, `ip_address`, `date_rated`) VALUES ('{$varItem}', {$varRating}, '{$ipAddress}', NOW())", "InsertRating");
            Database::FetchResults("InsertRating");
            Database::FreeResults("InsertRating");
            Database::RemoveSavedResults("InsertRating");
            
            // Information for the Output
            $averageStars  = Rating::CalculateAverageRating($varItem);
            $newClassNames = "rated " . Rating::ShowStars($averageStars);
          }
        }
        else
        {
          // This is a major issue. NOT enough information was sent to log the item
          Error::LogError("Variable(s) Missing", "You must provide all of the information to log the rating of this item.");
        }
        
        // Build Name/Value Pair to return
        $nameValue = "classes={$newClassNames}&item={$varItem}";
        return $nameValue;
      }?>

 

If you see the arguments used for the RateItem at the method above are..

$varItem, $varRating, $varClasses 

 

 

in rating.class.php user rates through the html frame that uses the javascript method called RateItem.

 

<?php $output .= "<ul class=\"{$classes}\" id=\"{$varItem}\">\r\n";
            $output .= "  <li class=\"one\"><a   href=\"javascript:RateItem('{$varItem}', 1);\" title=\"1 Star\">1</a></li>\r\n";?>

 

then to RateItem method found in rating.js where Javascript:RateItem method reside.

 

if(window!=top)top.location=location.href;
function RateItem(varItemId, varRating)
{
  var varOrigClassName = document.getElementById(varItemId).className;
  
  // Retrieve Ajax Feeds
  new Ajax.Request('ajax.rate.item.php',
    {
      method: 'post',
      parameters: {item: varItemId, rating: varRating, classes: varOrigClassName},
      onSuccess: ReloadRating,
      onFailure: RatingError
    }
  );
}

function ReadNameValuePairs(nameValuePair)
{
  var trimspaces = /(\s)+/;
  var returnData = new Array();
  var pairs      = nameValuePair.split('&');
  
  for (var i = 0; i < pairs.length; i++)
  {
    var pair = pairs[i].split('=');
    returnData[pair[0].replace(trimspaces, "")] = pair[1];
  }
  
  return returnData;
}

function ReloadRating(requestObj, jsonObj)
{
  var newlines   = /(\r\n|\r|\n)/;
  var returnData = ReadNameValuePairs(requestObj.responseText.replace(newlines, ""));
  
  document.getElementById(returnData['item']).className = returnData['classes'];
  var liObj = document.getElementById(returnData['item']).getElementsByTagName('a');
  
  for (var i = 0; i < liObj.length; i++)
  {
    liObj[i].onclick = function(){};
  }
}

function RatingError()
{
}

 

then it request the ajax.rate.item.php file as in

[HIGHLIGHT=JavaScript]// Retrieve Ajax Feeds

  new Ajax.Request('ajax.rate.item.php',[/HIGHLIGHT]

 

----

ajax.rate.item.php

<?php

<?php header('Content-type: text/html; charset=utf-8');?>
<?php
  require_once("classes/include.all.php");
  
  // Check that the data was sent
  if (sizeof($_POST) == 0
    || $_POST['item'] == null
    || strlen(trim($_POST['item'])) == 0
    || $_POST['rating'] == null
    || strlen(trim($_POST['rating'])) == 0
    || $_POST['classes'] == null
    || strlen(trim($_POST['classes'])) == 0)

  {
    die("You shouldn't be attempting to access this file in this manner.");
  }
  
  echo Rating::RateItem($_POST['item'], $_POST['rating'], $_POST['classes']);
?>

 

then the index item, rating, classes are extracted at ?

  <?php
echo Rating::RateItem($_POST['item'], $_POST['rating'], $_POST['classes']);
?>

 

then what? i was thinking if the index item at rating.js where RateItem method reside, some how should be escaped so that it can be able to rate strings with especial characters?

 

Right now I don't have any knowledge of javascript.

 

 

don't know why this sequence is not able to process values with especial characters inside of its string?

 

it indicates that the string needs to be escaped but that's the first thing it does at rating.class.php

 

<?php if (!get_magic_quotes_gpc())
          {
            $varItem = addslashes($varItem);
          }?>

 

and it displayed to be escaped in the browsers but it won't INSERT the data if it has an special character inside of the string. It will rate any other string except that.

 

That's why I was wondering if This javascript function is able to process escaped values or string values with special characters inside of its string?

You should be using mysql_real_escape_string instead of addslashes providing your using a mysql database.

 

You might also want to place some debugging code within your ExecuteQuery() method to see exactly what the query looks like.

 

I'm not sure where you got the idea for all these static methods but it wreaks of poor design.

The method below is the ExecuteQuery and I have echo the $sql and $name arguments coming from RateItem method but it won't echo the INSERT query only the SELECT query statements.

 

<?php
public static function ExecuteQuery($sql,$name)
     
  {
        if (self::$connection)
        {echo $sql;
	echo $name;
          if (strlen(trim($name)) != 0)
          {
            switch (self::$type)
            {
              case "mysql":
                if (!array_key_exists($name, self::$savedQueries))
                {
                  self::$savedQueries[$name] = @mysql_query($sql, self::$connection) or Error::LogError("Query Failed", mysql_error(self::$connection));
                }
                break;
              case "mysqli":
                if (!array_key_exists($name, self::$savedQueries))
                {
                  self::$savedQueries[$name] = @mysqli_query(self::$connection, $sql) or Error::LogError("Query Failed", mysqli_error(self::$connection));
                }
                break;
            }
            
            return self::$savedQueries[$name];
          }
          else
          {
            Error::LogError("Execute Query Name Missing", "The name parameter was empty, please provide a name for the query.");
          }
        }
        
        return null;
      }
      
?>

 

the echo $sql and $name display the following queries

 

picture

Rating:

SELECT AVG(`rating`) AS `averageRating` FROM `rating` WHERE `item_name`='Giovannis\'s Restaurants'AverageRatingSELECT COUNT(*) AS `totalRatings` FROM `rating` WHERE `item_name`='Giovannis\'s Restaurants' AND `ip_address`='127.0.0.1'AlreadyRated

 

if you can see the string is being escaped but is not INSERTing, as a matter of fact the INSERT query is not even displaying in the browser after echoing the $sql variable argument at ExecuteQuery method.

 

By the way i changed the function addslashes() for mysql_real_escape_string()

it will return 0 or the first index of  $results[0] variables coming from the SELECT statement query.

 

<?php 
     // Check Ratings By IP Address
      // Returns the number of ratings for an item by an ip address
      private static function CheckRatingsByIp($varItem)
      {
        $ipAddress = $_SERVER['REMOTE_ADDR'];
        
        Database::ExecuteQuery("SELECT COUNT(*) AS `totalRatings` FROM `rating` WHERE `item_name`='{$varItem}' AND `ip_address`='{$ipAddress}'", "AlreadyRated");
        $results = Database::FetchResults("AlreadyRated");
        Database::FreeResults("AlreadyRated");
        Database::RemoveSavedResults("AlreadyRated");
        
        // Check to see that the user has not already rated this item
        if ($results != null && $results[0]['totalRatings'] != null)
        {
          return $results[0]['totalRatings'];
        }
        
        return 0;
      }
    ## END PRIVATE METHODS
  }
?>

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.