Drupal 6 db insert: Strings are getting escaped - mysql

Getting driven crazy by this one...
I'm trying to insert a number of rows into a D6 database with a single db_query call. I've collected the rows as a set of strings, and have then collected them into one big string, something like so:
$theData = "(1, 2, 'a'), (3, 4, 'b'), (5, 6, 'c')";
db_query("insert into {table} (int1, int2, str) values %s", $theData);
($theData isn't typed like that in my code; it's the result of the code I've written -- a big string containing sets of values wrapped up in parens.)
When this runs, I get an error like:
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 'insert into
table (int1, int2, str) values (1,2,\'a\' at line 1 query: insert into
table (int1, int2, str) values (1,2,\'a\'),(3,4,\'n\'),(5,6,\'c\')...
So, db_query or somebody else is escaping the strings before passing the values of to mysql. How do I keep this from happening? I could do individual queries for each set of data, but that's wrong/expensive for all the obvious reasons. Thanks!

$theDatas = array("(1, 2, 'a')", "(3, 4, 'b')", "(5, 6, 'c')");
foreach($theDatas as $data) {
db_query("insert into {table} (int1, int2, str) values %s", $data);
}
But it's not recommend to do that, instead of this you should:
$theDatas = array(array(1, 2, 'a'), array(3, 4, 'b'), array(5, 6, 'c'));
foreach($theDatas as $data) {
db_query("insert into {table} (int1, int2, str) values (%d, %d, '%s')", $data[0], $data[1], $data[2]);
}
Or you can serialize($theData) and put it "text" format field as one value, then use unserialize() for restoring array - this way is recommend if you want only store data (no searching, indexing etc).

Related

Get top x values in mysql table according to column value

I have the following table data:
content,count
'a', '1'
'b', '2'
'c', '2'
'd', '2'
'content_name', '18'
'de', '2'
'dea', '2'
'deaasdfdsaf', '5'
'content_name', '17'
I would like to have the correct query for getting x (for example 4) rows with the biggest values in their content column
I have tried the answers given in:
Getting Top 3 from Mysql table based on Condition/Value
but it didnt work as i was expecting
it keeps giving me just the rows by their table location
any suggestions?
create table Test(content varchar(100),count integer );
insert into Test(content, count) values("a", 1);
insert into Test(content, count) values("b", 2);
insert into Test(content, count) values("c", 2);
insert into Test(content, count) values("d", 2);
insert into Test(content, count) values("content_name", 18);
insert into Test(content, count) values("de", 2);
insert into Test(content, count) values("dea", 2);
insert into Test(content, count) values("deaasdfdsaf", 5);
insert into Test(content, count) values("content_name", 7);
select * from Test
order by count desc
limit 4;
However, I am not quite sure what you mean by "biggest values in their content column", therefore I ranked by their count values.
If you are actually looking for the number of character within the content column, which was my initial impression reading your question:
Using Martin Stagl's post to create the example table .
select *, LENGTH(REPLACE(content, 'N', '')) as char_length from Test;
NOTE: If this is not working on the server, try replacing the LENGTH() function with LEN()
Fiddle: http://sqlfiddle.com/#!9/032d48/9

Any way to auto add a quote mark around a character variable during implode for mysql?

Here it is..
Foreach ($data as $x) {
$mydata = implode( ", ", $x);
$sql = "INSERT INTO `wp_realty_listingsdb` (`listingsdb_id`, `user_id`,
`class_id`, `MLS`, `DOM`, `Zip`, `Status`) VALUES($id, 1, 1, $mydata);";
echo "$sql<br>";
$id++;
}
Keep in mind this is a simplified example and there will be over 200 fields being imploded for insertion.. so there might be as many as 100+ character variables that will require tick encapsulation so if the implode won't do it then it could get complicated..
End result of echo the resultant sql..
Line 1:
INSERT INTO `wp_realty_listingsdb` (`listingsdb_id`, `user_id`,
`class_id`, `MLS`, `DOM`, `Zip`, `Status`) VALUES(2, 1, 1, 1475566, 626,
89005, Sold);
Line 2:
INSERT INTO `wp_realty_listingsdb` (`listingsdb_id`, `user_id`,
`class_id`, `MLS`, `DOM`, `Zip`, `Status`) VALUES(3, 1, 1, 1485995, 492,
89005, 'Sold');
PROBLEM: To use php insert the character variables require that it have a tick on each side of the variable like 'Sold' as you see in line 1 it will not put the tick on implode.. Line 2 is an example of where i manually added the tick.. and it works fine.. Is there anyway to have the implode add the ticks around any character variables... w/o extensive additional programming.
$xt = array_map(function($x){ return "'$x'";}, $x);
$mydata = implode( ", ", $xt);
Apart from that the code is probably vulnerable to SQL injection.

How to set Django to Ignore mysql errors and force mysql to insert a record?

So I am a naive Django developer and want a similar functionality as INSERT IGNORE of mysql in Django. Is there a way to do that? Right now whenever I try to save a record in my database, It throws (1364, Field doesn't have a default value). Should there be any change in Django settings or mysql settings?
You can execute mySQL command in Django.
create_fields = ['f1', 'f2', 'f3']
values = [
(1, 2, 3),
(4, 5, 6),
(5, 3, 8)
]
db_table = self.model._meta.db_table
values_sql = []
values_sql.append( "(%s)" % (','.join([ " %s " for i in range(len(create_fields))]),) ) # correct format
base_sql = "INSERT IGNORE INTO %s (%s) VALUES " % (db_table, ",".join(create_fields))
sql = """%s %s""" % (base_sql, ", ".join(values_sql))
cursor.executemany(sql, values)

how to insert '&' in mysql database using ios?

I am inserting value which contains & character, but the value breaks after & while it's inserted in database. Can anyone please help me to insert value with & character?
My filed's datatype is varchar(50) and collation is utf8_general_ci.
I have used code:
NSString *strUr=[NSString stringWithFormat:#"%s%s?event_name=%#&id=%#",ServerPath,URLAddEvent,eventName,ID];
strUr = [strUr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"url : %#",strUr);
request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:strUr]];
con=[[NSURLConnection alloc]initWithRequest:request delegate:self];
if(con)
{
webdata=[NSMutableData data];
}
in my ios code.
Any needful help will be appreciated.
You can escape any special characters.
you need to identify them using string manipulation and then create the sql accordingly.
See My fiddle.
Inserting into table:
INSERT INTO Table1
(`id`, `col1`)
VALUES
(1, 'test\&'),
(2, 'special character \''),
(3, 'speacial character \"'),
(4, 'test'),
(5, 'testing'),
(6, 'test')
;
Selection from table:
select * from Table1 where col1 like '%&%' or col1 like '%\'%'

mysql: write query with if in where part

i have this table:
(`id`, `name`, `type`, `price`)
(1, 'cats', 1, 12.25),
(2, 'dogs', 0, 11.35),
(3, 'house', 1, 7.25),
(4, 'cats2', 2, 5.26);
I need select all data, but if type is 1, i need get items witch price is more than 10.
I create this query:
SELECT *
FROM `items`
WHERE IF(TYPE = "1", price > 10, 1 = 1)
Works well, but maybe possible write much smarter or in other way?
Maybe don't need "1 = 1"?.
I would like to know your advice, thanks
Your 1=1 is senseless, but your IF is not. You can use just 1:
SELECT *
FROM `items`
WHERE IF(TYPE = "1", price > 10, 1)
-since MySQL evaluates expression as bool (actually, int) - and so 1 means 'true'.
But on the other hand, there's logic equivalent for your condition:
SELECT *
FROM `items`
WHERE `price`>10 OR `type`!="1"
However, I've faced such case in another question and, after some researching, I've discovered that IF is faster, even if it looks more complicated.