0

i have a stored procedure to send and fetch blog data to database at the same time:

CREATE DEFINER=`root`@`localhost` PROCEDURE `post_and_fetch_ans`(
    IN answerbody longtext,
    IN postid int,
    IN answerer int)
BEGIN
   INSERT INTO `login`.`answers` (answer_body,userpost_post_id,users_user_id) VALUES (answerbody,postid,answerer);
   SELECT * FROM `login`.`answers` WHERE userpost_post_id = postid  ORDER BY answer_date DESC LIMIT 1;
END

But my problem is the amount of text data i write on the text editor ,only a few lines are send and store to the database.I am using ajax to send the data to a php page which will store it to database .

$('#answerform').submit(function(event){
   event.preventDefault();
   var data='answer_body='+CKEDITOR.instances.content.getData()+'&userpost_post_id=<?php echo $contents[0]->post_id;?>&users_user_id=<?php echo $userdata->user_id; ?>';
   alert(data);

   $.ajax('../includes/verifyanswer.php',{
        data:data,
        type:"POST",
        datatype:'json',
        success:function(response){
            alert(response);

            var obj=$.parseJSON(response);

            $('#mainanswer').hide();
            $('#answerform').hide();
            $('#answerthisquestion').show();
            var str="<div class='styleanswer' >"+obj[0]['answer_body']+'</div><hr>';

            $('#answerwrapper').append(str);
            $('#answerwrapper pre code').each(function(i, block) {
                hljs.highlightBlock(block);
            });
        },
        error:function(response){
            alert(response);
        }
    });
}); 

and verifyanswer.php page is :

require_once '../core/init.php';
$answer=$_POST['answer_body'];

$post_id=$_POST['userpost_post_id'];
$answerer=$_POST['users_user_id'];

if(isset($answer,$post_id,$answerer)){
    if(!empty($answer) && !empty($post_id) && !empty($answerer)){
        $db = DB::getInstance();
        $result = $db->post_and_fetch("CALL login.post_and_fetch_ans(?,?,?)",array($answer,$post_id,$answerer))->result();
        echo json_encode($result);
    }
}

this line

$answer=$_POST['answer_body'];

contains only the partial (very less than actual text) text ,not the full text.So less text is stored in database

an example of the problem is

i send this amount of text to store in DB

enter image description here

but i get only this few lines of text stored in DB

Congratulations to Mathematics SE for being the first site to unlock this hat, less than 18 hours into the event! Also to Code Review SE and Blender SE for technically needing only three users each to get this hat (i.e. at the time that the hat was earned, one user had 16 or more hats, and two other users had enough hats that the first user didn

d.coder
  • 1,988
  • 16
  • 23
AL-zami
  • 8,902
  • 15
  • 71
  • 130

3 Answers3

4

Few options come to mind.

  1. The apostrophe may be ending your SQL statement. You will need to escape it.

  2. The field that you're trying to store your data in is too small.

Chris Fremgen
  • 4,649
  • 1
  • 26
  • 26
  • if point 1 == true, does it mean he is vulnerable to `SQL Injection`? – bart s Jan 08 '16 at 20:58
  • can you please tell my in which line this problem lies ?can't find it – AL-zami Jan 08 '16 at 21:00
  • @AL-zami Always escape special characters in a string for use in an SQL statement. $answer= mysqli_real_escape_string($_POST['answer_body']); – aayush93 Jan 08 '16 at 21:01
  • @barts Most likely, but maybe not since he's using a stored proc. – Chris Fremgen Jan 08 '16 at 21:01
  • how can i escape it in my sql? – AL-zami Jan 08 '16 at 21:02
  • @al-zami Check your procedure 'login.post_and_fetch_ans'. Possibly this is not correct, or the database field is not big enough. What size is the column you're saving to? – Chris Fremgen Jan 08 '16 at 21:03
  • it is of type "longtext" and i gave it a length of 33333.should be engough to hold this amount text – AL-zami Jan 08 '16 at 21:07
  • 1
    @Al-zami I would try again with even smaller data, but keep an apostrophe in there. Try to send "This is a ' test" and see what is stored. If it ends again before the apostrophe, then your problem is with the apostrophe. – Chris Fremgen Jan 08 '16 at 21:17
  • yah it ended before the apostrophe..How can i escape it . – AL-zami Jan 08 '16 at 21:19
  • @AL-zami apart from your question, please find some information about `SQL injection`, what it is, how it can destroy your database etc, and how you can prevent from being vulnerable to `SQL Injection` – bart s Jan 08 '16 at 21:20
  • @Al-zami See the answer by Ralrom. – Chris Fremgen Jan 08 '16 at 21:21
3

Problem

As others have mentioned, the problem is caused by special characters in your answer body. The current way you are storing your answers causes special characters to interfere with the SQL commands and leaves you vulnerable to SQL injections.

Solution 1

You can use mysqli_real_escape_string in PHP.

mysqli_real_escape_string - Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection

mysqli_real_escape_string

Solution 2 (Better)

You can fix your problem and prevent SQL Injection by using prepared statements with bound parameters. Check this other SO answer to learn more.

Community
  • 1
  • 1
ralrom
  • 433
  • 3
  • 9
  • but as you can see my query is parameterized "CALL login.post_and_fetch_ans(?,?,?)" . and i bind value to it before sending it to database.So what's the problem? – AL-zami Jan 09 '16 at 07:35
1

You're not properly encoding the POST data in the Javascript code. Instead of concatenating strings, set the data: option to an object, and jQuery will encode it properly.

var data = {
    answer_body: CKEDITOR.instances.content.getData(),
    userpost_post_id: <?php echo $contents[0]->post_id;?>,
    users_user_id: <?php echo $userdata->user_id; ?>
};
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • if i use it it works (store data with quote) but in response i am getting an error : SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data in my ajax response – AL-zami Jan 09 '16 at 09:10
  • That means you're not sending back correct JSON. Make sure the script doesn't produce any other output before or after it does `echo json_encode$result)`. You can use the Network tab of the browser console to see the complete AJAX response, and you'll see what you're returning. – Barmar Jan 09 '16 at 15:46