prevent "&" to &. encoding when save to database - php

I use sql server 2008 and I have PDO connection
$con = new \PDO("sqlsrv:Server={$config['server']};Database={$config['database']}", $config['username'], $config['password']);
$con->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$con->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC);
What I want is, I need to save directory name containing "&" sign without converting to &
eg - directory name - "New & old"
when I save in database it converted to the "New & old". I want to stop this conversion. I what to save it as "New & old"
Here is the data saving code -
$stmt = $this->db->prepare( "SET NOCOUNT ON DECLARE #return_value int
EXEC #return_value = [dbo].[sp_update_t_Rfile2_RF2_Path]
#RF2_RfileID_pk_ind = ?, #RF2_Path = ?
SELECT 'Return Value' = #return_value
");
$return = null;
$stmt->bindParam(1,$fields['RF2_nd'],\PDO::PARAM_STR );
$stmt->bindParam(2,$fields['Path_New'],\PDO::PARAM_STR);
$stmt->execute();
I call to this code using POST request not any Ajax. When I print this $fields['Path_New'] before this code it return "New & old" correctly not happen any encoding at POST.
Database column data type is varchar(265) and I use IIS server for PHP 5.3
I have two systems working on same database one is Access system and other one is PHP web application. Access system not working with &
please help me to stop this encoding "&" to &
Thanks

Finally I found the solution for this, to stop saving & as a & we need to decode the html encoding (UTF-8).
(PHP 4 >= 4.3.0, PHP 5)
html_entity_decode — Convert all HTML entities to their applicable characters
more information - http://php.net/manual/en/function.html-entity-decode.php
Now I can save & without converting to &
My updated code is - #RK_Path = N'".\html_entity_decode($fields['txtRK_Path'])."',
Thanks.

You should use UTF-8 in all pages, php files, and collation database.
Also check this:
https://stackoverflow.com/a/11249695/1919749

Change the collation to UTF-8 in your MYSQL database as well as the encoding in your php script

Related

mysql & UTF8 Issue with arabic

this might look like a similar issues for utf8 and Arabic language with MySQL database but i searched for result and found none..
my database endocing is set to utf8_general_ci ,
i had my php paging to be encoded as ansi by default
the arabic language in database shows as : ãÌÑÈ
but i changed it to utf8 ,
if i add new input to database , the arabic language in database shows as : زين
i dont care how it show indatabase as long as it shows normally in php page ,
after changing the php page to utf8 , when adding input than retriving it , if show result as it should .
but the old data which was added before converting the page encoding to uft8 show like this : �����
i tried a lot of methods for fixis this like using iconv in ssh and php , utf8_decode() utf8_encode() .. and more but none worked .
so i was hoping that you have a solution for me here ?
update :: Main goal was solved by retrieving data from php page in old encoding ' windows-1256' than update it from ssh .
but one issue left ::
i have some text that was inserted as 'windows-1256' and other that was inserted as 'utf-8' so now the windows encoding was converted to utf-8 and works fine , but the original utf-8 was converted as well to something unreadable , using iconv in php, with old page encoding ..
so is there a way to check what encoding is original in order to convert or not ?
Try run query set name utf8 after create a DB connection, before run any other query.
Such as :
$dbh = new PDO('mysql:dbname='.DB_NAME.';host='.DB_HOST, DB_USER, DB_PASSWORD);
$dbh->exec('set names utf8');

XOR encode a multibyte string and save to MySQL field without loss

I'm currently using this function to obfuscate a bit the field values in MySQL and protect it from direct dumping. It all works good and values are stored correctly, but what happens when i try to store a multibyte string?
Here's an example, let's try to encode the string álex:
<?
$v = xorencode('álex');
// step 1 - encode
echo $v."\n";
// step 2 - decode
echo xorencode($v);
?>
Works good, i see some obfuscated string first time, and then i see álex again. Now if i try to save it in a VARCHAR field in a MySQL table, and then select it - i no longer have a utf string, instead it gets returned as gllex.
Note, MySQL tables and fields collations are utf8_general_ci, files are UTF-8, and i SET NAMES utf8 after connecting. Any workaround to this?
Thanks

Store BLOB-like data in PostgreSQL

I recently switched from MySQL to PostgreSQL. I have one problem left however.
Previously, I would store small images in the BLOB format in MySQL.
PostgreSQL doesn't know such thing as a BLOB.
I tried using BYTEA field type instead. This actually inserts an large (hexadecimal?) string I guess, but now I'm stuck trying to get this string back to displaying an actual image in PHP..
Any ideas? Thanks in advance.
Here is a piece of code I use to save the image in the database:
$data = bin2hex(file_get_contents('php://input'));
if (!empty($data)) {
$sql = "UPDATE asset SET data = X'%s' WHERE uuid = '%s'";
$args = array($data, $asset_uuid);
}
psql (9.1.3) and php 5.3.6 are used
Bytea is a byte array. It's not a bit pattern. See section 4.2.1.5 of PostgreSQL Lexical Structure.
The correct way to enter bytea is '\x...' with hex values. So what you want is SET data = '\x%s'.
You might also want to look into prepared statements with pg_prepare.
Edit: I was able to insert a (text) file into a bytea with this:
$source = file_get_contents( 'hello.php' );
$insert = pg_prepare( $conn, '', 'insert into t (name, data) values($1,$2)' );
pg_execute( $conn, '', array( 'hello.php', $source ) );
3rd Edit: This works fine to insert the file into the database. However, the pgsql driver in PHP is quite impolite. The only way to retrieve the actual data back is using the old bytea escape mechanism, as detailed here: pg_unescape_bytea.
pg_query('SET bytea_output = "escape";');
$result = pg_query( 'select data from t' );
while ( $row = pg_fetch_row( $result ) ) {
echo pg_unescape_bytea( $row[0] );
}
I'm sorry about how annoying this is. The PostgreSQL interface in PHP can do with some major overhaul for binary values.
To insert bytea contents with the pg_* API, the binary value should always be run through the pg_escape_bytea() function, even if it's passed to the pg_execute or pg_query_params functions.
This is because the pg_* layer doesn't "know" that a particular parameter has binary contents, and it does not implement any real support for parameter types anyway. So the text representation must be used. It can either be in the escape form or the hex form, it doesn't matter to the PG server, and it's independant of the value of bytea_output, which is meaningful only for values read from the server.
Example:
$esc=pg_escape_bytea("\000\001\002");
pg_query_params('INSERT INTO some_table(some_col) VALUES($1)', array($esc));
To read bytea contents with the pg_* API, the value must be run through pg_unescape_bytea() after the fetch. Assuming the client library is not older than 9.0 (libq.so.5.3 or higher), it can decode the contents whether it's in hex form or escape form and it will autodetect it. Only with an older library would it be necessary to force bytea_output to escape for it to decode properly, either dynamically with SET or statically for the whole database (ALTER DATABASE SET bytea_output=escape) or in postgresql.conf for the whole instance.
Example:
$p=pg_query("SELECT some_col FROM some_table WHERE...");
$r=pg_fetch_array($p);
$contents = pg_unescape_bytea($r[0]);
Both answers posted here gave me some thoughts, but none were 100% of the answer.
So, I will explain in this answer what I did to get it to work.
When displaying the image, I used this:
header('Content-Type: image/jpeg');
$data = pack("H*", pg_unescape_bytea($data));
echo $data;
I'm running PHP 5.3.8, in PHP 5.4.0 it turns out you can use hex2bin instead of pack.
When adding the image to the database, I used this:
$data = pg_escape_bytea($data); // Escape input for PostgreSQL
$sql = "UPDATE asset SET data = '%s'WHERE uuid = '%s'";
I'm glad it is working now. Thank you both Daniel and Johann!

Special characters to mysql from php

I know there have been a lot of almost the same questions, but I still didn't find the answer to my problem.
I want to place "les Îles Açores" into the db. But I get:
les Îles Açores
I tried usin:
SET Names 'ut8)
$mysqli->set_charset("utf8");
mysql_real_escape_string()
htmlentities (Here I got htmlentities, but I want to know if there's another way)
Code:
$name_fr = $_POST["name_fr"]; $name_nl = $_POST["name_nl"];
$arr_kollommen = array("NAME_FR","NAME_NL");
$arr_waardes = array($naam_nl,$naam_fr);
$obj_db->insert("landen",$arr_kollommen,$arr_waardes);
Does someone has an idea how to solve my litle problem?
Thank you very much!
Make sure the table uses the correct CHARSET, for example:
CREATE TABLE myTable (
one VARCHAR(255),
two VARCHAR(255)
) DEFAULT CHARSET=utf8;
Make sure you actually write in UTF8 (meaning your IDE / editor you write your code must have encoding set to UTF8).
Is the record corrupted both in the DB and on your page after you fetch it or only in DB?
$name_fr = $_POST["name_fr"];
$name_nl = $_POST["name_nl"];
$arr_kollommen = array("NAME_FR","NAME_NL");
$arr_waardes = array($naam_nl,$naam_fr);
$obj_db->insert("landen",$arr_kollommen,$arr_waardes);
Try using instead of encode to utf_8 decode.
like this:
$name_fr = $_POST["name_fr"];
$name_nl = $_POST["name_nl"];
$naam_fr = utf8_decode($naam_fr);
$naam_nl = utf8_decode($naam_nl);
$arr_kollommen = array("NAME_FR","NAME_NL");
$arr_waardes = array($naam_nl,$naam_fr);
$obj_db->insert("landen",$arr_kollommen,$arr_waardes);
2 possible reasons i can see:
1) Your database doesn't feature UTF-8 fields
2) When you read your data from the server, you are not setting the connection as utf-8. If you have to set it utf-8 when writting you also have to set it utf-8 when reading.
Check using PHPMyAdmin if the data is wrecked... If it is, then it means that your SET names'utf-8' is not working...
Do you pass the "UTF-8" parameter into your htmlentities, and html_entity_decode this way ?
html_entity_decode($text,ENT_QUOTES , "UTF-8");

mysql getting urlencoded data into database

he i have a problem
i have a mysql database dump, but all the data is url encoded has + instead of spaces and other characters as %20 etc
i tried to import this directly and wrote a php script to decode the data and rewrite it back to the db,
/// make rs..........
........
do {
// decode the items in the countries table
$myCountryID = $row_countries['id_con'];
$new_country_con = urldecode($row_countries['country_con']);
$result = mysql_query("UPDATE countries_con SET country_con = '".$new_country_con."'
WHERE id_con = ".$myCountryID."")or die(mysql_error()) ;
echo("id_win: ".$myCountryID."<br>added country_con: ".$new_country_con."<br>");
} while ($row_countries = mysql_fetch_assoc($countries));
echo('----------------------------------END Countries-------------------------------------<br><br>');
the page is set to use utf8 all the tables in the db are set to use utf8
the echo statement outputs the correct characters, but it still gets stored in the db as a urlencoded string, how do i get it into the db as utf8 without the url encoded characters?????
Try to printout your query to see at which point it produces %20 (before query execution or after).
Also please see: http://recursive-design.com/blog/2008/06/23/force-mysql-encoding-to-utf8/

Categories