开发者

serialize not working for me in drupal

开发者 https://www.devze.com 2023-03-22 16:13 出处:网络
i am trying to insert data to database but it removing braces\'{}\' while inserting i am using this code.

i am trying to insert data to database but it removing braces'{}' while inserting i am using this code.

<pre><code>
require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);
$aa['alt']="happy alt";
$aa['title']="happy title";
$sldata=serialize($aa);
$sql="Insert into test(pval) values('".$sldata."')";
echo $sql;
db_query($sql);    
</pre></code>

my db structure is as

<pre><code>
CREATE TABLE IF NOT EXISTS `test` (
  `sl` int(11) NOT NULL AUTO_INCREM开发者_如何学CENT,
  `pval` text NOT NULL,
  PRIMARY KEY (`sl`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1
</pre></code>

suggest me what is wrong here..


Drupal uses {} arround the tables names, to be able to do some manipulations on those names -- like prefix them, if you have configured it to do so.

So, you must not use {} in your query -- except arround tables names, of course.


Instead of brutaly injecting your serialized-string into the SQL query, you must use place-holders in it -- and pass the corresponding values to db_query(), which will take care of escaping what has to be :

$sldata = serialize($aa);
$sql = "insert into {test} (pval) values('%s')";
db_query($sql, $sldata);

Here :

  • As the pval field is a string in database, I used a %s place-holder
  • And the first value passed to db_query() (after the SQL query itself, of course) will be injected by drupal, to replace that first (and only, here) placeholder.


And, for more informations, you might want to take a look at Database abstraction layer.


instead of just serialize, you could base64_encode to bypass curlies being a problem.

http://php.net/manual/en/function.base64-encode.php

base64_encode(serialize($aa));

Then on the retrieving side of the data

unserialize(base64_decode($db_data)); 
0

精彩评论

暂无评论...
验证码 换一张
取 消