Wordpress write into database with primary key autoincrement not working - php

I'm trying to write into a database table in a PHP script. This is my code:
$tablename = $wpdb->prefix.'test';
$wpdb->insert( $tablename, array(
'id' => DEFAULT,
'post_id' => $post_id,
'user_id' => $user_id,
array( '%s', '%s', '%s' )
));
After trying out my code I've got following error:
[29-Sep-2018 17:34:29 UTC] PHP Parse error: syntax error, unexpected 'DEFAULT' (T_DEFAULT) in C:\xampp\htdocs\wordpress\wp-content\themes\DiviChild\test.php on line 32
My table has a primary key "id" which should be autoincrement. I don't know what I'm doing wrong.

if "id" is set to be autoincrement then there is no need to include 'id'=>DEFAULT, while inserting record. It will be set automatically in your table when new record is inserted.
It seems there is mistake in argument.
$wpdb->insert takes 3 arguments and it seems you've included 3rd argument into 2nd argument.
$wpdb->insert( $tablename,
array(
'post_id' => $post_id,
'user_id' => $user_id
),
array( '%d', '%s' )
);
Removed id as it's autoincrement and modified formatting array assuming post_id to be numeric based on your comment.

Related

How to use insert_string query helper with SQL function?

My database is using UUIDs as a primary key. When I insert into the DB (mariaDB), I need to do:
insert into table_name (id, parent_id, name,... etc. )
values (UUID_TO_BIN(UUID()), 'a UUID', 'record name', .etc)
I would like to use CI's insert_string function, but this array:
$data = array(
'id' => 'UUID_TO_BIN(UUID())',
'name' => 'record name',
'parent_id' => 'UUID_TO_BIN(' . $parent_id . ')'
);
$this->db->insert_string('table_name',$data);
...I do not think will work, because each result is escaped, so CI will escape the whole text including the function, instead of only what is inside the UUID_TO_BIN function in the parent_id value.
I am trying to figure out if this is a possibility for the parent_id to run the function given. Otherwise, I guess the easiest way is to do the conversion to BIN from HEX in PHP, but will that break the SQL?
You could use the set() method, which accept optional third parameter ($escape), that will prevent data from being escaped if set to FALSE on the id column.
$data = array(
// 'id' => 'UUID_TO_BIN(UUID())',
'name' => 'record name',
'parent_id' => 'UUID_TO_BIN(' . $parent_id . ')'
);
//set id column value as UUID
$this->db->set('id', 'UUID_TO_BIN(UUID())', FALSE);
$this->db->insert_string('table_name', $data);
more on set() method.

data escaping remove for specific filed in cakephp

I am using subquery for id field.
$db = $this->AccountRequest->getDataSource();
$subQuery = $db->buildStatement(
array(
'fields' => array('MAX(id)'),
'table' => $db->fullTableName($this->AccountRequest),
'alias' => 'MaxRecord',
'limit' => null,
'offset' => null,
'order' => null,
'group' => array("user_id")
),
$this->AccountRequest
);
$searching_parameters = array(
#"AccountRequest.id IN " => "(SELECT MAX( id ) FROM `account_requests` GROUP BY user_id)"
"AccountRequest.id IN " => "(".$subQuery.")"
);
$this->Paginator->settings = array(
#'fields' => array('AccountRequest.*'),
'conditions' => $searching_parameters,
'limit' => $limit,
'page' => $page_number,
#'group' => array("AccountRequest.user_id"),
'order' => array(
'AccountRequest.id' => 'DESC'
)
);
$data = $this->Paginator->paginate('AccountRequest');
This structure is producing a query is:
SELECT
`AccountRequest`.`id`,
`AccountRequest`.`user_id`,
`AccountRequest`.`email`,
`AccountRequest`.`emailchange`,
`AccountRequest`.`email_previously_changed`,
`AccountRequest`.`first_name`,
`AccountRequest`.`first_namechange`,
`AccountRequest`.`f_name_previously_changed`,
`AccountRequest`.`last_name`,
`AccountRequest`.`last_namechange`,
`AccountRequest`.`l_name_previously_changed`,
`AccountRequest`.`reason`,
`AccountRequest`.`status`,
`AccountRequest`.`created`,
`AccountRequest`.`modified`
FROM
`syonserv_meetauto`.`account_requests` AS `AccountRequest`
WHERE
`AccountRequest`.`id` IN '(SELECT MAX(id) FROM `syonserv_meetauto`.`account_requests` AS `MaxRecord` WHERE 1 = 1 GROUP BY user_id)'
ORDER BY
`AccountRequest`.`id` DESC
LIMIT 25
In the subquery, its add an extra single quote so it's producing an error.
So, How can I remove these single quotes from this subquery?
Thanks
What are you trying to achieve with the sub query?
The MAX(id) just means it will pull the id with the largest value AKA the most recent insert. The sub query is completely redundant when you can just ORDER BY id DESC.
using MAX() will return only one record, if this is what you want to achieve you can replicate by adding LIMIT 1
If the sub query is just an example and is meant to be from another table I would just run the query that gets the most recent id before running the main query. Getting the last inserted id in a separate query is very quick and I cant see much of a performance loss. I think it will result in cleaner code that`s easier to follow to.
edit 1: From the comments it sounds like all your trying to get is a particular users latest account_requests.
You dont need the sub query at all. My query below will get the most recent account record for the user id you choose.
$this->Paginator->settings = array(
'fields' => array('AccountRequest.*'),
'conditions' => array(
'AccountRequest.user_id' => $userID // you need to set the $userID
)
'page' => $page_number,
'order' => array(
'AccountRequest.id DESC' //shows most recent first
),
'limit' => 1 // set however many you want the maximum to be
);
The other thing you cold be meaning is to get multiple entries from multiple users and display them in order of user first and then the order of recent to old for that user. MYSQL lets you order by more than one field, in that case try:
$this->Paginator->settings = array(
'conditions' => array(
'AccountRequest.user_id' => $userID // you need to set the $userID
)
'page' => $page_number,
'order' => array(
'AccountRequest.user_id', //order by the users first
'AccountRequest.id DESC' //then order there requests by recent to old
)
);
If the example data you have added into the question is irrelevant and you are only concerned about how to do nested subqueries it has already been answered here
CakePHP nesting two select queries
However I still think based on the data in the question you can avoid using a nested query.

wpdb insert with no ID

I'm new in WordPress
I'm trying to insert on database without knowing the id, here what I'm trying to do:
$create = $wpdb->insert('wp_ito_plan', array('name' => $_POST['name'], 'tickets' => $_POST['tickets'], 'price' => $_POST['price'], 'visits' => $_POST['visits']));
and I got this error:
WordPress database error: [Duplicate entry '0' for key 'PRIMARY']
INSERT INTO `wp_ito_plan` (`name`,`tickets`,`price`,`visits`) VALUES ('asd','123','123','123')
I tried adding to the array: 'id' => $wpdb->insert_id, but stills the same.
How can I fix this? Do I need to check what is the last ID on database and then increment? There's no easiest way?
It appears as though you aren't auto incrementing the ID column so you're insert is going to overwrite an existing row. Set the ID column to auto increment and it should work fine.

DynamoDB : query global secondary index on non-key attributes

I want to query global secondary index by applying a condition on non-key attributes of GSI. I have tried below code and its not working.
Code :
$result = $this->dbClient->query(array(
'TableName' => 'myTable',
'IndexName' => 'myIndex',
'AttributesToGet' => array('id'),
'KeyConditions' => array(
// Key attribute
'userId' => array(
'ComparisonOperator' => ComparisonOperator::EQ,
'AttributeValueList' => array(
array(Type::NUMBER => $value)
)
),
// This is non-key attribute
'length' => array(
'ComparisonOperator' => ComparisonOperator::LE,
'AttributeValueList' => array(
array(Type::NUMBER => $upperLimit),
)
),
),
));
EDIT :
I get error message
Query key condition not supported
You can only query on key attributes. You need to create a GSI on "length" - The reason GSI exist is for this purpose.
From http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Query.html
For a query on a table, you can only have conditions on the table
primary key
attributes. You must specify the hash key attribute name and value as an EQ
condition. You can optionally specify a second condition, referring to the range
key attribute.
For a query on an index, you can only have conditions on the index key attributes.
You must specify the index hash attribute name and value as an EQ condition. You
can optionally specify a second condition, referring to the index key range
attribute.

how to use insert_batch with unique ids

I am using codeignitor's insert batch function to insert multiple rows to a table.
$this->db->insert_batch('table', $sizes);
my $sizes array looks like this
$sizes = array(
array(
'size' => 'M' ,
'product' => 'Hat'
),
array(
'size' => 'L' ,
'product' => 'Hat'
)
);
I was intending for separate rows to be added to my db table with these values along with unique ids, however when each nested array is added, It adds 0 to the id field, rather than a unique ID
I am receiving the error "Duplicate entry '0' for key 'id'"
What is the best approach to solve this? Thanks for reading!
Make your UNIQUE Column with AUTO_INCREMENT

Categories