How to insert rows into a WordPress custom table - database

I know the title makes it look like a question that has been answered already but I checked the similar questions and I'm still not answered.
I have a custom table created with the following code:
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
meta_id int(9) NOT NULL,
copied tinyint(1) NULL,
local_url varchar(55) DEFAULT '' NOT NULL,
s3_url varchar(55) DEFAULT '' NOT NULL,
PRIMARY KEY (id)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
I'm trying to insert rows into it using the following code but nothing is happening:
$table_name = $wpdb->prefix . 's3images';
$wpdb->insert(
$table_name,
array(
'local_url' => $local_url,
's3_url' => $s3_url,
'meta_id' => $meta_id,
'copied' => 0,
)
);
Where am I messing up?

Use following query to insert new row in your custom database table
$sql = "INSERT INTO ".$table_name." set local_url='".$local_url."',s3_url='".$s3_url."',meta_id='".$meta_id."',copied='".$copied." ";
$results = $wpdb->query($sql);

Related

Updating a custom table on user profile create/save

I'm trying to update a row in a custom table (or update if the 'user_id' exists) when creating or updating a user profile. The source data is the 'location' field - an ACF field.
Currently the custom table doesn't get updated on profile create or save. Here's what I have so far:
function copy_location_to_user_locations( $user_id ) {
if ( !current_user_can( 'edit_user', $user_id ) ) {
return false;
}
$location = get_field('location', 'user_'.$user_id); // Needs to match the ACF field name
$latitude = $location['lat'];
$longitude = $location['lng'];
global $wpdb;
$table_name = $wpdb->prefix . 'user_locations';
$data = array(
'user_id' => $user_id,
'latitude' => $latitude,
'longitude' => $longitude
);
$wpdb->replace( $table_name, $data );
}
add_action( 'profile_update', 'copy_location_to_user_locations', 10, 1 );
add_action( 'user_register', 'copy_location_to_user_locations', 10, 1 );
What have I missed?
For reference, my function for creating the custom table is:
function create_user_locations_table() {
global $wpdb;
$table_name = $wpdb->prefix . 'user_locations';
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE $table_name (
id bigint(20) NOT NULL AUTO_INCREMENT,
user_id bigint(20) UNSIGNED NOT NULL,
latitude float(10,6) NOT NULL,
longitude float(10,6) NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (user_id) REFERENCES {$wpdb->users}(ID)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
}
register_activation_hook( __FILE__, 'create_user_locations_table' );

How to do database migration in wordpress?

I am newbie to the wordpress. I have created a custom installable plugin. Now i want that When this plugin is installed at that time some tables should be migrated to the database required by this plugin.
Any help will be helpful. Thank you.
You can register an activation hook. This will fire when your plugin is activated and do what you want it to do. In combination with dbDelta you can execute the creation of a table (or the alteration if a new version requires different layout of your table).
A working example is provied:
<?php
global $jal_db_version;
$jal_db_version = '1.0';
function jal_install() {
global $wpdb;
global $jal_db_version;
$table_name = $wpdb->prefix . 'liveshoutbox';
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
name tinytext NOT NULL,
text text NOT NULL,
url varchar(55) DEFAULT '' NOT NULL,
UNIQUE KEY id (id)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
add_option( 'jal_db_version', $jal_db_version );
}
function jal_install_data() {
global $wpdb;
$welcome_name = 'Mr. WordPress';
$welcome_text = 'Congratulations, you just completed the installation!';
$table_name = $wpdb->prefix . 'liveshoutbox';
$wpdb->insert(
$table_name,
array(
'time' => current_time( 'mysql' ),
'name' => $welcome_name,
'text' => $welcome_text,
)
);
}
register_activation_hook( __FILE__, 'jal_install' );
register_activation_hook( __FILE__, 'jal_install_data' );
?>

Issue with setDataSource in CakePHP 2.4.8

I wrote a behavior, Cascadable, that merges records across 2 databases. It works sort of like CSS, where the more local style overrides the global. The behavior uses $this->setDataSource() to switch between the databases. This was working up until the 2.4.8 release when this commit was made to the Model.php file.
Here's sort of an extraction from the behavior:
$Model->setDataSource( 'alt' );
$altData = $Model->find($findType, array(
'contain' => false,
'conditions' => array(
$Model->alias.'.id' => $ids
),
'callbacks' => 'before'
));
If the callbacks option is set to false, I get Missing Database Table errors about tables that are only present in the default (parent) datasource.
I'm not sure what I'm doing wrong here, but after 2.4.8 upgrade it always uses the wrong (parent) database instead of the child. I can revert Model.php back to the 2.4.7 version to fix the issue. I realize this is difficult to replicate because it only breaks in my very specific database structure.
MySQL Table Schema example:
Parent Database Table
CREATE TABLE `products` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL DEFAULT '',
`price` float(8,2) DEFAULT NULL,
`active` tinyint(1) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`),
KEY `active` (`active`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 PACK_KEYS=0;
INSERT INTO `parent_db`.`products` (`id`, `name`, `price`, `active`) VALUES (NULL, 'Big Box of Goodies', '99.99', '0');
Child Database Table
CREATE TABLE `products` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`price` float(8,2) DEFAULT NULL,
`active` tinyint(1) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `active` (`active`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 PACK_KEYS=0;
INSERT INTO `child_db`.`products` (`id`, `name`, `price`, `active`) VALUES (NULL, 'Small Box of Surprises', NULL, '1');
Query Results
From Parent DB
array(
(int) 0 => array(
'Product' => array(
'id' => '1149',
'name' => 'Big Box of Goodies',
'price' => '99.99',
'active' => false
)
)
)
From Child DB with working Cascadable behavior (child record is merged into parent record, ignoring null values)
array(
(int) 0 => array(
'Product' => array(
'id' => '1149',
'name' => 'Small Box of Surprises',
'price' => '99.99',
'active' => true
)
)
)
Workaround:
Setting the schemaName manually after using setDataSource fixes the issue for me.
$Model->setDataSource( 'alt' );
App::uses('ConnectionManager', 'Model');
$dataSources = ConnectionManager::enumConnectionObjects();
$Model->schemaName = $dataSources['alt']['database'];

Wordpress plugin creating database in localhost but not on real host

So I am busy creating a plugin that creates a custom table to read in some data.
The plugin works 100% on localhost but does not create the table in the db on the real host.
I have debug enables and there does not seem to be a problem.
I have tried query but no luck
On localhost the wordpress installation is in the root file but on the server the wordpress installation is in a folder called v in the root file. (might make a difference?)
The basic code is
<pre><code>
function elite_fuel_installl() {
global $wpdb;
$table_name = $wpdb->prefix . "test";
$sql = "CREATE TABLE $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
timeDataCollected datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
ULP93Inland text NOT NULL,
ULP95Inland text NOT NULL,
ULP93Coastal text NOT NULL,
ULP95Coastal text NOT NULL,
Diesel005 text NOT NULL,
Diesel0005 text NOT NULL,
UNIQUE KEY id (id)
);";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
$rows_affected = $wpdb->replace( $table_name, array
( 'id' => $idd, 'timeDataCollected' => current_time('mysql'),
'ULP93Inland' => $ULP93Inland, 'ULP95Inland' => $ULP95Inland,
'ULP93Coastal' => $ULP93Coastal,'ULP95Coastal' => $ULP95Coastal,
'Diesel005' => $Diesel005,'Diesel0005' => $Diesel0005) );
}
register_activation_hook( __FILE__, 'elite_fuel_installl' );
</code></pre>
Thanks

Help with CakePHP Model Relationships

Three simple tables...
Feedname (eg. News or
Events) which are the names of RSS
feeds.
Posts that belong to a
Feedname
User, that owns all
the posts
I want to use the Form helper to automatically give me a select box so that when I add a post I can select which Feedname to assign it to.
It seems like posts belong to both Feedname and User but I can't get the correct combination of belongsTo and hasMany in my model/ .php files. The select box for feedname is shown, but there is nothing in it. Can anyone point me in the right direction?
The tables look like this at the moment:
CREATE TABLE `feednames` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
`created` datetime DEFAULT NULL,
`modified` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE `posts` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
`body` text COLLATE utf8_unicode_ci,
`created` datetime DEFAULT NULL,
`modified` datetime DEFAULT NULL,
`user_id` int(10) unsigned NOT NULL DEFAULT '1',
`feedname_id` int(10) unsigned NOT NULL DEFAULT '1',
PRIMARY KEY (`id`),
KEY `foreign_key` (`user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) CHARACTER SET latin1 NOT NULL,
`password` char(40) CHARACTER SET latin1 NOT NULL,
`group_id` int(11) NOT NULL,
`created` datetime DEFAULT NULL,
`modified` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
edit - adding the model .php files ...
class Feedname extends AppModel {
var $name = 'Feedname';
var $hasMany = array(
'Post' => array(
'className' => 'Post',
'foreignKey' => 'feedname_id',
'dependent' => false
)
);
}
class Post extends AppModel {
var $name = 'Post';
var $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id'
),
'Feedname' => array(
'foreignKey' => 'feedname_id'
)
);
}
class User extends AppModel {
var $name = 'User';
var $hasMany = array(
'Post' => array(
'className' => 'Post',
'foreignKey' => 'user_id',
'dependent' => false
)
);
}
edit - adding SQL dump ** ...
/posts/index.ctp:
SELECT COUNT(*) AS count FROM posts AS Post LEFT JOIN users AS User ON (Post.user_id = User.id) LEFT JOIN feednames AS Feedname ON (Post.feedname_id = Feedname.id) WHERE 1 = 1
SELECT Post.id, Post.title, Post.body, Post.created, Post.modified, Post.user_id, Post.feedname_id, User.id, User.username, User.password, User.group_id, User.created, User.modified, Feedname.id, Feedname.name, Feedname.created, Feedname.modified FROM posts AS Post LEFT JOIN users AS User ON (Post.user_id = User.id) LEFT JOIN feednames AS Feedname ON (Post.feedname_id = Feedname.id) WHERE 1 = 1 ORDER BY Post.created DESC LIMIT 10
Please note: /posts/add.ctp does not produce any SQL dump, so it's not getting the select box options from the database, this is what I'm trying to fix with proper model relationships.
Do you have something like this in your controller methods (e.g. the admin_add / admin_edit functions)?
$feednames = $this->Feedname->find('list');
$this->set('feednames', $feednames);
Cake should then automatically populate the select list with these values. Or you can manually set the values with:
$form->input('feedname_id', array('options' => $feednames));
So far I agree :
posts > belongs to > users
posts > belongs to > feednames
feednames > has many > posts
users > has many > posts
Just checking, but, did you actually insert data into your tables? Else it would be only logical that your select field is empty. Also, what does the Sql dump say in debug mode?

Resources