How can I retrieve character data from MySQL without the extra spaces? - php

I am using a form to load text into a database. Then, I'm pulling the text back out with php in order to dynamically create my CSS selectors. Then I'm using javascript to toggle the selectors on and off as needed. Everything works well except the retrieved data has long lines of spaces in it (like the entire textarea of the form is included) and therefore, the javascript doesn't work due to the extra spaces. Because these are labels, they vary in length. I've tried storing the data as VARCHAR CHAR and TEXT.
How can I retrieve only the characters from MySQL? I have seen it somewhere in the manual but can't seem to find it now.
Thanks

You could just use trim in PHP. MySQL also has a TRIM().
Note that this removes all whitespace before and after the string, not space within the string.
You also will apparently always have a newline submitted because of the whitespace in the html itself. You should probably close the textarea without creating additional whitespace.

Do you just want to replace all white spaces?
REPLACE(col, ' ', '')
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_replace

Related

Only allow certain characters to be entered in database

I was checking for an answer to only accept certain type of characters and ignoring some.
I found a link in stack itself, here
But, even though that prevents from entering the data in text box, anyone with a little knowledge of how to inspect the content and delete the pattern from client side will allow it to enter any detail it wants and send to database.
Is there any way I can prevent it for my website? I don't want certain characters like space, semicolon, etc.
Frontend in html & php
Backend in MySQL
It could be done with pattern attribute on clients side, but HTML5 textarea element does not support the pattern attribute.
The another way is to use JavaScript (as you mentioned)
var text = $('textarea').val();
var expres = /[^a-zA-Z0-9\!\#\#\$\%\^\*\|]+/;
if(expres.test(text)){
//... some action
}
If you would like to replace invalid characters, you can use jQuery function replace() which is similar to preg_replace() in PHP and it accepts regular expresions.
You could check validity on server side (in PHP) too (before inserting the values to db)
preg_replace("/[^A-Za-z0-9 ]/", '', $string);
First of all,
You can define a type for each column in your database, for example, if you set type as integer - you won't be able to insert anything else.
Let us assume you're looking to "filter" or manipulate strings in your database - I Would make a regex to replace any unwanted character from the string and the insert it into database.

Correct formatting of HTML in database

I'm using TinyMCE to save some HTML into an SQL table in phpMyAdmin. Inserting and retrieving the row from the table works fine.
I'm using a regex to translate some short codes in the retrieved text and this is where the problem arises.
This is my regular expression, which simply gets the text between two short codes with possible html tags and new lines:
/(<.+>)?[[]{$code}[]](<\/.+>)?((?:\n.+\n?)+)(<.+>)?[[]{$code}[]](<\/.+>)?/
When I retrieve the HTML from the DB and run the regex on it, the preg_match_all() fails to match anything, but when I double-click on the row in the database and open the in-line editor, phpMyAdmin does...something and performs an update on the row automatically and sets the text to a new value; Then, when I run the regex on the newly updated value, preg_match_all() matches the correct values.
I was thinking it was some automatic text encoding conversion or something, but running mb_detect_encoding() on the HTML before I insert it indeed confirms that the encoding is UTF-8 same as the table's utf8_unicode_ci.
I then compared the text plus EOL characters before and after the update in Notepad++ and they're exactly the same, yet my regex doesn't work before phpMyAdmin updates it.
What is phpMyAdmin doing to fix the text and how can I do it before it gets inserted in to the database? Why is it automatically updating the row at all?
I added some more code to the regular expression to check for content after the short code on the same line and now preg_match_all() matches correctly every time. I'm still not sure what's going on there as the content before and after the update are identical in every test I've tried (Same text, same amount of spaces and new line characters).
Regardless, I fixed it by adding the below regex after the check for the end HTML tag:
(?:.+)?
So the full expression is:
(<.+>)?[[]{$code}[]](<\/.+>)?(?:.+)?((?:\n.+\n?)+)(<.+>)?[[]{$code}[]](<\/.+>)?

Inserting HTML into database

I am inserting data into a table which contains some basic html tags, double quotes and single quotes.
I am using the following line to handle the data:
htmlentities(($_POST[content]), ENT_QUOTES);
The problem with this is that when I select this data to bring it back onto the screen, displays the actual html tags instead of rendering the html, i.e. if I use the <b>bold</b> tag, is displays it as text instead of making the text within that tag bold. If I don't use the above line, i.e.
htmlentities(($_POST[content]), ENT_QUOTES);
Then I can't insert the data into the database because the data can contain single quotes and double quotes.
How do I deal with this issue?
So basically, I should be able to insert the data into the database where single or double quotes should not cause a problem. When when rendering the data back onto the screen, it should render html tabs as they should get rendered into the browser and the quotes should be displayed as quotes in the text being rended back onto the screen.
You are inserting data into a database, not into an HTML document. Don't use htmlentities. Use whatever methods your database provides for escaping content. This should be something that uses bound parameters. Bobby-tables explains a number of different methods
$html = mysql_real_escape_string($html);
http://php.net/manual/en/function.mysql-real-escape-string.php
Make sure you have made a proper mysql connection mysql_connect before using this function.
you have to use strip_tags($str);
if you want remove only html tags.. single quote or double quote will remain...
but the problem in your case is ...you are putting lots of white space with your strings so you can perfectly use use strip_tags($str);
Putting so much HTML codes into the mysql table seems an ugly method to me, it is needed if you are adding a post but if you are saving a page which you may repopulate you may consider another way.
this is my method doing this:
Clear any html code
Put useful data into array (serialize array)
Save array into database
Repopulate array when the page is called (unserialize array)
This saved me to put <1kb data instead of 125kb
This is a good way if you are using templating like systems.

Preserve user comments format in database

HI,
I am creating on comments form where users will be commented and will be stored in the MYSQL database. The problem what I am facing is, it is stored as the single line in the database. It should be stored with exact format how user is entered in the form(like new lines and everything). I am using PHP to store it in the MySQL db.
First store it as text or longtext. Second, when showing the comment, use a function like nl2br to convert newlines to html <br> elements. This way, linebreaks are preserved.
Your text is stored just fine in the database if you are putting it into a long enough text-type field (e.g. TEXT), including the newlines in the user input.
Your problem is how to display the text formatted the way the user was seeing it when entering it. This is a more generic problem, and it only has to do with how HTML treats whitespace.
One approach would be to call nl2br on the comments, as Ikke says. This would replace all newlines (which the browser disregards) with <br> tags which have a visible effect on the rendered output.
Another option would be to put the text inside a <pre>...</pre> tag. This will force the browser to render it with whitespace preserved.
It's really up to what's more convenient/suitable for you.
Update: Just to be clear: do not modify the user input before inserting it in the database (unless it's part of your input validation, like e.g. stripping HTML tags from the input). Store it in an "untouched" format, and only do some processing on it before you output the data. This way, you always have the option of performing the correct processing if your output channel changes in the future (e.g. export comments to a text file vs displaying them as HTML).
you can store the comments in the same form in the mysql database. one difference would be when you retrieve the comments that has new line your code should look for \r\n and interpret it.. and also when you insert the data in mysql you will have to escape ' and \ characters from the comment.

How do I maintain user-formatting of text entered in an HTML form and stored in a MYSQL database?

I have a website in which a user enters text into an html form. The nature of the content is such that it is likely the user will want to write multiple paragraphs. As it stands now, the form sends the text via POST to a PHP file which inserts the text into a database. On another page, the text is pulled from the database and displayed. When it is displayed, all user formatting is gone. Multiple spaces and line breaks are deleted. How can I save the formatting of the user? Instructing him to use HTML tags to format is not feasible for a couple of reasons. I have also considered the
<pre>
tag, but that creates layout-breaking long lines of text and changes the font.
Any help is very much appreciated.
I'm assuming you're dealing with just a bunch of plain text entered into a textarea, not some fancy HTML editor as the other answerer assumed.
The reason your line breaks are lost is that HTML doesn't treat line breaks as line breaks. Line breaks are treated as just another space. Only <br> is treated as a line break. (Or <br /> in XHTML) If this is what's happening, you can use the nl2br() function to convert all line breaks into <br>.
Multiple spaces are more difficult. HTML doesn't distinguish between one space and many spaces. Spaces, tabs, line breaks, or any combination thereof, it doesn't matter, it's all treated as a single space. One way to prevent this is to wrap the whole thing in a <pre> or <code> block. But this is ugly unless you're trying to display computer code.
Or if you really desparately need those extra spaces, you could replace all spaces with which forces web browsers to display an extra space. (See edit below.)
Edit: Definitive version which preserves both line breaks and multiple spaces, and also prevents XSS:
<?php echo nl2br(str_replace(' ', ' ', htmlspecialchars($text))); ?>
You could use a rich text editor (TinyMCE, CKEditor) on the initial form which will allow the user to create markup without needing to know how to write HTML.
You then save the submitted markup into your DB (optionally filtering it for unwanted markup / scripting).
When displaying, don't use htmlspecialchars / htmlentities as you will want the content to be interpreted as HTML.

Categories