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'";
Related
I'm trying to do an update to my database. One of the column values contains apostrophes, etc. I have used $this->db->escape in CodeIgniter around the strings that may contain such characters, but I still get the following error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'O\'Keeffe, O\'Keefe'' WHERE `survey_id` = 188' at line 1
UPDATE `survey` SET `firstname_confidence_score` = 100, `firstname_rhymes` = '''', `lastname_confidence_score` = 85, `lastname_rhymes` = ''O\'Keeffe, O\'Keefe'' WHERE `survey_id` = 188;
How do I fix this?
UPDATE:
$sql = "UPDATE `$table_name` SET `firstname_confidence_score` = $firstname_confidence_score, `firstname_rhymes` = '" . $this->db->escape($firstname_rhymes) . "', `lastname_confidence_score` = $lastname_confidence_score, `lastname_rhymes` = '" . $this->db->escape($lastname_rhymes) . "' WHERE `$primary_id` = $id;";
$result = $this->db->query($sql);
Since you are using $this->db->escape(), you are automatically adding single quotes around the data.
You query simply needs to be:
$sql = "UPDATE `$table_name`
SET `firstname_confidence_score` = $firstname_confidence_score,
`firstname_rhymes` = " . $this->db->escape($firstname_rhymes) . ",
`lastname_confidence_score` = $lastname_confidence_score,
`lastname_rhymes` = " . $this->db->escape($lastname_rhymes) .
"WHERE `$primary_id` = $id;";
You do not need the single quotes around $this->db->escape($firstname_rhymes) and so on.
UPDATE `survey` SET `firstname_confidence_score` = 100, `firstname_rhymes` = '''', `lastname_confidence_score` = 85, `lastname_rhymes` = 'O\'Keeffe, O\'Keefe' WHERE `survey_id` = 188;
You had double apostraphes around the lastname_rhymes value.
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) . "'";
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;
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
I've got a SQL query within a foreach loop. Sometimes there can be many, and I mean a lot of queries to do, depending on several criteria, up to 78 queries potentially.
Now, I know that premature optimisation is root cause of all evil, but I don't want to see 78 queries - it's just not healthy.
Here's the code:
$crumbs = explode(",", $user['data']['depts']);
foreach ($crumbs as &$value) {
$data = $db->query("SELECT id FROM tbl_depts WHERE id = '" . $value . "'");
$crumb = $data->fetch_assoc();
$dsn = $db->query("SELECT msg, datetime FROM tbl_motd WHERE deptid = '" . $value . "'");
$motd = $dsn->fetch_assoc();
if ($motd['msg'] != "") {
<?php echo $motd['msg']; ?>
}
}
Can I make it any better?
Use IN MySQL operator to search over a set of values for id:
$ids = '"' . implode('", "',$crumbs) . '"';
$query1 = "SELECT id FROM tbl_depts WHERE id IN (" . $ids . ")";
$query2 = "SELECT msg, datetime FROM tbl_motd WHERE deptid IN (" . $ids . ")";
And so you will not need to retrieve all data you need using foreach loop, so you will have only 2 queries instead of 78.
Example: I have a table named table with 10 records which ids are: 1,2,3,4,5,6,7,8,9,10 (auto-incremented). I know I need records with ids 1,5,8. My query will be:
$sql = "SELECT * FROM `table` WHERE id in (1,5,8);";
And I don't understand why do you need to use & operator in foreach loop if you don't modify the $crubms arrays values.
I think this is want you want.
SELECT msg, datetime
FROM tbl_depts td
INNER JOIN tbl_motd tm ON td.id = tm.deptid