Jump to content

Need addslashes() explanation


co.ador

Recommended Posts

I am using a rating system that won't rate items names which containt symbols or single quotes inside the name as :

 

Giovannis's shoe store

 

if you notice Giovannis's has an single quote after the s, That fat right there won't let the rating system to enter the name inside the database through the INSERT Quere in the code.

 

<?php 
<?php
class Rating
  {
    ## PRIVATE VARIABLES
    ## END PRIVATE VARIABLES

    ## PUBLIC METHODS
      // Output the Rating information
      // Returns a string of HTML
      public static function OutputRating ($varItem)
      {
        // Verify $varItem was provided
        if ($varItem != null && strlen(trim($varItem)) != 0)
        {
          // Check if Magic QUotes is ON
        
          if (!get_magic_quotes_gpc())
          {
            $varItem = addslashes($varItem);
          }
          // Information for the Output
          $averageStars = Rating::CalculateAverageRating($varItem);
          
          // Check to see that the user has not already rated this item
          if (Rating::CheckRatingsByIp($varItem) == 0)
          {
            $classes      = "rating " . Rating::ShowStars($averageStars);
            
?>

 

The code above is the first part of the main rating page. Notice the function addslashes() inside the script. Is that the function that won't allow the data go inside the database?

 

why could that function be stoping the rating to go inside the database?

 

Waht's really going inside thiscode above? can anybody explain ?

 

 

thank you.

 

Link to comment
Share on other sites

Several threads ago, it was mentioned to you that you need to use mysql_real_escape_string on the values being put into a query in order to fix this problem. And in fact when you did use it in that thread, your query worked and inserted the data (you said.)

 

If you had read the information at the link that was posted in that thread to the mysql_real_escape_string function in the documentation, you would have learned that it takes into account the current character encoding when it escapes data.

 

addslashes and magic_quotes_gpc do NOT escape all the characters in all the character sets that can break a query. In fact, if magic_guotes_gpc is on, your code is not even executing the addslashes() function.

 

If magic_quotes_gpc is ON, you should in fact use stripslashes on the data first, then unconditionally use mysql_real_escape_string -

 

          if (get_magic_quotes_gpc())
          {
            $varItem = stripslashes($varItem);
          }
          $varItem = mysql_real_escape_string($varItem);

Link to comment
Share on other sites

I don't understand why if the three switches in php.in for magic quotes are off by default and still the data is not being escape.

 

switch #1

; - magic_quotes_gpc = off        [Performance]

;    Input data is no longer escaped with slashes so that it can be sent into

;    SQL databases without further manipulation.  Instead, you should use the

;    database vendor specific escape string function on each input element you

;    wish to send to a database

 

 

switch #2

; Magic quotes for incoming GET/POST/Cookie data.

magic_quotes_gpc = off

 

switch #3

 

; Magic quotes for runtime-generated data, e.g. data from SQL, from exec(), etc.

magic_quotes_runtime = Off

 

the switches are off by default in my php.ini, You have said that if the switches are off I could use addslashes, well

I have used it like this

 

<?php 

          if (get_magic_quotes_gpc())          {            
	  $varItem = addslashes($varItem);        
	    }         
	   $varItem = mysql_real_escape_string($varItem);
	   echo $varItem;
?>

 

And the echo for that result is

 

picture

Rating:

Giovannis\'s stores

 

    * 1

    * 2

    * 3

    * 4

    * 5

 

Description:

 

And it seem to be escaping it,

 

I have also used the stripslashes as well and the result of the echo is the same as above.

 

<?php 
   if (get_magic_quotes_gpc())          {            
	  $varItem = stripslashes($varItem);        
	    }         
	   $varItem = mysql_real_escape_string($varItem);
	   echo $varItem;
?>

 

For stripslashes and addslashes the rating information is not going in for those items thata has the single quotes in the string. So if I have used stripslashes and addslashes, having the magic_quotes_gcp switches off in the php.ini, Means that the problem for that rating malfunctioning is something else than escaping matters?

Link to comment
Share on other sites

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

 

if magic_quotes_gpc is off, the condition above will return false.  any stripslashes or addslashes you do within that condition have absolutely no affect on the output.

 

<?php
if (get_magic_quotes_gpc()) {            
     $varItem = stripslashes($varItem);        
}
$varItem = mysql_real_escape_string($varItem);
echo $varItem;
?>

 

your full code here shows that you are running mysql_real_escape_string() against $varItem, which is how that variable is being escaped no matter what.  your logic with the get_magic_quotes_gpc() is incorrect.

Link to comment
Share on other sites

When you use mysql_real_escape_string() the slashes disappear once the data is safely inside the database. Thats the difference between mysql_real_escape_string() and addslashes() . With addslashes() , the slashes will still be on the string when its in the DB.

 

No they won't

Link to comment
Share on other sites

that's the case in here!

 

<?php 
   if (!get_magic_quotes_gpc())          {            
	  $varItems = stripslashes($varItem);        
	    }        
	   $varItem = mysql_real_escape_string($varItems);
	   echo $varItem;
?>

 

 

First it checks if there is not magic quotes which in my php.ini is off.  So that has logic tilll that point. Then it will stripslashes $varItem as below,

 

Giovannis\'s store

 

That's stripslashing or escaping right? just want to make 100% sure.

 

 

Then it will mysql_real_escape_string the data to make it safe into the database like

 

<?php 

$varItem = mysql_real_escape_string($varItems);

?>

 

But they won't get in the database I don't get it, Sorry.

 

 

 

 

 

Link to comment
Share on other sites

that's the case in here!

 

<?php 
   if (!get_magic_quotes_gpc())          {            
	  $varItems = stripslashes($varItem);        
	    }        
	   $varItem = mysql_real_escape_string($varItems);
	   echo $varItem;
?>

 

 

First it checks if there is not magic quotes which in my php.ini is off.  So that has logic tilll that point. Then it will stripslashes $varItem as below,

 

Giovannis\'s store

 

That's stripslashing or escaping right? just want to make 100% sure.

 

 

Then it will mysql_real_escape_string the data to make it safe into the database like

 

<?php 

$varItem = mysql_real_escape_string($varItems);

?>

 

But they won't get in the database I don't get it, Sorry.

 

 

 

 

 

 

well, you just changed your logic on the fly .. you never has a ! in your other code.

 

this: Giovannis's store to: Giovannis\'s store would be adding a slash.  pay more attention to the function names.

 

and you only need to strip the slashes if magic quotes are on.  otherwise, they is nothing to strip.  and you would add slashes if magic quotes are off, but there's no point since you're going to just use mysql_real_escape_string anyways.

 

k, to keep this from getting way out of wack, you already know that magic quotes are off, correct?

 

simply use mysql_real_escape_string on your query data, and all will be well.  forget about stripslashes and addslashes.  magic quotes are deprecated as of v5.3, and fully removed from v6, so relying on them is just setting yourself for rework.

Link to comment
Share on other sites

I have taken off the magic_quotes_gpc(); and the if condition and leave it with the mysql_real_escape_string function and it will do the same effect as addslashes or stripslashes.

I have leave it as:

 

<?php$varItem = mysql_real_escape_string($varItem);
	   echo $varItem;?>

 

The echo results for $varItem is

 

Giovannis\'s store
it is escaping with mysql_real_escape_string but still the rating results won't go in the database.....

 

UCH.......... it is something else than escaping the string. Right?

Link to comment
Share on other sites

When you use mysql_real_escape_string() the slashes disappear once the data is safely inside the database. Thats the difference between mysql_real_escape_string() and addslashes() . With addslashes() , the slashes will still be on the string when its in the DB.

 

No they won't

 

Your right they both function the same, the slash disappears once its put into the database. Rather to correct myself, if you have magic_quotes_gpc  on, and put addslashes(), the it will be double-slashed, and the slashes will appear in the database.

 

 

@OP,

 

This is the proper why to detect magic quote

 

<?php
          if (function_exists('get_magic_quotes_gpc'))
          {
               $varItem = stripslashes($varItem);
          }

             $varItem  = mysql_real_escape_string($varItem);

 

 

Also put  use var_dump($varItem); to see that it the expected input,  echo doesn't show the whole story,  and also put

or die(mysql_error());  on your query to see if there is an error. Remember garbage in garbage out. Check your inputs.

 

Link to comment
Share on other sites

This kind of moves away from your original idea, but when I have data that isn't going to be evaluated, but simply displayed, I like to use htmlspecialchars($blah, ENT_QUOTES) and convert the quotes to their html equivalent. Just an idea. Makes my life a lot easier. Some forms I may even use:

 

foreach ($_POST as $key=>$value) {

$_POST[$key]=htmlspecialchars($value, ENT_QUOTES);

}

Link to comment
Share on other sites

The var dump for the code below is.

 

<?php if (function_exists('get_magic_quotes_gpc')) {   
	      $varItem = stripslashes($varItem);         
		   }
		   $varItem  = mysql_real_escape_string($varItem);
		   var_dump($varItem);?>

 

<?php 
string(24) "Giovannis\'s store"

    * 1
    * 2
    * 3
    * 4
    * 5

Description:
?>

Link to comment
Share on other sites

Your saying you can't get the data to insert so do the usual,

 

1. Put  or die(mysql_error()) on your query, examine if there is an sql error.

2. check that your table names are correct.  Mysql sometimes just returns false and not an error.

3. Check that your WHERE statment is correct.

4. Check the table row is varchar with at least a length of least 20, and utf8_general_ci  and is not Int

5. Is $varItem  actually an Array?, if it is you have to do this, $varitem['index']

5. Check that your mysql is plugged in. :P

 

Giovannis\'s store is perfectly fine to put into database, there is nothing wrong with it, the problem likely is in your query.

Link to comment
Share on other sites

bear with me because this rating system uses an OOP it was not code by me. It also has an database error and the OOP query uses and Error instance in the query to call the error class.

 

the query to Insert is

 

<?php 
    // 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.");
        }
?>

 

The else condition will display the error is there is anything wrong with the query... Right now is not displaying any error.

 

I will show you that's the error class is like to see if it is using the die function...

 

<?php 
class Error
  {
    ## CONSTANT VARIABLES
    ## END CONSTANT VARIABLES
    
    ## PUBLIC VARIABLES
    ## END PUBLIC VARIABLES
    
    ## PRIVATE VARIABLES
      private static $title;
      private static $type;
      private static $description;
      private static $datetime;
      
      private static $numErrors;
      private static $numWarnings;
    ## END PRIVATE VARIABLES
    
    ## CONSTRUCTOR
    ## END CONSTRUCTOR
    
    ## DECONSTRUCTOR
    ## END DECONSTRUCTOR
    
    ## PUBLIC METHODS
      // Initialize the Variables
      // Does not return anything, but acts like a constructor for Static classes
      public static function Initialize()
      {
        self::$title       = array();
        self::$type        = array();
        self::$description = array();
        self::$datetime    = array();
        self::$numErrors   = 0;
        self::$numWarnings = 0;
      }
      
      // DeInitialize the Variables
      // Does not return anything, but acts like a destructor for Static classes
      public static function DeInitialize()
      {
        self::$title       = null;
        self::$type        = null;
        self::$description = null;
        self::$datetime    = null;
        self::$numErrors   = null;
        self::$numWarnings = null;
      }
      
      // Log Error Method (receives Name and Description)
      // Returns true or false depending on if the logging of the error was successful
      public static function LogError($varTitle, $varDescription)
      {
        // Check Parameters
        if (strlen(trim($varTitle)) != 0 && strlen(trim($varDescription)) != 0)
        {
          array_push(self::$title, $varTitle);
          array_push(self::$type, "ERROR");
          array_push(self::$description, $varDescription);
          array_push(self::$datetime, date("m/d/Y H:i:s"));
          self::$numErrors++;
          
          return true;
        }
        
        return false;
      }
    
      // Show Error Messages
      // Returns the Error Message Output (in HTML format)
      public static function ShowErrorMessages()
      {
        $output = "";
        
        // Check to see if 1 error occurred or more than one.
        if (self::$numErrors > 0)
        {
          if (self::$numErrors > 1)
          {
            $error = "ERRORS";
          }
          else
          {
            $error = "ERROR";
          }
          
          // Loop through Error Messages
          for ($i = 0; $i < sizeof(self::$title); $i++)
          {
            if (self::$type[$i] == "ERROR")
            {
              // Output each individual Error
              $output .= "    <div class=\"divErrorTitle\">\r\n" . 
                         "      " . self::$title[$i] . "\r\n" . 
                         "      <span class=\"spnErrorDateTime\">at " . self::$datetime[$i] . "</span>\r\n" .
                         "    </div>\r\n" .
                         "    <div class=\"divErrorDesc\">" . self::$description[$i] . "<br /><br /></div>\r\n";
            }
          }
          
          // Write Error Template Output
          $output  = "<div class=\"divErrorBox\">\r\n" .
                     "  <div class=\"divErrorBoxTitle\"><img src=\"icons/24-em-cross.png\" align=\"left\" /> {$error}:</div>\r\n" .
                     "  <div class=\"divErrors\">\r\n" . $output . "\r\n  </div>\r\n" .
                     "</div>\r\n";
        }
        
        // Return the Error Message Output
        return $output;
      }
      
      // Retrieve Last Error
      // Returns the title and description of the last error in an array
      public static function RetrieveLastError()
      {
        $output = array();
        
        // Check to see if 1 error occurred or more than one.
        if (self::$numErrors > 0)
        {
          for ($i = sizeof(self::$title) - 1; $i >= 0; $i++)
          {
            if (self::$type[$i] == "ERROR")
            {
              array_push($output, self::$title[$i]);
              array_push($output, self::$description[$i]);
              break;
            }
          }
        }
        
        return $output;
      }
      
      // Clear Errors
      // Returns nothing
      public static function ClearErrors()
      {
        self::$numErrors   = 0;
        
        for ($i = 0; $i < sizeof(self::$type); $i++)
        {
          if (self::$type[$i] == "ERROR")
          {
            self::$title[$i]       = null;
            self::$type[$i]        = null;
            self::$description[$i] = null;
            self::$datetime[$i]    = null;
          }
        }
      }
      
      // Has Errors
      // Returns true or false on whether errors exist
      public static function HasErrors()
      {
        if (self::$numErrors > 0)
        {
          return true;
        }
        
        return false;
      }
      
      // Log Warning Method (receives Name and Description)
      // Returns true or false depending on if logging the warning was successful
      public static function LogWarning($varTitle, $varDescription)
      {
        // Check Parameters
        if (strlen(trim($varTitle)) != 0 && strlen(trim($varDescription)) != 0)
        {
          array_push(self::$title, $varTitle);
          array_push(self::$type, "WARNING");
          array_push(self::$description, $varDescription);
          array_push(self::$datetime, date("m/d/Y H:i:s"));
          self::$numWarnings++;
          
          return true;
        }
        
        return false;
      }
    
      // Show Warning Messages
      // Returns the Warning Message Output (in HTML format)
      public static function ShowWarningMessages()
      {
        $output = "";
          
        // Check to see if 1 warning occurred or more than one.
        if (self::$numWarnings > 0)
        {
          if (self::$numWarnings > 1)
          {
            $warning = "WARNINGS";
          }
          else
          {
            $warning = "WARNING";
          }
          
          // Loop through Warning Messages
          for ($i = 0; $i < sizeof(self::$title); $i++)
          {
            if (self::$type[$i] == "WARNING")
            {
              // Output each individual Warning
              $output .= "    <div class=\"divWarningTitle\">\r\n" . 
                         "      " . self::$title[$i] . "\r\n" . 
                         "      <span class=\"spnWarningDateTime\">at " . self::$datetime[$i] . "</span>\r\n" .
                         "    </div>\r\n" .
                         "    <div class=\"divWarningDesc\">" . self::$description[$i] . "<br /><br /></div>\r\n";
            }
          }
          
          // Write Warning Template Output
          $output  = "<div id=\"divWarningBox\">\r\n" .
                     "  <div id=\"divWarningBoxTitle\"><img src=\"designs/icons/24-message-warn.png\" align=\"left\" /> {$warning}:</div>\r\n" .
                     "  <div id=\"divWarnings\">\r\n" . $output . "\r\n  </div>\r\n" .
                     "</div>\r\n";
        }
        
        // Return the Warning Message Output
        return $output;
      }
      
      // Has Warnings
      // Returns true or false on whether there are any Warnings
      public static function HasWarnings()
      {
        if (self::$numWarnings > 0)
        {
          return true;
        }
        
        return false;
      }
    ## END PUBLIC METHODS
          
    ## PRIVATE METHODS
    ## END PRIVATE METHODS
    
    ## PROTECTED METHODS
    ## END PROTECTED METHODS
  }
?>

That's the whole error class where do I put the die function  :'(  Well It should be inside the first method call LogError since that's the want being instanciated in the else statment.
?>

 

 

Link to comment
Share on other sites

Your query looks correct.  I was looking over the first code and noticed

 

$averageStars  = Rating::CalculateAverageRating($varItem);

 

The problem might be the Rating method. Maby its not expecting a  Single Quote ?

You never know with OOP there could be some thing that stop the query from excuting inside the  Rating::CalculateAverageRating method when it finds what it thinks is garbage input (The single quote and slash)

 

Edit:

Also are you sure that $varitem is not an array? Inserting it as $varItem wont work if it is, its will just insert "Array" in the database. You need access its indexes in the query like

 .... VALUES ('{$varItem['name']}', ....

By the looks of the var_dump, I would say maby it is, put print_r($varItem); to see if its an array.

(But then again somewhere else in the code the variable could be reassigned. Lke $varItem = $varItem['name'] )

Link to comment
Share on other sites

Rating method for references

<?php 
<?php
class Rating
  {
    ## PRIVATE VARIABLES
    ## END PRIVATE VARIABLES

    ## PUBLIC METHODS
      // Output the Rating information
      // Returns a string of HTML
      public static function OutputRating ($varItem)
      {
        // Verify $varItem was provided
        if ($varItem != null && strlen(trim($varItem)) != 0)
        {
          // Check if Magic QUotes is ON
        
               
	     if (function_exists('get_magic_quotes_gpc')) {   
	      $varItem = stripslashes($varItem);         
		   }
		   $varItem  = mysql_real_escape_string($varItem);
		  
          // Information for the Output
          $averageStars = Rating::CalculateAverageRating($varItem);
          
          // Check to see that the user has not already rated this item
          if (Rating::CheckRatingsByIp($varItem) == 0)
          {
            $classes      = "rating " . Rating::ShowStars($averageStars);
            
            // Write Output HTML for the Rating Data
            $output  = "\r\n";
            $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";
            $output .= "  <li class=\"two\"><a   href=\"javascript:RateItem('{$varItem}', 2);\" title=\"2 Stars\">2</a></li>\r\n";
            $output .= "  <li class=\"three\"><a href=\"javascript:RateItem('{$varItem}', 3);\" title=\"3 Stars\">3</a></li>\r\n";
            $output .= "  <li class=\"four\"><a  href=\"javascript:RateItem('{$varItem}', 4);\" title=\"4 Stars\">4</a></li>\r\n";
            $output .= "  <li class=\"five\"><a  href=\"javascript:RateItem('{$varItem}', 5);\" title=\"5 Stars\">5</a></li>\r\n";
		$output .= "</ul>\r\n";
          }
          else
          {
            $classes      = "rated " . Rating::ShowStars($averageStars);

            
            // Write Output HTML for the Rating Data
            $output  = "\r\n";
            $output .= "<ul class=\"{$classes}\" id=\"{$varItem}\">\r\n";
            $output .= "  <li class=\"one\">1</li>\r\n";
            $output .= "  <li class=\"two\">2</li>\r\n";
            $output .= "  <li class=\"three\">3</li>\r\n";
            $output .= "  <li class=\"four\">4</li>\r\n";
            $output .= "  <li class=\"five\">5</li>\r\n";
					            		
            $output .= "</ul>\r\n";
          }
        }
        else
        {
          $output = "";
          // This is a major issue. NO information can be retrieve if an item name is not passed.
          Error::LogError("Variable Missing", "You must provide the item name for this function to find the average.");
        }
        
        return $output;
      }

      // Rate an Item
      // Returns the name/value pair of new class names and the item name
      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)
        {
                 
	   $varItem = mysql_real_escape_string($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;
      }
    ## END PUBLIC METHODS
    
    ## PRIVATE METHODS
      // Calculate Average Rating
      // Returns the number of stars to show
      private static function CalculateAverageRating($varItem)
      {
        $averageStars = 0;
        
        // Query Average Rating for a specific Item


        
	Database::ExecuteQuery("SELECT AVG(`rating`) AS `averageRating` FROM `rating` WHERE `item_name`='{$varItem}'", "AverageRating");
        $results = Database::FetchResults("AverageRating");
        Database::FreeResults("AverageRating");
        Database::RemoveSavedResults("AverageRating");
        
        // Round the Average into a Whole Number
        if (sizeof($results) == 1)
        {
          if ($results[0]['averageRating'] != null)
          {
            $averageStars = round($results[0]["averageRating"], 0);
          }
        }
        else
        {
          // This is simply a warning, as it isn't vital if no results were found, as the item may be new.
          Error::LogWarning("Rating Data Missing", "No entries were found for '{$varName}', this might be the first entry.");
        }
        
        return $averageStars;
      }
      
      // Show Stars
      // Returns the class information for the number of stars to show
    private static function ShowStars($varStars)
{
    $aStars = array(
        1    =>    'onestar',
        2    =>    'twostar',
        3    =>    'threestar',
        4    =>    'fourstar',
        5    =>    'fivestar'
    );
    return (true === array_key_exists((integer)$varStars, $aStars)) ? $aStars[(integer)$varStars] : 'nostar' ;
} 

  
      // 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'];
        $varItem = mysql_real_escape_string($varItem);
        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
  }
?> 
?>

 

Let me check on what you said.

 

Yes the $varItem is an array...

 

 

Link to comment
Share on other sites

don't see any reassinment to $varItem that could be changing the value of varItem at least with my limit knowledge in rating class..

 

 

Have to clear up that the data is an array when it comes to display from page1.php to page.2 but in page2.php every item is rated by separate meaning that the varItem variable is not an array by the time it gets to the rating class... right?

 

Ps: i have to say that others items are going in the database when they are rated the only problem is when an item string has an single quote in such as giovannis's store.

 

 

Link to comment
Share on other sites

Put  print_r($varItem) right near the heart of the problem to see if it an array, if it you see something like

 

Array( [1]=> "",

          [2]=> "";

 

etc. , Then yes you have an array probably  being inserted into the query, which wont work.

 

<?php
// Some pre tags so it displays as plain text in the browser.
echo "<pre>";
print_r($varItem);
echo "</pre>";
// exit , and see the output of print_r
exit;
Database::ExecuteQuery("INSERT INTO `rating` (`item_name`, `rating`, `ip_address`, `date_rated`) VALUES ('{$varItem}', {$varRating}, '{$ipAddress}', NOW())", "InsertRating");

Link to comment
Share on other sites

If it is put in before the INSERT query then the print_r function won't display anything,

 

So I have put the print_r function on top of the rating class as:

 

<?php 

   if ($varItem != null && strlen(trim($varItem)) != 0)
        {
          // Check if Magic QUotes is ON
        
               
	     if (function_exists('get_magic_quotes_gpc')) {   
	      $varItem = stripslashes($varItem);         
		   }
		   $varItem  = mysql_real_escape_string($varItem);
		   
	echo "<pre>";
		print_r($varItem);
		echo "</pre>";// exit , and see the output of print_r
		exit;	  
          // Information for the Output
          $averageStars = Rating::CalculateAverageRating($varItem);
          
?>

 

Results are that it exit...

 

And won't go through, it won't even display something like

 

Array( [1]=> "",

          [2]=> "";

 

Link to comment
Share on other sites

The if(function_exists('get_magic_quotes_gpc')) {  code that keldorn posted is nonsense. The get_magic_quotes_gpc function exists in php4, php5, and php6, so that code will always perform stripslashes() even if the magic_quotes_gpc setting is OFF. This will result in any actual \ in the data being removed. stripslashes() should only be executed when magic_quotes_gpc in ON, in which case calling the get_magic_quotes_gpc() function will return a TRUE value.

Link to comment
Share on other sites

The if(function_exists('get_magic_quotes_gpc')) {  code that keldorn posted is nonsense. The get_magic_quotes_gpc function exists in php4, php5, and php6, so that code will always perform stripslashes() even if the magic_quotes_gpc setting is OFF. This will result in any actual \ in the data being removed. stripslashes() should only be executed when magic_quotes_gpc in ON, in which case calling the get_magic_quotes_gpc() function will return a TRUE value.

Are you sure , I learned that from the PHP IPN example from Paypal. If you'll take a look,

https://cms.paypal.com/us/cgi-bin/?&cmd=_render-content&content_ID=developer/e_howto_admin_IPNImplementation

Why would paypal show a incorrect way to  detect magic quotes. Would of the code example been reviewed before being put on the site?

Link to comment
Share on other sites

This is the proper why to detect magic quote

 

<?php
          if (function_exists('get_magic_quotes_gpc'))
          {
               $varItem = stripslashes($varItem);
          }

             $varItem  = mysql_real_escape_string($varItem);

 

No. You don't want to check to see if the get_magic_quotes_gpc function exists, you want to see if it returns true or false.

 

if (get_magic_quotes_gpc()) {
  $varItem = stripslashes($varItem);
}
$varItem  = mysql_real_escape_string($varItem);

 

No wonder the OP is confused.

Link to comment
Share on other sites

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.