Cannot access newly created wordpress table - php

I have created a new table in the wordpress database via PhpMyAdmin.
However I have not be able to write into any of the tables that I have created. Writing in the predefined tables such as metapost works just fine with the same code. When I write out the error it seems that wordpress believes that I "forgotten" to enter the table name, like wordpress is not aware that this new table exists. What is going on?
The name of my table is hest
Here is my code:
<?php
$metakey = 'THAT IS';
$metavalue = 'DONE.';
$wpdb->query(
$wpdb->prepare(
"
INSERT INTO $wpdb->hest
( meta_key, meta_value )
VALUES ( %s, %s)
",
$metakey,
$metavalue
)
);
$wpdb->show_errors();
echo $wpdb->last_query;
?>
Here is the show_error message:
As you can see the table name is suddenly gone in the executed query.
WordPress database error: [You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '( meta_key, meta_value ) VALUES ( 'THAT IS', 'DONE.')' at line 2]
INSERT INTO ( meta_key, meta_value ) VALUES ( 'THAT IS', 'DONE.')
Thanks a bunch!!
Cheers Chris.

Looking at the documentation it seems that only the default tables are available as properties on the wpdb class. You would need to reference your new table as a string.
$wpdb->query(
$wpdb->prepare(
"
INSERT INTO hest
( meta_key, meta_value )
VALUES ( %s, %s)
",
$metakey,
$metavalue
)
);
You could alternatively use the insert function to insert a row to your new table.
$wpdb->insert(
'hest',
array(
'meta_key' => $metakey,
'meta_value' => $metavalue,
),
array(
'%s',
'%s',
)
);

Related

MySQL query doesn't work while using wpdb->prepare

I need to insert into two tables at the same time so I'm using BEGIN and COMMIT in the query using $wpdb->query() and $wpdb->prepare() but unfortunately it doesn't work
Testing by [ die( $wpdb->last_error ); ],
Generates [ WordPress database 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 'INSERT INTO TABLE_NAME ( name ) VALUES ( 'xxxxxx' ); at line 2] ]
P.S. I copied the printed query and paste it in mySQL Query window and IT WORKS!!!
$wpdb->query( $wpdb->prepare(
"BEGIN;
INSERT INTO {$tbl_accounts} ( name )
VALUES ( %s );
SELECT LAST_INSERT_ID() INTO #last_seller_id;
INSERT INTO {$tbl_apps} ( seller_id, slug, name, token )
VALUES ( #last_seller_id, %s, %s, %s );
COMMIT;",
$seller_name,
$app_name_sanitized,
$app_name,
$token_key )
);

Add new user and usermeta into database with SQL

I've using this to create a new user in the WordPress database...
// Add user to WP users table.
$user_table_name = $wpdb->prefix . "users";
$unique_string = substr(md5(rand(0, 1000000)), 0, 10);
$wpdb->insert( $user_table_name, array(
'user_login' => sanitize_text_field($_POST['email']),
'user_pass' => sanitize_text_field(MD5($unique_string)),
'user_email' => sanitize_text_field($_POST['email']),
'user_registered' => sanitize_text_field(date("Y-n-d G:i:s")),
'user_status' => $_POST['1'],
'display_name' => sanitize_text_field($_POST['first_name']) . " " . sanitize_text_field($_POST['last_name'])
) );
...which works fine, and let's pretend that the ID of that user turned out to be 1234 in the database table (thanks to auto increment).
So now I also need to add the corresponding user meta information into the usermeta table for that user, and this is where I get a little confused.
The code above is easy because it's just adding a row to a table. But the usermeta table is different because it will need - in this case - a bunch of rows with the corresponding user_ID of 1234 each respectively with:
nickname (I'll use the email address for this)
wp_capabilities (value to be a:1:{s:10:"subscriber";b:1;})
sales (a custom field I have - value will be set to the word "yes")
colour (another custom field I have - value will be set to the word "green")
I'm guessing the SQL statement is going to be similar to the one at the start of this post.
If anyone could show me, that would be awesome.
UPDATE:
So this is mostly done. This works:
// Add corresponding user metadata to WP users table.
$usermeta_table_name = $wpdb->prefix . "usermeta";
$last_id = $wpdb->insert_id;
$role = sanitize_text_field('a:1:{s:10:"subscriber";b:1;}');
$wpdb->query(
$wpdb->prepare(
"
INSERT INTO $usermeta_table_name (
`umeta_id`,
`user_id`,
`meta_key`,
`meta_value` )
VALUES (
NULL,
$last_id,
$usermeta_table_name . 'capabilities',
'$role' )
",
$last_id, $last_id
)
);
That will add one row to the usermeta table, but how can I add 2 more rows within the same statement?
Store the last inserted row's ID to a variable:
$last_id = $wpdb->insert_id;
now, use this $last_id variable for metadata insertion. The insert_id variable is provided by the wpdb class.
OK so I feel a little silly about this - though to be fair it's been a long time since I wrote any SQL :-)
The answer is simply to follow this method:
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);

wpdb query using duplicate key to check update/insert

I am trying to use the query below to insert a row into my wp_postmeta table. If this row exists already e.g the meta_id key is not unique I need it to update this row witht the meta_value at the end of the query.
This is what I have so far
$wpdb->insert( 'wp_postmeta', array('post_id' => $productID[0], 'meta_key' => 'custom_field', 'meta_value' => 'worked'), array("%d","%s","%s") . " ON DUPLCIATE KEY UPDATE meta_value = changed " );
But this is what my last query comes out as:
string(226) "INSERT INTOwp_postmeta(post_id,meta_key,meta_value) VALUES (Array ON DUPLCIATE KEY UPDATE meta_value = changed ,Array ON DUPLCIATE KEY UPDATE meta_value = changed ,Array ON DUPLCIATE KEY UPDATE meta_value = changed )"
As you can see something in the dupolicate key is throwing this off.
You should not do this with wpdb object insert. Looking at the documentation:
$wpdb->insert( $table, $data, $format );
Variable $format has to be Array or String, if you concatenate an SQL string to your array it will cause unexpected behaviors. And you can't concatenate an Array with a String with dot.
You should rather using a raw SQL query with
$wdpb->query('your query')
Or even better:
$wdpb->query($wdpb->prepare('your query'))
to be protected from injection if values are user-inputs.
I found a great way to extend wdpb. I did not write this and I do not want to take credit for it. I am using this to run the 'ON DUPLICATE KEY UPDATE'.
https://wpreset.com/customize-wpdb-class/

MySQL syntax error inserting php strings into table

I'm parsing a website's table with QueryPath and trying to put my results into a MySQL database.
The table looks like this:
mysql_query("CREATE TABLE Airplanes (
flightID VARCHAR( 50 ) PRIMARY KEY NOT NULL,
flightLink TEXT( 20000 ) NOT NULL,
orig TEXT( 20 ) NOT NULL,
dest VARCHAR( 20 ) NOT NULL ,
time VARCHAR( 5 ) NOT NULL
);
");
I was trying to save airplanes using their flight numbers as IDs.
This is how I extract the table and the echos for shoving the variables' contents.
$flightData = $row->find('td');
// $flightID = str_replace(" ", "", $flightData->eq(1)->text());
$flightID = mysql_real_escape_string( trim( $flightData->eq(1)->text() ) );
$flightLink = mysql_real_escape_string( $flightData->eq(1)->html() );
$orig = mysql_real_escape_string( "ROME (FCO)" );
$dest = mysql_real_escape_string( trim( $flightData->eq(2)->text() ) );
$time = mysql_real_escape_string( trim( $flightData->eq(4)->text() ) );
echo '$flightID: ';
echo var_dump($flightID)."<br>";
echo '$orig: ';
echo var_dump($orig)."<br>";
echo '$dest: ';
echo var_dump($dest)."<br>";
echo '$time: ';
echo var_dump($time)."<br>";
Didn't ask to echo $flightLink, that would have been pretty long.
This is the output on the variables:
$flightID: string(7) "JN 5215"
$orig: string(10) "ROME (FCO)"
$dest: string(14) "TEL AVIV (TLV)"
$time: string(5) "23:45"
This is my SQL-query:
$insertQuery = mysql_query("INSERT INTO Airplanes (flightID, flightLink, orig, dest, time) VALUES( '$flightID', '$flightLink', '$orig', '$dest', '$time' ) ON DUPLICATE KEY UPDATE;");
if($insertQuery == false) die("Problem inserting flight data into table. ".mysql_error($connection));
And this is the error message I get on the input query:
Problem inserting flight data into table. 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 '' at line 1
I've seen loads of other guys having trouble feeding MySQL with strings, almost all of them failed on quotation marks, so I bet it's gonna be something about that. Still couldn't find it though.
Also grateful for feedback on improving the MySQL-table, just getting into this and not too sure about the data types.
Your INSERT ... ON DUPLICATE KEY UPDATE syntax is invalid because you have to tell what columns you want to update when a duplicate is encountered
INSERT INTO Airplanes (flightID, flightLink, orig, dest, time)
VALUES( '$flightID', '$flightLink', '$orig', '$dest', '$time' )
ON DUPLICATE KEY UPDATE
^^^^ missing part of ON DUPLICATE clause
It should be something like
INSERT INTO Airplanes (flightID, flightLink, orig, dest, time)
VALUES( '$flightID', '$flightLink', '$orig', '$dest', '$time' )
ON DUPLICATE KEY UPDATE flightLink = VALUES(flightLink),
orig = VALUES(orig),
dest = VALUES(dest),
time = VALUES(time)

$wpdb->insert produces " Duplicate entry '0-0' for Key '1' "

I'm writing a plugin and trying to insert a new row into the wp_term_relationships table inside of a foreach loop. I know the variables have values because of a var_dump, but for some reason, I'm getting an error consistently. This shows up about 600 times on the show_errors() function:
WordPress database error: [Duplicate entry '0-0' for key 1] INSERT
INTO wp_term_relationships
(object_id,term_taxonomy_id,term_order) VALUES ('','','')
My Code:
foreach ($cb_t2c_cat_check as $values) {
global $wpdb;
$prefix = $wpdb->prefix;
$table = $prefix . 'term_relationships';
$object_id = $values->object_id;
$taxo_id = $values->term_taxonomy_id;
$num_object_id = (int)$object_id;
$num_taxo_id = (int)$taxo_id;
//var_dump($num_object_id); //This produces values, so why are they not getting inserted into the table?
//var_dump($num_taxo_id); //This produces values, so why are they not getting inserted into the table?
$wpdb->insert(
$table,
array(
'object_id' => $num_object_id,
'term_taxonomy_id' => $num_taxo_id,
'term_order' => 0
), ''
);
//$wpdb->show_errors();
//$wpdb->print_error();
}
As for why it does not work: do not set third parameter of $wpdb->insert to empty string. It formats every field accordingly..
What it does now is equivalent to:
$wpdb->insert($table, array(
'object_id' => sprintf('', $num_object_id),
'term_taxonomy_id' => sprintf('', $num_taxo_id),
'term_order' => sprintf('', 0)
));
If you really want to set third parameter you should do:
$wpdb->insert($table, array(
'object_id' => $num_object_id,
'term_taxonomy_id' => $num_taxo_id,
'term_order' => 0
), array('%d', '%d', '%d'));
As for error: wp_term_relationships table has a unique primary key on (object_id, term_taxonomy_id). This means that you cannot have two rows in that table which have both same object_id and term_taxonomy_id.
Though this has happened because by setting third parameter of insert to empty string, you are trying to insert rows with object_id=0 and term_taxonomy_id=0 over and over again.
The answer above was correct in that the database needs to have unique keys and cannot insert a row where the key-value pair already exists, and the format of each new value needs to be set. In addition, specific to Wordpress, there was a problem I wasn't addressing, specifically dealing with the term_taxonomy table and updating the count.
First it's important to note that the plugin was designed to update certain categories for posts in the term_relationships table. This was actually accomplished using the $wpdb-> insert method. However, my test for determining whether the plugin actually inserted new rows in the term_relationships table was not to look at the table directly, but to go to the Wordpress dashboard, select categories, and see if the number of posts with that category was more than before. This didn't work, because the plugin never updated the count in the term_taxonomy table. I only discovered this by clicking 'view' next to a category in the Wordpress dashboard and seeing that there were multiple posts with that category, even though the official Wordpress "count" said there were none.
I confirmed that the term_taxonomy table, the 'count' column, needed to be updated as well by going straight to the database and putting WHERE = 'term_taxonomy_id' in the statement. Sure enough, there were over 1700 results, even though Wordpress thought there were none.
Lesson: Confirm the $wpdb->insert method is working by using PHPMyAdmin, not necessarily relying on the Wordpress dashboard.
With a few modifications, the code now works great. Here's an example:
foreach ($cb_t2c_objects as $values) {
global $wpdb;
$prefix = $wpdb->prefix;
$table = $prefix . 'term_relationships';
$object_id = $values->object_id;
$taxo_id = $values->cat_taxo;
$num_object_id = (int)$object_id;
$num_taxo_id = (int)$taxo_id;
//Need to check to see if row exists for each, if not, then insert.
$cb_t2c_get_row = $wpdb->get_row("
SELECT *
FROM ".$prefix."term_relationships
WHERE object_id = ".$num_object_id." AND term_taxonomy_id = ".$num_taxo_id."
GROUP BY object_id, term_taxonomy_id
", OBJECT);
//var_dump($cb_t2c_get_row);
if ( is_null($cb_t2c_get_row) ) {
//Insert the new values.
$wpdb->insert(
$table,
array(
'object_id' => $num_object_id,
'term_taxonomy_id' => $num_taxo_id,
'term_order' => 0
),
array(
'%d',
'%d',
'%d'
)
);
}
//Set the variables for the count update.
$cb_t2c_term_taxonomy_table = $prefix . 'term_taxonomy';
$cb_t2c_update_data = $wpdb->get_var("
SELECT count(term_taxonomy_id) as 'new_count'
FROM ".$prefix."term_relationships
WHERE term_taxonomy_id = ".$num_taxo_id."
",0,0); //returning NULL
//var_dump($cb_t2c_update_data);
//Update the count in the term_taxonomy table.
$wpdb->query("
UPDATE ".$prefix."term_taxonomy
SET count = ".$cb_t2c_update_data."
WHERE term_taxonomy_id = ".$num_taxo_id."
");

Categories