I have the following html code:
<div class=" modal" id="indexModal">
<span class="thing"></span>
închide
<h2 class="title">Promoţia lunii februarie!</h2>
<div>
<h3>Beneficiaţi de promoţia sezonului.</h3>
<p>În luna Februarie, vă oferă posibilitatea de a achiziţioana, solarii profesionale şi hobby, sisteme de irigatii, folie şi accesorii cu o reducere de 10% aplicată la preţul de producator.</p>
vedeţi oferta specială!
</div>
</div>
and I want to insert it into database but it doesn't saves the full content. I tried using htmlentities() on insert, and html_entity_decode() when I want to display the html. But all I get is this:
<div class=" modal" id="indexModal">
<span class="thing"></span>
închide
<
Can you explain me, how to safely insert some html in database without problems and how to display that html afterwards on a page? My table is utf8_general_ci charset.
The short answer is 'don't put HTML into a database'.
There are a lot of very good reasons for this. Some are:
Reusing the data in another non-HTML context is not possible
Extracting the data with other data joined to it is not possible
You end up with encoding problems like you are having now
If you wish to change the way your site is laid out, you have to update every database field, rather than just one HTML template.
Use PHP to extract and store just text, or just numbers and store them in a proper set of relational tables. If you are not sure how, take the time to learn, otherwise you will find many more headaches further down the line when you inevitably want to expand the site to other things you haven't thought of yet, or change the way it works.
You need to change your database structure to accept more characters. Example: Set your column type to varchar 250 (or however many characters you need) *it does have a maximum number of characters though.
Im not sure what you mean by insert safely, if you mean that you get funny characters with the charset then try the following two steps
1)
First you need to check what charset your mysql is setup as. Different setups default to different ones. I generally go for utf8. it should be fairly straight forward to change and setup. From mysql administrator or some other tool. see following
http://dev.mysql.com/doc/refman/5.0/en/charset-connection.html
2)
Then your html document headers if youadd the following meta tag
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
this should link the two charsets up and remove funny characters
Just use PDO prepare statement and it will allow any kind of text to be added on the database. It will actually consider all the variables as text, so it will add in the way you are looking for
Like this:
$host = 'localhost';
$user = 'root';
$password = '';
$dbname = 'myDatabase';
$dsn = 'mysql:host='.$host.';dbname='.$dbname.';charset=utf8mb4';
$conn = new PDO($dsn, $user, $password);
$conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$query = "INSERT INTO yourTable(someColumn, messageHTML) VALUES (?, ?)";
$stmt = $conn->prepare($query);//This is the line that will consider all as text
$stmt->execute([$something, $html]);
Related
so here's what I want to do, I want to be able to cache a whole web page, which would be something like this
$domain = "cnn.com";
$title = "CNN";
$cacheado = file_get_contents('http://www.google.com');
$ingresar = "INSERT INTO indexed_links (link, title, cacheado) VALUES ('$domain', '$title', '$cacheado')";
$db_on = mysqli_connect('localhost', 'root', 'pass', 'data_base');
mysqli_query($db_on, $ingresar);
My great concern is, I tried to do this exact code with the page example.com, which would be $cacheado = file_get_contents('http://example.com');
Which worked completely fine, it added the whole HTML code to the page, which is something somewhat short, it's an easy HTML code, now, Google and a bunch of other sites got more codes into their HTML, as a result, sites with longer HTML codes are not going through the mysqli_query query, which I suppose it has to do with MySql and not PHP because the code works just fine with example.com...
The column of the table which I want to insert the HTML code is cacheado, which has a type set in the MySQL database of text, does this have something to do?
The problem is not with the datatype. Instead, you failed to escape the strings before building the INSERT statement.
In particular, there was probably an apostrophe (') in that web page.
Change field type from TEXT() to VARCHAR(65535). It is the max lenght I now you can set for a field.
I have a mySQL database with the following
e.g.
Microeconomics.
The ‘theory of the ï¬rm’
or:
Resource allocation modiï¬cations.
For some reason, the text that has been input (through CKEditor), has been changed so any instances of fi are in the database as 'ï¬'. I believe this is something to do with HTML entities. The text (I believe) was copy-pasted from a word document, which could be part of the problem.
How do I change (in PHP or mySQL) all instances of 'ï¬' into fi? When rendered as a PDF by TCPDF, it shows a ? (e.g. financial = ?nancial, significant = signi?cant)
Thanks in advance.
This statement will correct all the false instances for the column that contains the 'ï¬'
Update table Set
column = replace(column, 'ï¬', 'fi')
I'm having trouble with the ampersand symbol, because I've to allow user to insert page_title within database.
The problem is that in my mother language many companies have the symbol in their names like per example "Santos & Filhos".
The question is, how can I insert this, without break my database and without opening security issues?
using this the database gets broken
$title = preg_replace('/&/', '&', $title);
$final_title = utf8_encode($title);
I'm using utf8_encode because of the other accents like á or ã
Thanks, hope you can help me here
EDIT
ok, first thanks to all, most of you were wright, mysql_real_escape_string is indeed one of the best options, if not the best.
I discovered that I was missing one escape (in query) before post my variables to be processed by php and inserted within the database.
So I manage to get my & but now I can't manage to have accents...
So far my php code looks like this
$title = mysql_real_escape_string($_POST['title']);
$sql = "UPDATE bodytable SET body_title = '".utf8_encode($title)."'";
and then in my frontage I've
utf8_decode($row['body_title']);
the result is
<title>Santos & Filhos - Repara?es de autom?veis</title>
Escape characters going into the database with something like mysql_real_escape_string() or PDO and use htmlentities() when displaying it.
This covers securing user input: What's the best method for sanitizing user input with PHP?
Try using an escape character in front of all your special characters you want to insert in the database. Encoding is ok but for example, if the following string was to be added to mysql string field you would get an error.
"special characters don't work"
And you can do this to prevent these errors
"special characters don\'t work"
I belive there is a methods called addslashes(string x) and stripslashes(string x) that will do that for you.
$title_to_insert_in_database = $str = addslashes($title);
$title_for_page = htmlspecialchars($title_from_database);
I've done this before in .Net but I am somewhat new to PHP and could use some help. I'm trying to pull data in PHP from a MSSQL db, some of which is Greek letters. The data type of the MSSQL columns is nvarchar and the Greek characters are displayed correctly in management studio; however, whenever I pull the data with the sqlsrv_query function in php I get a bunch of question marks.
In sqlsrv_connect function I've tried setting CharacterSet"=>"UTF-8 which doesn't work.
I've tried iconv(), but am not sure which sets to use.
I tried mb_detect_encoding() and it returned ASCIIASCII.
Here is some sample code:
public function _getOrderItemDetails($orderItemIds,$productTypeId){
$params = explode(',', $orderItemIds);
$sql = "select od.*, ofs.Sort
from orderDetail od
left join orderFieldSort ofs on ofs.fieldName = od.name and productTypeId in ($productTypeId)
where orderItemid in (".rtrim(str_repeat('?,', count($params)),',').")
order by ofs.sort";
return $this->_compileResults($sql,'OrderDetail',$params);;
}
private function _compileResults($sql,$classType,$params ){
$result = sqlsrv_query($this->conn,$sql,$params);
$arrayResult = array();
while($orderObject = sqlsrv_fetch_object($result,$classType)){
array_push($arrayResult, $orderObject);
}
return $arrayResult;
}
Any suggestions are welcome. Please help!
A couple of things to maybe try.
1) Can you validate exactly what character encoding your DB is in? I recommend UTF8 for everything as it should handle the widest range of characters. "ASCIIASCII" is not a character encoding to my knowledge do you mean "ASCII"?
2)Try using mysql_set_charset('utf8'); changing the char set to match your db encoding. It "Sets the default character set for the current connection." from within the current php script. PHP official docs
3)This is an outlier but where are you viewing the results? Irrelevant of the data returned from your DB the if you are viewing the results in a web browser you will need to make sure the page has the appropriate charter encoding set in the head if this is a miss match from the character set returned from your db it can result in the question marks or diamonds... Typically something like this
<head>
<title>page title</title>
<meta charset="UTF-8" />
</head>
I had exactly the same problem with you so when i was searching to find the solution i saw your question.The answer is very simple.I guess somewhere in your code you connect to the database with code like the following :
$serverName = "YOUR_SERVER";
$connectionInfo = array("Database"=>"YourDatabase");
$link = sqlsrv_connect($serverName,$connectionInfo);
if(!$link ) {
die('Could not connect: ' . mysql_error());
}
To make greek characters show up you need to change line 2, from:
$connectionInfo = array("Database"=>"YourDatabase");
to :
$connectionInfo = array("Database"=>"YourDatabase","CharacterSet"=>"UTF-8");
and the rest code stays the same.
This solution was suggested by #Graham to his own question i think, and it is from here : Greek character insertion in php compared to SQL server management studio
Relevent code:
$status = $db->run(
"INSERT INTO user_wall (accountID, fromID, text, datetime) VALUES (:toID, :fromID, :text, '" . time() . "')",
array(":toID" => $toID, ":fromID" => %accountID, ":text" => $text)
);
I am taking input text from javascript, throwing it in an AJAX call to handle it, which calls a function which includes these lines of code.
The text string in question is: "Türkçe Türkçe Türkçe!"
Upon investigating the database, the following value is saved "Türkçe Türkçe Türkçe!", which is double utf8_encode'd.
When viewing the text by SELECTing it from the database, I get "Türkçe Türkçe Türkçe!", which is how they should be saved in the database in the first place.
As far as I know, I am not encoding the data as it is being prepared by PDO...
Encoding is a b*tch. You need to make sure it is as you expect it to be in several places:
The HTML page with the Javascript. Set it to utf-8 with a meta tag like:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
The connection to your database. Execute the query set names 'utf8' after connecting to the database (and before any other queries).
Your database field. In MySQL it's called a collation set it to utf8_general_ci (ci stands for case-insensitive).
If you have these 3 your data should always be, and stay, utf-8 (unless you're doing encoding yourself).
For good measure, make sure your source code files are utf-8 as well. Windows typically defaults to iso.