0

For some reason, long posts are not inserted into the database, when the post includes a very long text (i.e. more than 200 words or so). However, this issue is pretty vague since some of these long texts are inserted in the database (for instance a large lorum ipsum text is inserted without any problem). First I thought it had something to do with the punctuation but this was not the issue. Also, text-breaks etc. are not the cause of the issue. Furthermore, I checked the data structure of the comment part (which is assigned a textarea as is shown below) in the database and there I saw it has been given a long text as a type. So character restrictions aren't the problem either. Thus, the strange thing is that it only occurs with "some" long texts. Short texts that are about 200 words are no problem and are inserted perfectly.

My code is as follows. First the HTML part:

    <div class="new-com-bt">
    <span>Schrijf hier uw bericht ....</span>
</div>
<div class="new-com-cnt">
    <input type="text" id="name-com" name="name-com" value="" placeholder="Uw naam" />
    <input type="text" id="mail-com" name="mail-com" value="" placeholder="Uw e-mail adres" />
    <input type="text" id="code-com" name="code-com" value="" placeholder="Viercijferige code..." />
    <textarea class="the-new-com"></textarea>

    <span class="rating2">Beoordeel ons:&nbsp;
        <input type="radio" class="rating-input"
            id="rating-input-2-1" name="example" value="5">
        <label for="rating-input-2-1" class="rating-star"></label>
        <input type="radio" class="rating-input"
            id="rating-input-2-2" name="example" value="4">
        <label for="rating-input-2-2" class="rating-star"></label>
        <input type="radio" class="rating-input"
            id="rating-input-2-3" name="example" value="3">
        <label for="rating-input-2-3" class="rating-star"></label>
        <input type="radio" class="rating-input"
            id="rating-input-2-4" name="example" value="2">
        <label for="rating-input-2-4" class="rating-star"></label>
        <input type="radio" class="rating-input"
            id="rating-input-2-5" name="example" value="1">
        <label for="rating-input-2-5" class="rating-star"></label>
    </span>

    <div class="bt-add-com">Plaats bericht</div>
    <div class="bt-cancel-com">Annuleer</div>
</div>

Now the JQuery part:

<script type="text/javascript">
  $(function(){ 
    //alert(event.timeStamp);
              $('.new-com-bt').click(function(event){    
              $(this).hide();
              $('.new-com-cnt').show();
               $('#name-com').focus();
    });

    /* when start writing the comment activate the "add" button */
    $('.the-new-com').bind('input propertychange', function() {
       $(".bt-add-com").css({opacity:0.6});
       var checklength = $(this).val().length;
       if(checklength){ $(".bt-add-com").css({opacity:1}); }
    });

    /* on clic  on the cancel button */
    $('.bt-cancel-com').click(function(){
        $('.the-new-com').val('');
        $('.new-com-cnt').fadeOut('fast', function(){
            $('.new-com-bt').fadeIn('fast');
        });
    });

    // on post comment click 
    $('.bt-add-com').click(function(){
        var theCom = $('.the-new-com');
        var theName = $('#name-com');
        var theMail = $('#mail-com');
        var theCode = $('#code-com');
        var theRating = $('input[name=example]:checked');

        if( !theCom.val()){ 
            alert('U moet een bericht schrijven'); 
        }else if(theCode.val() != '7624'){
            alert('Vul de viercijferige code in die u heeft gekregen tijdens de ceremonie')
        }else{
            $.ajax({
                type: "POST",
                url: "ajax/add-comment.php",
                data: 'act=add-com&id_post='+<?php echo $id_post; ?>+'&name='+theName.val()+'&email='+theMail.val()+'&comment='+theCom.val()+'&rating='+theRating.val(),
                success: function(html){
                    theCom.val('');
                    theMail.val('');
                    theName.val('');
                    theRating.val('');
                        setTimeout(function(){
                            //fade back
                            $('.new-com-cnt').html("Dank u wel voor uw bericht. Deze zal zo spoedig mogelijk op de site verschijnen!");
                        }, 0);
                    }  
            });
        }
    });

});

This is the add-comment.php script:

<?php
extract($_POST);
if($_POST['act'] == 'add-com'):
$name = htmlentities($name);
$email = htmlentities($email);
$comment = htmlentities($comment);
$rating = htmlentities($rating);

include('../config.php'); 

// Get gravatar Image 
// https://fr.gravatar.com/site/implement/images/php/
$default = "mm";
$size = 35;
$grav_url = "http://www.gravatar.com/avatar/" . md5( strtolower( trim( $email ) ) ) . "?d=" . $default . "&s=" . $size;

if(strlen($name) <= '1'){ $name = 'Guest';}
//insert the comment in the database
mysql_query("INSERT INTO comments (name, email, comment, id_post, rating, display)VALUES( '$name', '$email', '$comment', '$id_post', '$rating', 'nee')");
if(!mysql_errno()){
?>

<div class="cmt-cnt">
    <img src="<?php echo $grav_url; ?>" alt="" />
    <div class="thecom">
        <h5><?php echo $name; ?></h5><span data-utime="1371248446" class="com-dt"><?php echo date('d-m-Y H:i'); ?></span><span class="com-dt-rating"><span class="rating">
                <input type="radio" class="rating-input"
                    id="rating-input-1-1" value="5" disabled="disabled" <?php echo ($rating=='5')?'checked':'' ?> />
                <label for="rating-input-1-1" class="rating-star"></label>
                <input type="radio" class="rating-input"
                    id="rating-input-1-2" value="4" disabled="disabled" <?php echo ($rating=='4')?'checked':'' ?> />
                <label for="rating-input-1-2" class="rating-star"></label>
                <input type="radio" class="rating-input"
                    id="rating-input-1-3" value="3" disabled="disabled" <?php echo ($rating=='3')?'checked':'' ?> />
                <label for="rating-input-1-3" class="rating-star"></label>
                <input type="radio" class="rating-input"
                    id="rating-input-1-4" value="2" disabled="disabled" <?php echo ($rating=='2')?'checked':'' ?> />
                <label for="rating-input-1-4" class="rating-star"></label>
                <input type="radio" class="rating-input"
                    id="rating-input-1-5" value="1" disabled="disabled" <?php echo ($rating=='1')?'checked':'' ?> />
                <label for="rating-input-1-5" class="rating-star"></label>
            </span></span>
        <br/>
        <p>
            <?php echo $comment; ?>
        </p>
    </div>
</div><!-- end "cmt-cnt" -->

<?php } ?>

An example of a long text that is inserted:

he technique described in the paper to model and formalize requirements is called FLAGS. FLAGS offers the possibility to model and formalize fuzzy goals, besides crisp goals. Distinctive about these fuzzy goals is that they cannot be concretely achieved, whereas crisp goals can. Instead, the achievability of these goals is vague and therefore they cannot either be satisfied or not, but they can be satisfied to a certain extent. hink of saving fuel while driving a car as a goal. It is not clear whether this goal is concretely achieved. hat is, fuel consumption can only be small, but that doesn’t state whether the goal is clear-cut achieved or not. Instead, it is only satisfied to a certain extent, namely when a car only uses a small amount of fuel. he same way of thinking can be applied to physiotherapy by modelling these kind of goals to evaluate the speed and correctness of movements realized by a person, which can only be done properly when the FLAGS goal model elements are formalized.

A few steps need to be followed in order to apply FLAGS. hese steps can be found in Appendix A in table 1 and will be further elaborated in this chapter by describing an example in which an application is described to learn a robot how to move like a human being. As the example concerns a robot application, and thus describes another situation, the FLAGS meta-model from Pasquale et al. (2013) is extended to the example described in this chapter. his extended FLAGS meta-model can be consulted in figure 2 included in appendix A. Furthermore, for the example it is assumed that the requirements are already identified.

he FLAGS meta-model consists of several classes that describe the composition of the FLAGS goal model at an abstract level. It explains that either crisp goals (clear goals) or fuzzy goals (achievable to a specific extent) can be modeled. Besides, goals can influence each other (influenced by relationship) and can be decomposed into sub goals (decomposed by relationship). Achieving these goals is important for both the person and the robot. Moreover, domain assumptions (conditions) and operations are adopted in the FLAGS meta-model and a person uses a controller to monitor his or her movements so that the robot can respond to these movement

An example of a text that is not inserted:

Mijn iboga ervaring bij iboga farm Zeer mooie en rustige locatie en een heerlijke sfeer, goed verzorgd. Geen haastigheid maar alles in een relaxte flow. Ik wist niet wat ik moest verwachten maar de jongens stellen je goed gerust, goede uitleg en er word goed rekening gehouden met je gezondheid toestand en eet gewoontes. Alles is aanwezig wat men nodig heeft. Eten,drinken,douche gelegenheid,slaap plek etc Mooie ceremonie voorafgaand. Eerst krijg je een test dosis om vast te kunnen stellen of men allergisch is voor de substantie. Iets wat veel andere niet doen. Als het eenmaal werkt word de sessie begonnen terwijl je boven op een comfortabel bed ligt, Met een spiritueel muziekje op de achtergrond. Toen het eenmaal goed werkte ervaarde ik een soort van ijl achtige droomstaat trip waarbij er visioenen tevoorschijn komen. Ik persoonlijk heb vorige levens en voorouders gezien en gevoeld. Ondertussen word er zeer goed op je gelet en je word uitstekend verzorgd, je zal niks tekort komen gedurende de iboga reis. Als men het toilet nodig heeft wel even om assistentie vragen want het lopen gaat wat moeilijk. Tijdens de reis zal het voor ieder andere anders zijn want het zijn allemaal persoonlijke kwesties die verwerkt worden. Ondertussen de sessie merk je al dat er veel dwars liggende emotie's en gewoontes verdwijnen uit je systeem, en

chris85
  • 23,846
  • 7
  • 34
  • 51
user2237168
  • 305
  • 1
  • 3
  • 17

2 Answers2

2

Example 1 has no single quote. Example 2 has a single quote, so your DB is throwing a 1064 error. When using the mysql_errno() you should do something with the error if there is one. So at your closing do

} else {
    echo mysql_errno() . ": " . mysql_error();
}

The error occurs at emotie's because the ' closes the SQL string and then the remaining text SQL doesn't know what to do with. This is also how SQL injections work. The ' is maliciously used and then SQL commands are passed in. Using the mysql_ functions you have to use the escaping functions to prevent this. You should really update to mysqli_ or PDO though. Then you can use parameterized queries where the driver handles the quoting.

So to assign your variables they should be:

$name = mysql_real_escape_string(htmlentities($name);
$email = mysql_real_escape_string(htmlentities($email));
$comment = mysql_real_escape_string(htmlentities($comment));
$rating = mysql_real_escape_string(htmlentities($rating));

Also note the warnings on the manual's page this isn't the best way but it is the best approach with the mysql_ driver. http://php.net/manual/en/function.mysql-error.php

For more on the topic see:
How can I prevent SQL injection in PHP?
https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet

Community
  • 1
  • 1
chris85
  • 23,846
  • 7
  • 34
  • 51
  • Thnx chris for your help. After your solution I still needed to add one more thing in my client side JQuery. I needed to add encodeURIComponent() to deal with the ampersand. Now everything is working fine! – user2237168 Feb 07 '16 at 19:19
1

You need to use prepared SQL statements so that you don't have sql injection issues and a apostrophe ' in the user input doesn't kill your insert.

http://php.net/manual/en/mysqli.quickstart.prepared-statements.php

Your code should be similar to this

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$databasename = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $databasename);

// Was there a connection error?
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// prepare and bind
$stmt = $conn->prepare("INSERT INTO comments (name, email, comment) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $name, $email, $comment);

// set parameters and execute
$name = "John";
$email = "john@example.com";
$comment = "TEST";
$stmt->execute();
PHPDave
  • 904
  • 1
  • 7
  • 15
  • Thnx for the comment about security! However, would you know what is causing this issue? Small texts are inserted as well (i.e. up to 200 words everything is fine). The problem is that "some" long texts are not inserted – user2237168 Feb 06 '16 at 18:58
  • in the long texts, are there any apostrophes? – PHPDave Feb 06 '16 at 19:01
  • @user2237168 the "long texts" probably have a quote in them at some point. Provide a reproducible example of the issue for specific help. – chris85 Feb 06 '16 at 19:01
  • EX: if $name="O'Malley", your script will fail to run because it will create a sql syntax error – PHPDave Feb 06 '16 at 19:02
  • You can use addslashes($name) to try and escape the apostrophe, but still leave you open to a sql injection attack where a hacker could delete your database, or pull data from other files etc... – PHPDave Feb 06 '16 at 19:04
  • Dear PHPDave and chris85 thanks for your suggestions. However the addslashes do not work. @chris85 I posted two long texts, the first one is inserted without any problem. The second piece of text on the other hand is not inserted. – user2237168 Feb 07 '16 at 09:22