I have a php page that uses mysql_real_escape_string() to escape content that contains single quotes. I believe it is using utf-8 (but I am not sure). When I insert some content, I get the following mysql warning (and it adds a ? instead of ' in the content):
Incorrect string value: '\x92t ...
Here is an example of my php:
$link = ConnectToServer($theIntranet, $theUser, $thePW);
$theTagToFind = 'ac';
$theTagToUse = 'trc';
$database = '{databaseName}';
$theQuery = "SELECT * FROM {$database}.templates
WHERE content like '%{" . $theTagToFind . ":%'";
$updates = fopen('001_intranet_change' . strtoupper($theTagToFind) . 'to' . strtoupper($theTagToUse) . '.sql', 'w+');
$rollback = fopen('001_intranet_change' . strtoupper($theTagToUse) . 'backto' . strtoupper($theTagToFind) . '.sql', 'w+');
$theResultHandle = mysql_query($theQuery, $link);
$comment = "--Update All $theTagToFind tags to $theTagToUse tags in $database --";
fwrite($updates, $comment . "\r\n\r\n");
fwrite($rollback, "--Rollback - Convert all $theTagToUse tags back to $theTagToFind tags --\r\n\r\n");
mysql_set_charset('latin1');
while (($data = mysql_fetch_assoc($theResultHandle)) != false)
{
$rb_content = $data['content'];
$data['content'] = preg_replace("/{" . $theTagToFind . ":/", "{" . $theTagToUse . ":", $data['content']);
$theResult[] = $data;
$update_script = "\r\n
Update $database.templates
SET content = '" . mysql_real_escape_string($data['content']) . "'
WHERE _id = " .$data['_id'] . ";";
$rollback_script = "\r\n
UPDATE $database.templates
SET content = '" . mysql_real_escape_string($rb_content) . "'
WHERE _id = " . $data['_id'] . ";";;
fwrite($updates, $update_script);
fwrite($rollback, $rollback_script);
}
fclose ($updates);
fclose($rollback);
print_r($theResult);
and $data['content'] could equal something like:
"Hello,
Please remember to contact the doctor's office at......"
here you go
mysql_set_charset('utf8');
you have to be sure that charset in your table definition also set to utf8
Are you sure your server is configured correctly and magic quotes are turned off? These can have the effect of double escaping values.
You can test this by looking at the $_POST data to see if it's been modified from what you'd expect. If so, see if you can fix the setting in php.ini.
As a note, you should not be using mysql_query in new code. It's dangerous, deprecated, and will be removed in future versions of PHP. Using SQL placeholders is the safest and easiest way to do escaping.
In your short example here it looks like you've forgotten to escape $data['_id'] which means it's a possible SQL injection bug. Even one mistake can have severe consequences, so never, ever put unescaped data into a query string.
Related
I'm using this question as a reference. My issue is that it's encoding my string to hex, but not decoding it once it's written to the database.
HTML textarea
<textarea class="form-control" rows="5" name="nomInfo[]" id="appNom" placeholder="Additional Information"></textarea>
Getting POST value and inserting into the DB
function mssql_escape($data) {
if(is_numeric($data))
return $data;
$unpacked = unpack('H*hex', $data);
return '0x' . $unpacked['hex'];
}
$nomInfo = $_POST['nomInfo'][0];
$nomInfoDecode = mssql_escape($nomInfo);
$query = "INSERT INTO dbo.emp_recog (nomInfo) VALUES (";
$query .= "'" . $nomInfoDecode . "');";
So for example, if I types in ggfdgdfg/fdg.fdgdf.gdf "fdskfdskfds;fsd ' sdfds' fds/f% into the textarea and submit the form, this is written to the database 0x67676664676466672f6664672e66646764662e676466205c226664736b6664736b6664733b667364205c272073646664735c27206664732f6625
Scrap all the hex stuff, there is no need. Really the only thing to worry about escaping is a quote '. MySQL uses a slash \ as an escape character. MS SQL uses a quote ' to escape a quote ', so you just double-up the quotes:
return str_replace("'", "''", $data );
However, you really should be using PHP Data Objects that supports MS SQL, then there is PDO::quote.
I'm pretty sure the example is not quoting the value to be inserted:
mssql_query('
INSERT INTO sometable (somecolumn)
VALUES (' . mssql_escape($somevalue) . ')
');
which translated to your query using double quotes would be:
$query = "INSERT INTO dbo.emp_recog (nomInfo) VALUES (";
$query .= $nomInfoDecode . ");";
Can you give that a shot?
I have a problem. I can't save my array data to database, i don't know why.
I try some version:
ver1:
$data=$_SESSION['need_save_data'];
$sql = "INSERT INTO session_search_data (`user_id`,`data`,`date`) VALUES ('" . $_SESSION['web_page_user_data']['id'] . "'," . $db_handler->db->quote(json_encode($data)) . ",'" . time() . "')";
$db_handler->db->query($sql);
and it save the database: []
if i echo my query, and run it in mysql console, it working fine:
INSERT INTO session_search_data (`user_id`,`data`,`date`) VALUES ('8','{\"selected_manufacturer_id\":\"504\"}','1442571431')
I try save the database json_encode, the result is similar, it save empty variable.
Also i try to save to file:
$data=$_SESSION['need_save_data'];
$filename = 'session_data/' . $_SESSION['web_page_user_data']['id'] . '.php';
$file = fopen($filename, "w");
fwrite($file, serialize($data));
I try save with json_encode, var_export, serialize, the result is: save empty variable data.
I use PHP 5.4 last version, i think it is configuration problem, because my code works fine two other servers, and my localhost.
Even if you are calling $db_handler->db->quote method, it will add quotes to the json encoded data only. You must wrap the data with quotes as well:
$sql = "INSERT INTO session_search_data (`user_id`,`data`,`date`)
VALUES ('" . $_SESSION['web_page_user_data']['id'] . "','" . $db_handler->db->quote(json_encode($data)) . "','" . time() . "')";
If this is not the problem then please verify that you are starting the session before trying to access session variables:
<?php
session_start();
Also, make sure you actually have some data inside the $_SESSION['need_save_data'] variable
make sure you're running in error_reporting(E_ALL), and make sure that query is successfully executed (if its PDO, make PDO run in PDO::ERRMODE->PDO::ERRMODE_EXCEPTION ), and make sure your fwrite succeeed, like
if(strlen(serialize($data))!==fwrite($file, serialize($data) || !fflush($file)){
throw new Exception("failed to write data to disk!");
}
then im sure the problem will become obvious... maybe you have a full harddrive? :p
so why you are trying to insert json into database when you can use explode? use prepared statements to avoid sql injection:
$uid = 8;
$data = $_SESSION['need_save_data']; // content: selected_manufacturer_id:504
$date = time();
$sql = "INSERT INTO `session_search_data` SET `user_id`=?, `data`=?, `date`=?";
if ($query = $dbcon->prepare($sql)) {
$query->bind_param('isi', $uid, $data, $date);
$query->execute();
$query->close();
}
so to retrieve the data from database and transform to json you can do:
$contents = explode(':', $data);
$transform = array();
$transform[$contents[0]] = $contents[1];
$to_json = json_encode($transform); // {"selected_manufacturer_id":"504"}
I work to execute this sql
$tarifekatalogcwsql=oci_parse($conn,'select TARIFE_ID, HIZMET_TURU, ALT_HIZMET_TURU, KAYIT_TARIHI, OM_TARIFE_ID from SMARTTBILL.TARIFE_KATALOG_CW
WHERE HIZMET_TURU='.$rowisemriabonecw[0].' AND ALT_HIZMET_TURU='.$rowisemriabonecw[1].' AND OM_TARIFE_ID='.$rowisemriabonecw[4].'');
You can just consider sql statement. When I execute this query, it returns error which I wrote in the header.
In my db tables, I have some values that includes '|' character and because of this, system gave me such an error.
OM_TARIFE_ID='.$rowisemriabonecw[4].' this is the source of the problem.
OM_TARIFE_ID='1|1'
$rowisemriabonecw[4]='1|1'
both are same but the system considers the '|' character as concatenation string.
Can you help for that case? How can I deal with the problem?
Try this:
$tarifekatalogcwsql=oci_parse(
$conn,
'select TARIFE_ID, HIZMET_TURU, ALT_HIZMET_TURU, KAYIT_TARIHI, OM_TARIFE_ID from SMARTTBILL.TARIFE_KATALOG_CW WHERE '
.'HIZMET_TURU = "' . $rowisemriabonecw[0] . '" AND '
.'ALT_HIZMET_TURU = "' . $rowisemriabonecw[1] . '" AND '
.'OM_TARIFE_ID = "' . $rowisemriabonecw[4] . '"'
);
But Your approach is the simplest way to make SQL Injection!
This is correct approach:
$tarifekatalogcwsql=oci_parse(
$conn,
'SELECT TARIFE_ID, HIZMET_TURU, ALT_HIZMET_TURU, KAYIT_TARIHI, OM_TARIFE_ID '
.' FROM SMARTTBILL.TARIFE_KATALOG_CW '
.'WHERE HIZMET_TURU = :HIZMET_TURU '
.' AND ALT_HIZMET_TURU = :ALT_HIZMET_TURU '
.' AND OM_TARIFE_ID = :OM_TARIFE_ID'
);
oci_bind_by_name($tarifekatalogcwsql, ":HIZMET_TURU", $rowisemriabonecw[0]);
oci_bind_by_name($tarifekatalogcwsql, ":ALT_HIZMET_TURU", $rowisemriabonecw[1]);
oci_bind_by_name($tarifekatalogcwsql, ":OM_TARIFE_ID", $rowisemriabonecw[4]);
Documentation: oci-bind-by-name
I generally understand the idea behind escaping quotes using backslashes and alternatively using backslashes to escape so that you can have backslashes in your strings and so forth, but I've run in to a problem trying to pass a query through odbc_exec() and using a table-valued function and I just cannot seem to get it to stop giving me
SQL error: [Microsoft][ODBC SQL Server Driver][SQL Server]Unclosed quotation mark after the character string '0000005'.
This is what it looks like when I hard code the variables:
$query = 'SELECT '.$csvCriteria.", googStep, Segment, PrevailingDirection FROM jSelectorCSVCreator('1','1','northbound','0006009','00000050370A2P000004','00060041270B2P000070','1')";
This works fine. Note that $csvCriteria hasn't given me any problems. This is what I want it to look like:
$query = 'SELECT '.$csvCriteria.", googStep, Segment, PrevailingDirection FROM jSelectorCSVCreator('".$stepNum."', '".$segMarker."', '".$prevDirection."', '".$rdNoA."', '".$re_1."', '".$re_2."', '".$directionA."')";
However I keep getting errors around $re_1 and $re_2 (the error I've put in at the top of this).
I've tried multiple variations of what I think may work, such as:
$query = 'SELECT '.$csvCriteria.", googStep, Segment, PrevailingDirection FROM jSelectorCSVCreator('".$stepNum."','".$segMarker."','".$prevDirection."','".$rdNoA.'\',\''.$re_1.'\',\'00060091100B1P000030\',\'1\')';
But I am neither expertly proficient at this, nor do I know if I'm missing something blatantly obvious. Just absolutely stuck and need a hand!
I can not reproduce your error:
The SQL in question is:
SELECT csvcriteria,
googstep,
segment,
prevailingdirection
FROM jselectorcsvcreator('1', '1', 'northbound', '0006009',
'00000050370A2P000004', '00060041270B2P000070', '1');
Placing the data in variables such as:
$csvCriteria = 'csvCriteria';
$stepNum = 1;
$segMarker = 1;
$prevDirection = 'northbound';
$rdNoA = '0006009';
$re_1 = '00000050370A2P000004';
$re_2 = '00060041270B2P000070';
$directionA = 1;
Using the first line of code, which works and using the one that doesn't work both return the exact same thing:
$correct = 'SELECT ' . $csvCriteria . ", googStep, Segment, PrevailingDirection FROM jSelectorCSVCreator('1','1','northbound','0006009','00000050370A2P000004','00060041270B2P000070','1')";
$query = 'SELECT ' . $csvCriteria . ", googStep, Segment, PrevailingDirection FROM jSelectorCSVCreator('" . $stepNum . "','" . $segMarker . "','" . $prevDirection . "','" . $rdNoA . "','" . $re_1 . "','" . $re_2 . "','" . $directionA . "')";
echo $correct . "\n";
echo $query . "\n";
var_dump($correct === $query);
The response is (CodePad):
SELECT csvCriteria, googStep, Segment, PrevailingDirection FROM jSelectorCSVCreator('1','1','northbound','0006009','00000050370A2P000004','00060041270B2P000070','1')
SELECT csvCriteria, googStep, Segment, PrevailingDirection FROM jSelectorCSVCreator('1','1','northbound','0006009','00000050370A2P000004','00060041270B2P000070','1')
bool(true)
My guess is that $csvCriteria or any of the variables at hand have errors.
I would highly recommend looking at the echoed query of $query in an SQL Formatter (Select MS ACCESS)
$query = 'SELECT '.$csvCriteria.", .....
should be
$query = 'SELECT '.$csvCriteria.', ......
Try using
$query = "SELECT $csvCriteria, googStep, Segment, PrevailingDirection FROM jSelectorCSVCreator('$stepNum','$segMarker','$prevDirection','$rdNoA','$re_1','00060091100B1P000030','1')";
This is much simpler without need of all the escapes.
As it turns out I was attempting to pass a string that looked like this "0000000\000X00X0\0000000" and it wasn't working so well. I decided to use stripslashes() so I could pass the variable more easily and work with it once it was in SQL. Turns out stripslashes() doesn't work like that. I used str_replace() instead and it now works fine.
I need to search a string in mysql with php. I get an error related to the spaces in the string. I an not fimilar with regex, I am not sure it that is my only choice.
example:
$ex="This and That";
$sql = 'SELECT
some_ID
FROM ' . atable. ' WHERE ' . strings. ' LIKE ' . $ex. ' AND visable=' . '1';
after executing I get an error like:
"near 'That AND visable=1' at line x"
so its probably not picking up the first two words, any suggestions?
Thanks in advance.
You are missing quotes around the string. They need to be encapsulated entirely for the query to execute properly.
Change this:
LIKE ' . $ex. ' AND
To this:
LIKE "' . $ex. '" AND
On a side note, make sure you are protecting your self against SQL injections AND make sure your query is properly escaped.