简体   繁体   中英

String value accumulating empty spaces in MySQL database

I have a webpage where admin users can edit the text on the page. But when they insert the text into the mysql database, it sometimes adds more and more white spaces before the acual content.
If you place your cursur before the first word on the page and spam backspace for a while, the whitespace in the database dissappears. But over time, the more you keep editing the page, more and more whitespaces are added again.

I did a lot of trouble shooting, but I just can't figure out what causes the whitespaces to be added. It does not always happen making it really difficult to troubleshoot.

Here's my code:

As my code is pretty long, I tried to translate most of the content to english.
If you want to translate something that in't already translated, the original language is Dutch.

- Shows edit button and page content from the database. 显示数据库中的编辑按钮和页面内容。

//Active page:
$pagina = 'over_ons'; ?>
<input type='hidden' id='pagina' value='<?php echo $pagina; ?>'> <!--Show active page to javascript--><?php
//Active user:
if(isset($_SESSION['correct_ingelogd']) and $_SESSION['functie']=='admin'){
$editor = $_SESSION['gebruikersnaam']; ?>
<input type='hidden' id='editor' value='<?php echo $editor; ?>'> <!--Show active user to javascript--><?php  
} ?>

<!--Editable DIV: -->
<div class='big_wrapper'><?php
        //Get eddited page content from the database
        $query=mysql_query("SELECT inhoud FROM paginas WHERE naam_pagina='" .$pagina. "'");
        while($inhoud_test=mysql_fetch_array($query)){
            $inhoud=$inhoud_test[0];
        }

    //Show Content
    ?><div id='editedText'><?php echo $inhoud; ?></p></div>

<!--Show edit button-->
<?php
if(isset($_SESSION['correct_ingelogd']) and $_SESSION['functie']=='admin')
{?>
    <div id='sidenote'>
        <input type='button' value='Bewerken' id='sent_data' class='button' />
        <div id="feedback" />
    </div>
<?php }

- Sents page content to the php file sent_data.php: 将页面内容发送到php文件send_data.php:

//If the system is in edit mode and the user tries to leave the page,
//let the user know it is not so smart to leave yet.
$(window).bind('beforeunload', function(){
var value = $('#sent_data').attr('value'); //change the name of the edit button

if(value == 'Verstuur bewerkingen'){
    return 'Are you sure you want to leave the page? All unsaved edits will be lost!';
}
});

//Make content editable and send page content
$('#sent_data').click(function(){
    var value = $('#sent_data').attr('value'); //change the name of the edit button

    if(value == 'Bewerken'){
        $('#sent_data').attr('value', 'Verstuur bewerkingen');  //change the name of the edit button
        var $div=$('#editedText'), isEditable=$div.is('.editable'); //Make div editable
        $div.prop('contenteditable',!isEditable).toggleClass('editable')
        $('#feedback').html('<p class="opvallend">The content from<BR>this page is now<BR>editable.</p>');
    }else if(value == 'Verstuur bewerkingen'){
                var pagina = $('#pagina').val();
                var editor = $('#editor').val();
                var div_inhoud = $("#editedText").html();
                $.ajax({
                type: 'POST',
                url:  'sent_data.php',
                data: 'tekst=' +div_inhoud+ '&pagina=' +pagina+ '&editor=' +editor,
                success: function(data){
                Change the div back tot not editable, and change the button's name
                    $('#sent_data').attr('value', 'Bewerken');  //change the name of the edit button
                    var $div=$('#editedText'), isEditable=$div.is('.editable'); //Make div not editable
                    $div.prop('contenteditable',!isEditable).toggleClass('editable')

                //Tell the user if the edditing was succesfully
                    $('#feedback').html(data);
                    setTimeout(function(){
                        var value = $('#sent_data').attr('value'); //look up the name of the edit button
                        if(value == 'Bewerken'){ //Only if the button's name is 'bewerken', take away the help text
                        $('#feedback').text('');
                        }
                        }, 5000);
                    }
                    }).fail(function() {
                    //If there was an error, let the user know
                        $('#feedback').html('<p class="opvallend">There was an error.<BR>Your changes have<BR>not been saved.<BR>Please try again.</p>');
                    });
    }
});


And finally,
- Get page content from javascript,js and insert into database: 从javascript,js获取页面内容并插入数据库:

<?php
session_start();
include_once('./main.php');
include($main .'connectie.php');

//Look up which page has to be edited
$pagina=$_POST['pagina'];
//Get the name of the person who eddited the page
$editor=$_POST['editor'];
//Get content:
$tekst=$_POST['tekst'];
$tekst = mysql_real_escape_string($tekst);
$tekst = trim($tekst);

$query="UPDATE paginas SET naam_editer='" .$editor. "', inhoud='" .$tekst. "' WHERE naam_pagina='" .$pagina. "'";

}
    if(mysql_query($query)){
        echo "<p class='opvallend'>Successfully saves changes.</p>";
    }else{
        echo "<p class='opvallend'>Saving of changes failed.<BR>
        Please try again.</p>";
    }
?>

Extra information:
PHP version: 5.5.15
jQuery version: 1.11.1
Testing in browser: Chrome
Database: phpMyAdmin 5.5.39
The content is inserted in a VARCHAR type with space for 10000 caracters

Thanks in advance for you help!

Thanks to the great help of a lot of people, and especially @avnishkgaur, it is working perfectly now. Here is what I ajusted (also changed it in my code above, so that's working code now).

1. Removed all the white spaces I had in my code between <div id='editable'> and <?php
2. Added $tekst = trim($tekst); to my PHP file to remove white spaces (didn't work) Added $tekst = trim($tekst); to my PHP file to remove white spaces (didn't work)
3. Placed the editable text into another div as the code for getting the data from the database (was in the same div before)
4. Renamed the ID from the editable div to editedText. Also changed the name in the javascript file. This solution made it work perfectly (it was 'editable' before). Renamed the ID from the editable div to editedText. Also changed the name in the javascript file. This solution made it work perfectly (it was 'editable' before).

This was kind of an unexpected solution, so I think this could help others too.

As to why it is adding extra whitespace, I think it is because you are inserting the text from database into div directly (which contains some white space in html code, which is removed when page is rendered).

One efficient solution would be to insert your content in

tag, probably like this:

<div class='big_wrapper'>
<p id='editable'></p>
</div>

Another solution is to trim the text before inserting into db. You can do that either at javascript post stage, or right before inserting in mysql db.

In jQuery, (which you are using) you can implement this :

data: 'tekst=' +$.trim(div_inhoud)+ '&pagina=' +pagina+ '&editor=' +$.trim(editor),

or in sent_data.php, you can use TRIM mysql function in your update query.

First of all, I would strongly suggest to use mysqli or PDO instead of the mysql functions in PHP, as these are deprecated. Please look into this on PHP.net.

As for your problem, I have no tried to reproduce the issue. I suggest you log and check what happens step by step, for example logging the div_inhoud var, are the spaces included at this stage already? And so on.

If you are in a hurry, you could also use the PHP function ltrim on the $tekst var in your sent_data.php , which would trim all spaces on the left side (Or any characters you would want to be trimmed from the string)

尝试在send_data.php中添加trim()函数,这将帮助您去除空格。

$tekst = trim($_POST['tekst']);

My guess is that the newlines after the <div id='editable'> and ?> and the indentation of <?php in over_ons.php is adding the extra whitespace. Specifically, a couple of extra /n 's and also spaces from the indentation within the file.

You could trim the whitespace before saving it to your database, or alternatively, before the ajax call, or both.

In php, trim() :

sent_data.php

$tekst = trim($tekst);

Or javascript, str.trim() :

javascript.js

var div_inhoud = $("#editable").html().trim();

Also, you may want to consider using PHP Data Objects , instead of inserting variables directly into your SQL statements. It's actually really easy to use and in my opinion makes code easier to read and more reusable. There is a fantastic tutorial by Tuts+ that makes it easy to learn and get started. This will ensure you don't accidentally allow SQL injection issues into your application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM