why it shows error for wpdb insert sql? - php

I'm trying simple code with 2 tables(1 customer may have 1 or more phone number):
$wpdb->insert('Customer',array('mtrname' => $_POST['amtrname'],
'test' => $_POST['atest'],
'password' => $_POST['apassword'] ));
Then trying to get the id_customer as FK for table Phones:
$lastid = $wpdb->insert_id;
Then insert:
$wpdb->insert('Phones',array('number' => $_POST['anumber'],
'id_customer' => $lastid ));
In DB it works but I get this error :
WordPress database error: [] INSERT INTO Phones (number,
id_customer) VALUES ('8', '63')
Why I have such an error? All I want to do is linking 2 tables with 1 foreign key as I have "1 to Many" relationship
Customer
- id_customer // primary key, autoincrement
- mtrname // a varchar
- test // a varchar
- password // a varchar
Phones
- id_phone // primary key, autoincrement
- number // a varchar
- id_customer // foreign key reference to Customer

I want to share the solution if someone needs it :
well, I found out that the error comes because I wrote both of these together:
$wpdb->show_errors();
$wpdb->print_error();
When I use just one of them, I don't get any error(I still don't know the logic behind but fine..).
Thanks for your comments and thank you 'Suhas Bachhav' for that hint.

Related

MySQL Duplicate entry for key 'PRIMARY' but a bit more weird

I am having a common problem. I read all over google, but my problem is a bit more weird.
I have a table I use these primary keys:
ALTER TABLE `companies`
ADD PRIMARY KEY(
`name_employee`,
`email`);
So the primary key is a compination of name_employee AND email.
The problem with examples (I give only the primary key's insertions as others are not primary and working as expected):
First insertion OK:
name_employee = 'Pavlos Pavlos'
email = 'company_Name#gmail.com'
Second insertion OK:
name_employee = 'John John'
email = 'company_Name#gmail.com'
Third insertion BAD:
name_employee = 'Nick Nick'
email = 'company_Name#gmail.com'
Error that pops up:
Error: INSERT INTO companies (name, account_number, dateExp,
credit_limit, amount_debt, balance, name_employee, id_employee,
email, password) SELECT name, account_number, dateExp, credit_limit,
amount_debt, balance, 'Nick Nick', '250', 'company_Name#gmail.com',
'pass' FROM companies WHERE email='company_Name#gmail.com'
Duplicate entry 'Nick Nick-company_Name#gmail.com' for key 'PRIMARY'
But there isn't another row with name_employee = Nick Nick and email = company_Name#gmail.com.
What is really weird is that it lets me do a second insertion with the same email but a different name_employee, but it doesn't let me do the same for a third and so on insertion.
Any help please?
EDIT:
This is an assignment and I cannot add more keys/primary keys etc.
Also I need under the same company a lot of employees that's and we can assume that name_employee is different for each one that's why I used these primary keys.
This query
SELECT
name, account_number, dateExp, credit_limit, amount_debt, balance,
'Nick Nick', '250', 'company_Name#gmail.com', 'pass'
FROM companies
WHERE email='company_Name#gmail.com'
selects rows from table companies where email equals 'company_Name#gmail.com'. This is true for two rows ('Pavlos Pavlos' and 'John John'). So you are trying to insert 'Nick Nick' twice. Hence the error.
.

Update dynamic SQL table with history table

I was successful in implementing a table's history (for auditing) based on this answer that basically suggests to create two tables wherein one contains the current version and the other a table of versions with the real data:
CREATE TABLE dbo.Page(
ID int PRIMARY KEY,
Name nvarchar(200) NOT NULL,
CreatedByName nvarchar(100) NOT NULL,
CurrentRevision int NOT NULL,
CreatedDateTime datetime NOT NULL
CREATE TABLE dbo.PageContent(
PageID int NOT NULL,
Revision int NOT NULL,
Title nvarchar(200) NOT NULL,
User nvarchar(100) NOT NULL,
LastModified datetime NOT NULL,
Comment nvarchar(300) NULL,
Content nvarchar(max) NOT NULL,
Description nvarchar(200) NULL
My UPDATEs to static, non-dynamic fields are OK where the versioning is recognised correctly (rough pseudocode adapted from dev't code):
$sql_pagecontent = array(
'PageID' => // logic to get PageID
'Title' => $data['Title']
'User' => $data['User'],
'LastModified' => $this->get_date(),
'Comment' => $data['Comment'],
'Content' => $data['Content'],
'Description' => $data['Description']
);
$this->db->insert('PageContent', $sql_pagecontent);
$id_version = $this->db->insert_id();
$sql_page = array(
'CurrentRevision' => $id_version
);
if($type_version === 'UPDATE')
{
$this->db->where('ID', $page_id_to_replace);
$this->db->update('Page', $sql_page);
}
else
{
$this->db->insert('Page', $sql_page);
}
The problem is when I apply this to dynamic tables with UPDATE.
During UPDATE, I want to achieve the following, just similar to the non-dynamic tables (context of Page and PageContent):
a new PageContent row is INSERTed (new PageContent), a new row of CurrentRevision in Page is added
a new PageContent row is INSERTed (update of existing PageContent), the CurrentRevision in Page UPDATEd with this new row
deleted PageContents are removed from Page
NOTE I want each row of these dynamic tables preserved in both Page and PageContent if ever the user wants to check the changes so I just cannot do INSERT which will just flood the table.
I cannot seem to filter these dynamic values correctly with the current implementation.
Please advise on how to deal with this use case.
Solution
I am not sure if my current implementation of my said requirements is correct, feasible or recommended but it does the job:
get ID of current PageContent being modified
get ID of current Page being modified
delete all rows of Page that has the ID of #1
perform INSERT and apply UPDATE as type of action of PageContent
Number 3 is key to make sure whether existing rows are edited/deleted or new rows added are saved as the current version in Page. Number 4 puts this into place to make sure every row is recognised.

Waht's the best way to use unique validation according to an attribute in a table

I'm using Laravel 5.1 , I've a model Customer which has many Vehicles.
I set validations for Vehicle model like this :
public static $Rules = array(
'code' => 'required|unique:vehicles',
'registernumber' => 'required|unique:vehicles'
);
Till now, all is fine : I can't insert two vehicles with the same code or registernumber.
What I want to do is :
Can I set a custom validation which allows me to insert unique code or registernumber value just for a given CustumerID ?
Example :
Customer1 :
Vehicle1: code1, registernumber1
Vehicle2: code2, registernumber2
(Here I can't insert for example two codes having 'code1' value with Customer1)
Customer2 :
Vehicle1: code1, registernumber1
Vehicle2: code5, registernumber5
(Here I can't insert for example two registernumbers having 'registernumber5' value with Customer2)
Any idea please ?
As long as the customer id is in that table. The way the unique validation rule works is as follows:
unique:
[table name, optionally with a connection name],
[the column you are checking for uniqueness, optional],
[the id of the row that will be ignored in the check (for example if you are updating a row, you want the row you are updating to not be included), optional],
[the column name that contains the id you are running the check against, optional],
[additional where clauses (where_column, where_value)]
So, if your table schema looks like this:
vehicle_id, code_number, registration_number, customer_id
And you only want to run the unique check for rows of the same customer, you can do this:
$customer_id = 'whatever';
$Rules = array(
'code' => 'required|unique:vehicles,code_number,NULL,vehicle_id,customer_id,'.$customer_id
);
That will run the check only on rows where('customer_id', $customer_id)
Syntax
ALTER TABLE `tablename`
ADD UNIQUE KEY `my_unique_key` (`colname1`, `colname2`);
In your example
ALTER TABLE `yourtable`
ADD UNIQUE KEY `unique_reg` (`customername`, `vehicle`, `code`, `regno`);
Try this but you should handle the db_error otherwise it affects the user experience

Duplicate entry '0' for key 'PRIMARY' Key is set as AI and not mentioned in the query

I'm getting the error: Duplicate entry '0' for key 'PRIMARY'
the query which is being ran is:
INSERT INTO cars (make, model, Reg, colour, miles, price, dealerID, mpg, mph) VALUES ('cake', 'pie', 'k', 'blue', '100', '10', '9', '40', '80')
The primary key for the table is carIndex and is set as Auto Increment, as-well as not being mentioned in the query I don't understand this error. It keeps trying to place the new entry at the very start of the table instead of just adding it on.
The PHP which generates this query is:
function addcar()
{
session_start();
if (isset($_SESSION['user']))
{
$db = mysqli_connect('localhost', 'root', '', 'cdb')
or die('Error connecting');
$query = "INSERT INTO cars (make, model, Reg, colour, miles, price, dealerID, mpg, mph)
VALUES (
'".$_POST['manufacture']."',
'".$_POST['model']."',
'".$_POST['reg']."',
'".$_POST['colour']."',
'".$_POST['mileage']."',
'".$_POST['price']."',
'".$_SESSION['dealerID']."',
'".$_POST['mpg']."',
'".$_POST['mph']."'
)
";
$addcarquery = mysqli_query($db, $query)
or die("Error in query: '$query'");
}
}
Edit:
Table structure, sure how to do the visual example I've seen before so I'll describe.
It is made up of 8 fields, the 7 seen in the query + the Primary key of carIndex, currently the only relation ship is between dealerID and a table called dealers, with carIndex set as Auto Increment.
Edit2:
So.... I restarted XAMPP... and well yeah all seems to work fine now -.-' Sorry y'all.
$query = "INSERT INTO cars (carIndex, make, model, Reg, colour, miles, price, dealerID, mpg, mph)
VALUES (
'',
'".$_POST['manufacture']."',
...
One possibility is that it's not the PRIMARY KEY constraint on the cars table that is throwing the error, if there's a trigger being fired that is performing an INSERT. (We can't tell from the name of the constraint PRIMARY that it's definitely the cars table.)
Also, verify that the AUTO_INCREMENT attribute is defined on the PRIMARY KEY column. The output from SHOW CREATE TABLE cars is a quick way to verify the current table definition.
You need to provide us tables structure so we can precisely answer to your question.
Anyway, error You get Duplicate entry '0' for key 'PRIMARY' usually means that for some reason your primary key is NOT defined as AUTO_INCREMENT so when you not explicitly set values for it in query it will always evaluate to 0 and will produce error like those one.
To be precise, you will get such error after you try to insert second record. In empty table this query can pass and will assign 0 for your primary key but on next insert query will fail because you already have value 0 of primary key for first inserted record.

Autoincrement Primary Key in MySQL when data received from form [duplicate]

This question already has an answer here:
Mysql - Add auto_increment to primary key
(1 answer)
Closed 9 years ago.
I have a form that sends the data it captures in to a database, i have a primary key attached to my table (form_id) which i want to autoincrement everytime a new form is submitted and consequently added into my database table. Currently it is just adding a 0 for the first form submitted then anymore forms i submit after do not show as it gives me a message saying you can not have two rows with the same id as zero, which is correct so i would like to change this?
Below is my php code that submits the data into the database:
public function action_claimincentive() {
$this->template->content = View::factory('crm/uk/claim_incentive_form');
$this->template->content->thanks = false;
$this->template->content->val = '';
$this->template->content->post = '';
if ($this->request->post('form')) {
$post = $this->request->post('form');
$stmt = DB::query(Database::INSERT, 'INSERT INTO `claim_incentive_form_data` (`Claimant Name`, `Claimant Postcode`, `Purchase Order No.`, `Claimant Email Address`, `Storename`, `Storetown`, `Date of Sale`, `Date of Delivery`, `Tempur Acknowledgement No.`, `Tempur Product`)
VALUES (:claimantname, :claimantpostcode, :orderno, :email, :storename, :storetown, :dateofsale, :dateofdelivery, :acknowledgementno, :tempurproduct)');
$stmt->param(':claimantname', $post['claimantname']);
$stmt->param(':claimantpostcode', $post['claimantpostcode']);
$stmt->param(':orderno', $post['orderno']);
$stmt->param(':email', $post['email']);
$stmt->param(':storename', $post['storename']);
$stmt->param(':storetown', $post['storetown']);
$stmt->param(':dateofsale', $post['dateofsale']);
$stmt->param(':dateofdelivery', $post['dateofdelivery']);
$stmt->param(':acknowledgementno', $post['acknowledgementno']);
$stmt->param(':tempurproduct', $post['tempurproduct']);
try {
$stmt->execute();
$this->template->content->post = $post;
$this->template->content->thanks = true;
} catch (Exception $e) {
FB::error($e);
}
}
}
This sounds more like a MySQL issue rather than anything else. Make sure you have your Primary Key setup to auto increment. Try altering the table to add the auto increment feature:
ALTER TABLE [table name] MODIFY COLUMN [column name] [column type] PRIMARY KEY AUTO_INCREMENT;
In the above example. Replace the keys in brackets with their appropriate names. Replace [table name] with the name of your table, [column name] with the name of the column and [column type] with the type of the column (SMALLINT, INT, etc).
For more information, see this answer posted by roman.
For more information on the AUTO_INCREMENT feature, check out the MySQL Development Documentation here.
You need to add AUTO_INCREMENT to the primary key column on the table check this http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html
you should be able to alter the table with something like this
ALTER TABLE claim_incentive_form_data CHANGE id id INT(10)AUTO_INCREMENT PRIMARY KEY;
Just make sure you change the id column and the datatype if yours are diffrent from that.
You have to set the auto_increment setting in the table within mysql.
ALTER TABLE `claim_incentive_form_data` MODIFY COLUMN `your_primary_column` int(4) PRIMARY KEY AUTO_INCREMENT
Refs:
http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html
http://dev.mysql.com/doc/refman/5.0/en/alter-table.html
you have to set form_id as primary key, auto increment and not null.

Categories