Syntax error everytime an Apostrophe is submitted in the textbox

Discussion in 'PHP' started by CuBz, Jul 22, 2009.

  1. #1
    Everytime somone enters an appostrophe in the textbox (code shown below), then get syntax error shown below:

    You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'TEXT ENTERED SHOWS HERE', 'main', '0', '0', '1248285644','2009-07-22 05:55:4' at line 1
    Code (markup):
    HTML code for the textbox

    <form action="" method="POST" name="form1" target="_self" id="start_topic">
      <table width="500" border="0" align="center" bgcolor="black" cellpadding="0" cellspacing="0">
        <tr>
    
          <td background=includes/grad.jpg><div align="center">Make a Topic </div></td>
        </tr>
        <tr>
          <td class="tableborder"><br /><div align="center">Subject: 
            <input name="title" type="text" class="textbox" id="insert_subject" value="" size="35" maxlength="23">
            <br>
            <br>
            </div>
            <br><center>
          <textarea name="topic_text" cols="50" rows="15" class="tableborder2" id="textarea" onselect="storeCaret(this);" onclick="storeCaret(this);" onkeyup="storeCaret(this);"></textarea></td>
        </tr>
        <tr>
          <td class="tableborder">
    
    	    <div align="center"><br>
              <br>
              <input type="submit" name="Submit" class='custombutton' class="custombutton" id="create_topic2" value="Create Topic">
                    </div></td>
        </tr>
      </table>
    </form>
    HTML:
    Here is the PHP code:

    if(strip_tags($_POST['Submit']) && strip_tags($_POST['title']) && strip_tags($_POST['topic_text'])){
    
    $time = time()+ (60 * 5);
    
    $title = strip_tags($_POST['title']);
    $topic_text=strip_tags($_POST['topic_text']);
    $forum=strip_tags($_POST['forum']);
    $new_time = time('h-i-s') + 60;
    
    if ($forum == "Crew" && $fetch->crew != "0"){
    mysql_query("INSERT INTO `topics` (`id`, `username`, `title`, `topictext`, `forum`, `locked`, `sticky`, `lastreply`,`made`,`crew`) VALUES ('', '$username', '$title1', '$topictext', '$forum', '0', '0', '$time','$timer','$fetch->crew');") or die (mysql_error());
    }else{
    mysql_query("INSERT INTO `topics` (`id`, `username`, `title`, `topictext`, `forum`, `locked`, `sticky`, `lastreply`,`made`) VALUES ('', '$username', '$title', '$topic_text', '$forum', '0', '0', '$time','$timer');") or die (mysql_error());
    }
    mysql_query("UPDATE users SET lasttop='$time' WHERE username='$username'");
    mysql_query("UPDATE users SET topictime='$new_time' WHERE username='$username'");
    $message =  "Topic Posted!";
    
    
    }
    PHP:
     
    CuBz, Jul 22, 2009 IP
  2. dimitar christoff

    dimitar christoff Active Member

    Messages:
    882
    Likes Received:
    62
    Best Answers:
    0
    Trophy Points:
    90
    #2
    don't just strip tags, also apply addslashes and check if magic_quotes_gpc is enabled.
     
    dimitar christoff, Jul 22, 2009 IP
  3. CuBz

    CuBz Peon

    Messages:
    117
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    tried using addslashes and still getting the same error

    plus i have never heard of MAGIC_QUOTES

    when looking it up on www.php.net i got this message:

    Warning
    
    This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0. Relying on this feature is highly discouraged.
    Code (markup):
     
    CuBz, Jul 22, 2009 IP
  4. Martinoes

    Martinoes Peon

    Messages:
    110
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Martinoes, Jul 22, 2009 IP
  5. CuBz

    CuBz Peon

    Messages:
    117
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    CuBz, Jul 22, 2009 IP
  6. Martinoes

    Martinoes Peon

    Messages:
    110
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #6
    Example query:

    
    $title1 = mysql_real_escape_string($title1);
    $topictext = mysql_real_escape_string($topictext);
    
    and so on.
    
    mysql_query("INSERT INTO `topics` (`id`, `username`, `title`, `topictext`, `forum`, `locked`, `sticky`, `lastreply`,`made`,`crew`) VALUES ('', '$username', '$title1', '$topictext', '$forum', '0', '0', '$time','$timer','$fetch->crew');") or die (mysql_error());
    
    PHP:
     
    Martinoes, Jul 22, 2009 IP
  7. wd_2k6

    wd_2k6 Peon

    Messages:
    1,740
    Likes Received:
    54
    Best Answers:
    0
    Trophy Points:
    0
    #7
    Is there any reason to use strip_tags, addslashes, magicquotes if we are using mysql_escape_string
     
    wd_2k6, Jul 22, 2009 IP
  8. CuBz

    CuBz Peon

    Messages:
    117
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #8


    Still Doesn't Work
     
    CuBz, Jul 22, 2009 IP
  9. wd_2k6

    wd_2k6 Peon

    Messages:
    1,740
    Likes Received:
    54
    Best Answers:
    0
    Trophy Points:
    0
    #9
    Try curly braces around the fetch part

    {$fetch->crew}
     
    wd_2k6, Jul 22, 2009 IP
    dimitar christoff likes this.
  10. CuBz

    CuBz Peon

    Messages:
    117
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #10
    without trying that, i know that will not do nothing at all

    I do know some php
     
    CuBz, Jul 22, 2009 IP
  11. wd_2k6

    wd_2k6 Peon

    Messages:
    1,740
    Likes Received:
    54
    Best Answers:
    0
    Trophy Points:
    0
    #11
    ok well you obviously know more than me so good luck..
     
    wd_2k6, Jul 22, 2009 IP
  12. killaklown

    killaklown Well-Known Member

    Messages:
    2,666
    Likes Received:
    87
    Best Answers:
    0
    Trophy Points:
    165
    #12
    stripslashes($_POST['name']); should work..

    Doing:

    
    str_replace("'","\'",$_POST['name']);
    
    PHP:
    should also work.. but have no idea why the other functions arnt working for you.
     
    killaklown, Jul 22, 2009 IP
  13. Steve136

    Steve136 Peon

    Messages:
    240
    Likes Received:
    15
    Best Answers:
    0
    Trophy Points:
    0
    #13
    Actually, that IS a valid statement.

    Using the curly braces around variables is used inside apostrophes and other statements.

    I've had a quick look through the code, not tested anything but see if this does anything -

    
    if(strip_tags($_POST['Submit']) && strip_tags($_POST['title']) && strip_tags($_POST['topic_text'])){
    	$time = time()+ (60 * 5);
    
    	$title	= mysql_real_escape_string($_POST['title']);
    	$topic_text = mysql_real_escape_string($_POST['topic_text']);
    	$forum	= mysql_real_escape_string($_POST['forum']);
    	$new_time   = time('h-i-s') + 60;
    
    	if($forum == "Crew" && $fetch->crew != "0"){
    		mysql_query("INSERT INTO `topics` (`id`, `username`, `title`, `topictext`, `forum`, `locked`, `sticky`, `lastreply`,`made`,`crew`) VALUES ('', '{$username}', '{$title1}', '{$topictext}', '{$forum}', '0', '0', '{$time}','{$timer}','{$fetch->crew}');") or die (mysql_error());
    	} else {
    		mysql_query("INSERT INTO `topics` (`id`, `username`, `title`, `topictext`, `forum`, `locked`, `sticky`, `lastreply`,`made`) VALUES ('', '{$username}', '{$title}', '{$topic_text}', '{$forum}', '0', '0', '{$time}','{$timer}');") or die (mysql_error());
    	}
    
    	mysql_query("UPDATE users SET lasttop='{$time}' WHERE username='{$username}'");
    	mysql_query("UPDATE users SET topictime='{$new_time}' WHERE username='{$username}'");
    
    	$message = 'Topic Posted!';
    }
    
    PHP:
    Regards,

    Steve
     
    Steve136, Jul 22, 2009 IP
  14. darrenbeige

    darrenbeige Peon

    Messages:
    97
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #14
    I agree with Steves code. {$var} is valid syntax. However, others on this forum are dis-illusioned.

    stripslashes() will fail. It removes escaped characters.

    You need to use addslashes() instead, which escapes the characters.
     
    darrenbeige, Jul 23, 2009 IP
  15. dimitar christoff

    dimitar christoff Active Member

    Messages:
    882
    Likes Received:
    62
    Best Answers:
    0
    Trophy Points:
    90
    #15
    +rep for this, well spotted :)

    also apply it around array elements, eg, .. = '$foo['bar']' would become = '{$foo['bar']}'

    Cubz: you'd do well to try / read up on things like that first before dismissing it out of hand. if you _know_ php then you'd be able to understand the difficulty in parsing the object property as a part of a string that is being evaluated - the braces keep the structure together and force it to be evaluated as a single entity. otherwise, the resulting string will come out the same as echo $fetch . "->crew";
     
    dimitar christoff, Jul 23, 2009 IP
  16. CuBz

    CuBz Peon

    Messages:
    117
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #16
    still not working

    sorry wd_2k6 i thought wrong
     
    CuBz, Jul 23, 2009 IP
  17. Chemo

    Chemo Peon

    Messages:
    146
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    0
    #17
    
    /**
       * Function to prepare userland input for DB
       * {@source}
       * @author Bobby Easland
       * @link http://www.oscommerce-freelancers.com/ osCommerce Freelancers
       * @param string $text Text to be prepared
       * @return string
       */
    function DBPrepare($text) {
        // Strip the slashes if magic quotes is enabled
        if ( get_magic_quotes_gpc() ) {
            $text = stripslashes($text);
        }
        // Return the escaped, HTML special character encoded string
        return mysql_real_escape_string(htmlspecialchars($text, ENT_QUOTES));
    } # end function
    
    /**
       * Function to insert or update rows - general data modification
       * {@source}
       * @author Bobby Easland
       * @link http://www.oscommerce-freelancers.com/ osCommerce Freelancers
       * @param string $table Table to be modified
       * @param array $data Associative array of data elements
       * @param string $action insert or update, defaults to insert
       * @param string $where Only used for updates to specify delimiter
       * @throws RuntimeException Upon invalid action or execution error
       * @return int
       */
    function DMQuery($table, array $data, $action = 'insert', $where = '') {
        switch($action){
            case 'insert':
                $sql = "INSERT INTO `" . $table . "` (`". implode('`, `', array_keys($data)) . "`) VALUES ('". implode(array_values("', '" $data)) . "')";
                break;
            case 'update':
                $sql = "UPDATE {$table} SET ";
                foreach( $data as $column => $value ){
                    $sql .= $column . " = '". $value ."',";
                }
                $sql = rtrim($sql, ',') . " WHERE {$where}";  
                break;
            default:
                throw new RuntimeException('Action not valid: ' . $action);
                break;
        } # end switch
    
        if ( false === mysql_query($sql) ){
            throw new RuntimeException('MySQL error: ' . mysql_error());
        }
    
        return mysql_affected_rows();
    } # end function
    
    if( isset($_POST['Submit']) ){
    
        $time = time()+ (60 * 5);
    
        $POST = array_map('DBPrepare', $_POST);
        extract($POST, EXTR_OVERWRITE);
        
        $new_time   = time('h-i-s') + 60;
    
        if($forum == "Crew" && $fetch->crew != "0"){
            $insert = array('id' => '',
                                   'username' => $username,
                                   'title' => $title1,
                                   'topictext' => $topictext,
                                   'forum' => $forum,
                                   'sticky' => 0,
                                   'lastreply' => 0,
                                   'made' => $time,
                                   'crew' => $fetch->crew
                                   );
            DMQuery('topics', $insert);
        } else {
            $insert = array('id' => '',
                                   'username' => $username,
                                   'title' => $title,
                                   'topictext' => $topic_text, // Should this be $topictext??
                                   'forum' => $forum,
                                   'locked' => 0,
                                   'sticky' => 0,
                                   'lastreply' => $time,
                                   'made' => $timer
                                   );
            DMQuery('topics', $insert);
        }
    
        DMQuery('users', array('lasttop' => $time), 'update', "username = '{$username}'");
        DMQuery('users', array('topictime' => $new_time), 'update', "username = '{$username}'");
    
        $message = 'Topic Posted!';
    }
    
    PHP:
     
    Chemo, Jul 23, 2009 IP
  18. dimitar christoff

    dimitar christoff Active Member

    Messages:
    882
    Likes Received:
    62
    Best Answers:
    0
    Trophy Points:
    90
    #18
    the bug he pointed is unrelated to the syntax error, actually.
     
    dimitar christoff, Jul 24, 2009 IP
  19. Chemo

    Chemo Peon

    Messages:
    146
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    0
    #19
    Exactly. Here is what he actually needs distilled down:
    
    mysql_real_escape_string(htmlspecialchars($text, ENT_QUOTES));
    
    PHP:
     
    Chemo, Jul 24, 2009 IP