Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 765 Vote(s) - 3.57 Average
  • 1
  • 2
  • 3
  • 4
  • 5
drupal insert or update DB record with only one function

#1
similar quest is here:

[To see links please register here]


But *drupal_write_record()* third argument is to determine update or insert. Maybe drupal has another function, who self determine insert or update by primary key? Or I should it to program my self?
Reply

#2
If you really don't know if there's a record there already, you probably need to check a bit earlier in your program flow. Normally I'd start the function or whatever with a call to the DB and if I don't get an existing record object, I make a new one from stdClass.

This has two benefits: first, it means that you know about existing data, so you can use it if needs be and not overwrite it blindly. Second: when you get to the point where you write to the DB, you know whether it's INSERT or UPDATE based on whether the object has an id property.
Reply

#3
Have a look at the [db_merge()](

[To see links please register here]

) function, I think it has the features you're looking for.
Reply

#4
I implemented function myself:

function drupal_write_record2($table, $data, $primaryKeys) {
$data = (array)$data;

$query = db_select($table)
->fields($table);

if (is_array($primaryKeys))
foreach ($primaryKeys as $key)
$query->condition($key, $data[$key]);
else
$query->condition($primaryKeys, $data[$primaryKeys]);

$update = (bool)$query->execute()->fetchAssoc();

if ($update)
return drupal_write_record($table, $data, $primaryKeys);
else
return drupal_write_record($table, $data);
}
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through