How to insert string with single quote in Mysql & Oracle database? - php

I am facing issue in inserting single quoted value (say Product Name: xyz80'). So how can I insert such data into mysql & oracle database. With double quote, it's working fine. eg: xyz90"
My script:
$query2 = "SELECT sfoi.name, sfoi.sku, sfoi.qty_ordered
FROM sales_flat_order sfo
JOIN sales_flat_order_item sfoi
ON sfoi.order_id = sfo.entity_id
WHERE sfo.increment_id = 100000473";
$result_query2 = mysql_query($query2);
while($row = mysql_fetch_array($result_query2))
{
$row["name"] = mysql_real_escape_string($row["name"]);
// $row["name"] = html_entity_decode($row["name"]);
$result_str_product .= "('". $row["name"] . "',". "'" . $row["sku"] . "'," . "'" . $row["qty_ordered"]),";
}
I tried using both mysql_real_escape_string() and html_entity_decode(), still getting error.
Here $row[name] is fetching value which is like xyz80', pqr75' etc. As I am inserting these values through PHP, unable to get where exactly error is occurring.
I am facing similar problem with Oracle db also. In Oracle , I tried this: "'". $row["name"] . "''," using '' at the end.
HOW TO insert special characters in Oracle dataabse?

prepare the data by replacing one ' with two '', before composing the query:
while($row = mysql_fetch_array($result_query2)) {
$n = mysql_real_escape_string($row["name"]);
$s = mysql_real_escape_string($row["sku"]);
$q = mysql_real_escape_string($row["sku"]);
// $n = html_entity_decode($row["qty_ordered"]);
$result_str_product .= "('$n','$s','$q'),";
}
// remember_to_remove_final_stray_comma($result_str_product);
print( $result_str_product ); // just to see what's been made

For Oracle, you could replace the single quotes with two single quotes when you query:
$query2 = "SELECT REPLACE(sfoi.name,'''','''''') name, sfoi.sku, sfoi.qty_ordered
FROM sales_flat_order sfo JOIN sales_flat_order_item sfoi
ON sfoi.order_id = sfo.entity_id
WHERE sfo.increment_id = 100000473";
Then the rest of your code should work as is.
In Oracle, two consecutive single quotes represent a single quote in a string literal.

Oracle now have the q function used to escape strings
http://docs.oracle.com/cd/B19306_01/appdev.102/b14251/adfns_sqltypes.htm#sthref373
select q'my 'quoted text' ' from dual
this solution is nice cause you don't have to have a bunch of nested quotes

Related

How to add quotes in mysql query in PHP 5.6

I have a variable $categoryName which has value ABC/ABC (for example). I nedd to add quotes around this text "ABC/ABC". This is my PHP code:
public function getCategoryID($categoryName)
{
$row = Db::getInstance()->getRow('
SELECT `id_category`
FROM ' . _DB_PREFIX_ . 'category_lang c
WHERE c.`name` = ' . $categoryName);
return isset($row['categoryName']);
}
And the error from mysql.
SELECT `id_category`
FROM ps_category_lang c
WHERE c.`name` = ABC/ABC LIMIT 1
How to solve this problem ? Thanks for help.
Just put the quotes in the string.
$row = Db::getInstance()->getRow('
SELECT `id_category`
FROM ' . _DB_PREFIX_ . 'category_lang c
WHERE c.`name` = "' . $categoryName . '"');
As mentioned in the comments, it would be better if you used prepared statements to protect against SQL injection. If you can't do that, you should make sure to escape $categoryName properly.
See How can I prevent SQL injection in PHP?

MySQL IN for strings

I have an array $friends and I used $friend_new = join(',',$friends ); to get name1,name2,name3.
But when I use this query I got error:
$query = mysqli_query($connect_db, "SELECT * FROM post WHERE name IN ($friend_new )");
Does anyone know where the problem is?
You should use implode("','", $friends) and IN ('$friends_new') as these are string values.
Your code is vulnerable to injection. You should use properly parameterized queries with PDO / mysqli
Your list has to look like:
... IN ('friend1','friend2','friend3')
If you have an array of friends such as:
$friends = array("friend1","friend2","friend3");
You can use implode to prepare for use with an IN:
$friend_new = "'" . implode("','", $friends) . "'";
Finally,
SELECT * FROM post WHERE name IN ($friend_new)
The way you do it the individual strings won't be quoted, and that causes the error. As join allows you to specify a "glue" longer than 1 character you can do as follows:
$query = mysqli_query($connect_db,
"SELECT * FROM post " .
"WHERE name IN ('".join("', '", $friends)."') ";
or
$friend_new = join("', '", $friends);
$query = mysqli_query($connect_db,
"SELECT * FROM post " .
"WHERE name IN ('$friend_new') ";
that is, have join write the intermediate ', ' , and surround with ''

Escaping % symbol in MySQL with PHP

i have a simple search box but I am trying to avoid the result page returning all results in table when the query is %. how can that be done?
I think you want to use \%...
In your PHP,
$query = str_replace ( '%' , '\%' , $query )
$sql = "SELECT * FROM table WHERE column LIKE '%" . mysqli_real_escape_string($query) . "%'"
Are you sanitizing your inputs?
You can start with mysqli_real_escape_string()
$query = "SELECT * FROM table WHERE column LIKE '" . mysqli_real_escape_string($input) . "'";

Trying to extract 5 characters from a column when adding record mysql via php

My part_no column has the following format: 000-00000-00 for all records.
I need to extract the five middle characters from part_no and place it in the core column when I create the record.
I can't get my script to work.
I'm not getting any errors. Just not working.
$order = "INSERT INTO cartons_added (add_time, type, part_no, add_type, add_qty, add_ref, add_by, add_notes)
VALUES
('$date',
'$_POST[type]',
'$_POST[part_no]',
'$_POST[add_type]',
'$_POST[add_qty]',
'$_POST[add_ref]',
'$_POST[add_by]',
'$_POST[add_notes]')";
$result = mysql_query($order);
$query2 = "select part_no from cartons_current";
$sel = mysql_query($query2);
$res = mysql_result($sel);
while($row = mysql_fetch_row($res)) {
$core_digits = split('-',$row[0]);
$core =$core_digits[1];
$query3 = "insert into cartons_current(core) values($core)";
$sel2 = mysql_query($query3);
}
You can update your cartons_current table based on your cartons_added table with something like:
INSERT INTO cartons_current(core)
SELECT SUBSTR(part_no, 5, 5) FROM cartons_added
You will probably want to limit that with a WHERE clause or maybe deal with what happens when this value is already in cartons_current (use either INSERT IGNORE or ON DUPLICATE KEY UPDATE)
You are right, the script has no error.
I think the problem is on your SQL that made you can't insert a new row, specifically on the table structure. Maybe you defined a PRIMARY KEY without AUTO_INCREMENT, defined a INDEX or UNIQUE key that is not the core key or there have some other key that did not have default value. Remember that you can't insert a row without defining all required field.
You script is selecting all part_no and for every part_no you are inserting a new row in the same table, so maybe there is the problem.
I think what you want is update every result to add they core value, you can do that with UPDATE as this code:
function getValue($value) {
return "'" . trim(mysql_real_escape_string($value)) . "'";
}
mysql_query('INSERT INTO `cartons_added` (`add_time`, `type`, `part_no`, `add_type`, `add_qty`, `add_ref`, `add_by`, `add_notes`)
VALUES (' .
getValue($date) . ', ' .
getValue($_POST[type]) . ', ' .
getValue($_POST[part_no]) . ', ' .
getValue($_POST[add_type]) . ', ' .
getValue($_POST[add_qty]) . ', ' .
getValue($_POST[add_ref]) . ', ' .
getValue($_POST[add_by]) . ', ' .
getValue($_POST[add_notes]) .
')');
$partNoQuery = mysql_query('SELECT `part_no` FROM `cartons_current`');
while($partNoResult = mysql_fetch_assoc($partNoQuery)) {
list($prefix, $core, $suffix) = explode('-', $partNoResult['part_no']);
mysql_query('UPDATE cartons_current SET `core` = \'' . $core . '\' WHERE `part_no` = \'' . $partNoResult['part_no'] . '\'');
}
I added getValue function to escape posted data to prevent SQL injection.
Try removing this
$res = mysql_result($sel);
And change your while to reference the main query resource
while($row = mysql_fetch_row($sel)) {
I don't understand your logic with your tables though. You're inserting data into the cartons_added table but then you're selecting from cartons_current?
Also, split is deprecated as of PHP 5.3.0
You said five middle "characters", so I'd add quotes around your variable like so:
$query3 = "insert into cartons_current(core) values('$core')";
(Also, there's only about a gazillion answers on SO about SQL injection, and using pdo)
INSERT INTO cartons_current(core)
SELECT
substr(part_no,position('-' IN part_no)+1,position('-' IN substr(part_no,position('-' IN part_no)+1))-1)
FROM cartons_added;

Using commas in a CONCAT php mysql update [duplicate]

This question already has answers here:
Is storing a delimited list in a database column really that bad?
(10 answers)
Closed 9 months ago.
I have to perform a query similar to:
<?php
//....connect to database
$old = "a,b,c,d";
$new = "e,f,g,h";
$insert = "UPDATE TABLE SET FIELD = CONCAT(" . $old . ", " . $new . ") WHERE something = 'something';
mysql_query($insert);
?>
So basically, I want to append the current database entry with the 'new' string which contains commas. But since the CONCAT function uses commas I'm having trouble.
Does anyone have any tips to accomplish this?
Change this line
$insert = "UPDATE TABLE SET FIELD = CONCAT(" . $old . ", " . $new . ") WHERE something = 'something'";
to this
$insert = "UPDATE TABLE SET FIELD = CONCAT('$old', '$new') WHERE something = 'something'";
Edit:
And if you want a comma between the $old and $new strings you are concatenating, use CONCAT_WS (http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_concat-ws)
Like so:
$insert = "UPDATE TABLE SET FIELD = CONCAT_WS(',', '$old', '$new') WHERE something = 'something'";
Use the function mysql CONCAT_WS() -> Concatenate With Separator
UPDATE TABLE_NAME SET FIELD_NAME = CONCAT_WS(",",FIELD_NAME,FIELD_NAME2) WHERE CONDITON
strings in SQL queries has to be delimited by quotes.
$insert = "UPDATE TABLE SET FIELD = CONCAT(FIELD,',','$new') WHERE ...";
there is also no point in breaking a PHP string, adding only useless noise.
Also, I smell a case for the database normalization
You need to add quotes around the variables so that you get strings, like this (I also added a trailing double quote):
$insert = "UPDATE TABLE SET FIELD = CONCAT('" . $old . "', '" . $new . "') WHERE something = 'something'";

Categories