Jump to content

I have a parse error in this query help..


co.ador

Recommended Posts

$query1="INSERT INTO `rating` (`item_name`, `rating`, `ip_address`, `date_rated`) VALUES ('{$varItem}', {$varRating}, '{$ipAddress}', NOW())", "InsertRating";

 

Parse error produced by the query above

br />

<b>Parse error</b>:  parse error in <b>C:\wamp\www\stores\classes\rating.class.php</b> on line <b>92</b><br />

 

Help please.

 

 

Link to comment
https://forums.phpfreaks.com/topic/186008-i-have-a-parse-error-in-this-query-help/
Share on other sites

  • Replies 51
  • Created
  • Last Reply

it didn't quite worked

 

I had done this with the query you have given me.

 

<?php 
$query1="INSERT INTO rating (item_name, rating, ip_address, date_rated) VALUES ('$varItem', $varRating, '$ipAddress'," .now() .")InsertRating"; 
		echo $query1;
			Database::ExecuteQuery($query1)
            Database::FetchResults("InsertRating");
            Database::FreeResults("InsertRating");
            Database::RemoveSavedResults("InsertRating");
?>

 

you mean to take out the single quotes around $ipAddress since it is a numeric value?

You don't need to have any quotes around numeric value in SQL query. Are you sure your IP field is numeric? - I don't see why would be numeric except if you making some conversion but stil... :confused: Maybe that is what cause error. I would set IP address field to string and it would be like I wrote in previous comment.

anthylon: now() is not a PHP function..

It is a MySQL function and the problem he was getting was a PHP error NOT mysql..

Im not sure what the InsertaRating thing at the end of the string is but..

$query1="INSERT INTO `rating` (`item_name`, `rating`, `ip_address`, `date_rated`) VALUES ('{$varItem}', {$varRating}, '{$ipAddress}', NOW())";

should work..

it works ok when set up in this way

 

<?php Database::ExecuteQuery("INSERT INTO `rating` (`item_name`, `rating`, `ip_address`, `date_rated`) VALUES ('{$varItem}', {$varRating}, '{$ipAddress}', NOW())", "InsertRating");?>

 

 

but when I take out get the query inside of a variable and then insert that variable as an argument for the method ExecuteQuery then it will produce a parse error.

 

<?php 
$query1="INSERT INTO `rating` (`item_name`, `rating`, `ip_address`, `date_rated`) VALUES ('{$varItem}', {$varRating}, '{$ipAddress}', NOW())", "InsertRating";
		Database::ExecuteQuery($query1);
?>

 

What's the differnece in between this set ups?  and why the second produce a parse error in the first line?

I have fixed it to this

 

 

<?php 
$query1="INSERT INTO `rating` (`item_name`, `rating`, `ip_address`, `date_rated`) VALUES ('{$varItem}', {$varRating}, '{$ipAddress}', NOW()), 'InsertRating'";
		echo $query1; 
		Database::ExecuteQuery($query1);
?>

 

and now it works it just echoing the query which doesn't display in the screen.

I got to echo the query. I went to the ExcuteQuery method at the database class and echo it like that.

 

<?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;
      }
?>

 

 

and it display this

 

picture

Rating:

Giovannis\'s RestaurantsSELECT 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

 

But the INSERT query won't display after echoing it I guess because it's function and activation would be only when rating an item right? in this case would be SELECTING it.  There are two SELECT queries in the script.

 

it still won't rate an item with apostrophes even though it is clearly escaped as you can see at the display..

Im not 100% sure what the 'InsertRating' thing is for? Can you explain it?

$query1="INSERT INTO `rating` (`item_name`, `rating`, `ip_address`, `date_rated`) VALUES ('{$varItem}', {$varRating}, '{$ipAddress}', NOW())";

 

Should work fine..

I don't understand why it is not working....

 

crazy.

 

The InsertRating is an string that detects wheather something has been rated or is rating.

 

that's what I think is for..

 

For instance

 

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

 

The InsertRating string is used as an argument for FetchResults method. That's what the FetchResults do with the InserRating string assigned to the $name variable at the FetchResults as below.ode

 

<?php public static function FetchResults($name)
      {
        $results = array();
        if (self::$connection)
        {
          if (strlen(trim($name)) != 0 && (array_key_exists($name, self::$savedQueries) || array_key_exists($name, self::$savedResults)))
          {
            if (array_key_exists($name, self::$savedQueries))
            {
              switch (self::$type)
              {
                case "mysql":
                  $row = 0;
                  while ($currentResult = @mysql_fetch_assoc(self::$savedQueries[$name]))
                  {
                    $col = 0;
                    foreach ($currentResult as $key => $value)
                    {
                      $results[$row][$col] = $value;
                      $results[$row][$key] = $value;
                      $col++;
                    }
                    
                    $row++;
                  }
                  break;
                case "mysqli":
                  $row = 0;
                  while ($currentResult = @mysqli_fetch_assoc(self::$savedQueries[$name]))
                  {
                    $col = 0;
                    foreach ($currentResult as $key => $value)
                    {
                      $results[$row][$col] = $value;
                      $results[$row][$key] = $value;
                      $col++;
                    }
                    
                    $row++;
                  }
                  break;
              }
            
              self::$savedResults[$name] = $results;
            }
            else
            {
              $results = self::$savedResults[$name];
            }
          }
          else
          {
            if (strlen(trim($name)) == 0)
            {
              Error::LogError("Fetch Results Name Missing", "The name parameter was empty, the name is required so it knows which results to return.");
            }
            else
            {
              Error::LogError("Fetch Results Name ('{$name}') Not Found", "The name provided did not have any query results associated with it.");
            }
          }
        }
        
        return $results;
      }
      ?>

 

 

Ok I understand now..

in that case:

<?php 
   $query1="INSERT INTO `rating` (`item_name`, `rating`, `ip_address`, `date_rated`) VALUES ('{$varItem}', {$varRating}, '{$ipAddress}', NOW())";
         echo $query1; 
         Database::ExecuteQuery($query1,'InsertRating');
?>

This is because the InsertRating this is NOT apart of the query itself.. its a parameter for the Database:ExecuteQuery function..

 

Let us know how this goes for you..

 

It does work now putting the parameter InsertRating as an argument for ExecuteQuery..

 

<?php 
   $query1="INSERT INTO `rating` (`item_name`, `rating`, `ip_address`, `date_rated`) VALUES ('{$varItem}', {$varRating}, '{$ipAddress}', NOW())";
         echo $query1; 
         Database::ExecuteQuery($query1,'InsertRating');
?>

 

It won't echo $query1 unless I go inside hte ExecuteQuery method and echo $sql variable which gets the value of $query1?.

 

Then it will echo The two SELECT query statements but not the INSERT query statement found at the rating.class.php  file below. I have to say INSERT should echo since it is execute as an argument of ExecuteQuery method... isn't it?

 

 

---rating.class.php---

 

<?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);
		   var_dump($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)
        {
          // 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;
      }
    ## 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'];
        
        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
  }
?> 
?>

 

as I said it will only display or echo the two SELECT statements queries as shown below:

 

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

 

and it won't still rate items with apostrophe even though they are escaped as in the case of 'Giovannis\'s Restaurants already escaped. it also said  AlreadyRated but it is not showing up in the databse...

<?php 

if (Rating::CheckRatingsByIp($varItem) == 0)
?>

 

The above is the first condition. if id is == 0 then it will execute.

 

<?php 
{
            $ipAddress = $_SERVER['REMOTE_ADDR'];
            
            $query1="INSERT INTO `rating` (`item_name`, `rating`, `ip_address`, `date_rated`) VALUES ('{$varItem}', {$varRating}, '{$ipAddress}', NOW())";
         Database::ExecuteQuery($query1,'InsertRating');
            Database::FetchResults("InsertRating");
            Database::FreeResults("InsertRating");
            Database::RemoveSavedResults("InsertRating");
            
            // Information for the Output
            $averageStars  = Rating::CalculateAverageRating($varItem);
            $newClassNames = "rated " . Rating::ShowStars($averageStars);
          }
?>

 

Which it won't echo if ip==!0  right?

 

that's not true right no i have empty the rating table, in other words i have erase all the data inside the table chich means ipaddress==0 now and but it still won't display or echo or call the INSERT rating.

It wont execute the query if there is a record in the database matching your ip address and that item..

Have you checked your records in the database to see.. Im nearly 100% certain that it will be in there since the INSERT query isnt being executed..

Rating is the table...

 

I have double checked it and the table name is indeed 'rating' and it also 100% it doesn't have a record inside that field. By the way it was displaying InsertRating, AlreadyRated and AverageRating parameters because i was echoing "echo $name" at the ExecuteQuery method which is the variable that gets the value of the parameter InsertRating or Alreadyrated and AverageRating strings at the INSERT and SELECT statements in the rating.class.php file.

 

 

InsertRating parameter at the INSERT

 

$query1="INSERT INTO `rating` (`item_name`, `rating`, `ip_address`, `date_rated`) VALUES ('{$varItem}', {$varRating}, '{$ipAddress}', NOW())";
         Database::ExecuteQuery($query1,'InsertRating');

 

at the SELECT  statement #1 called AverageRating

 

  // Query Average Rating for a specific Item
        Database::ExecuteQuery("SELECT AVG(`rating`) AS `averageRating` FROM `rating` WHERE `item_name`='{$varItem}'", "AverageRating")

 

and at the SELECT statement #2 called AlreadyRated

 

Database::ExecuteQuery("SELECT COUNT(*) AS `totalRatings` FROM `rating` WHERE `item_name`='{$varItem}' AND `ip_address`='{$ipAddress}'", "AlreadyRated");

 

ExecuteQuery method where I echo the variables $sql and $name equivalent to the queries above and the passed parameters.

 

<?php
public static function ExecuteQuery($sql,$name)
     
  {
        if (self::$connection)
        {echo $sql;
	echo $name;
          if (strlen(trim($name)) != 0)
          {
            switch (self::$type)
            {...
?>

my bad I got confused it won't echo anything inside the () parenthesis

 

  Database::ExecuteQuery("INSERT INTO `rating` (`item_name`, `rating`, `ip_address`, `date_rated`) VALUES ('{$varItem}', {$varRating}, '{$ipAddress}', NOW())", "InsertRating");

 

anything not even the parameter InsertRating.

 

It is echoing the SELECT queries and its parameters as well but not the INSERT query and its parameter, in other words nothing inside the double quotes.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.