I need to insert to custom table that has primary key 'id' by number, but I got this problem for example
I have 5605 rows (start with id = 1) in my table,so I have to set current id = 5606 to insert.
1/I set $data['id'] = 5606 by hand to insert it, it works fine. current row with id 5606 is inserted.
but I want it automatically get the right id to insert so I do
2/select * to returns the current number of rows in table, it returns 5604 (always lesser by 1 when I check database has 5605). so I + 2 then do insert.
It ends up insert 3 times like 5606 5607 5608 in my table.
Please help me here is my code
$data = array(
'name' => 'naomi',
'ability' => 'walk',
);
$wpdb->get_results("SELECT * FROM contest");
$numid = $wpdb->num_rows;
$numid +=2;
$data['id'] = $numid;
$wpdb->insert('contest', $data);
The given number is for example, my problem is in that format.
Just declare column id (or whatever you use as primary key) as AUTO_INCREMENT (in MySQL) or SERIAL (in PostgreSQL) and insert all other columns but your primary key.
Example:
CREATE TABLE Persons
(
ID int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (ID)
);
INSERT INTO persons (LastName,FirstName,Address,City) VALUES (
'Sample','Person','Sample-street','Sample-city'
);
More than! You should not use any manual inserts for primary keys, because it can make you a lot of problems with handling unsuccessfull queries etc.
SECOND PART. To return number of rows in your table just use
SELECT COUNT(id) FROM persons;
Related
Supposing I have a table:
CREATE TABLE files (
id_prod INT UNSIGNED NOT NULL DEFAULT PRIMARY KEY AUTO_INCREMENT,
id_rel INT UNSIGNED,
name VARCHAR(250),
other VARCHAR(200),
UNIQUE INDEX(id_rel , name)
);
and I want to use an unique query to insert/update the data on this table:
INSERT INTO files (id_rel , name)
VALUES ('25', 'test')
ON DUPLICATE KEY UPDATE
now, reading the MySQL manual I read about this:
ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID(id)
so I thought my query should be:
INSERT INTO files (id_rel , name)
VALUES ('25', 'test')
ON DUPLICATE KEY UPDATE id_prod = LAST_INSERT_ID(id), name = 'TESTED'
but which is the difference if I use only:
INSERT INTO files (id_rel , name)
VALUES ('25', 'test')
ON DUPLICATE KEY UPDATE name = 'TESTED'
?
I cannot understand the meaning of LAST_INSERT_ID(id). What is (id) and what it's supposed to do?
This is only necessary if your application needs to call LAST_INSERT_ID() after performing the INSERT. Normally, LAST_INSERT_ID() will only return a value if you actually inserted a new row into the table, not of there was a duplicate key and it updated the row instead.
From the documentation:
If expr is given as an argument to LAST_INSERT_ID(), the value of the argument is returned by the function and is remembered as the next value to be returned by LAST_INSERT_ID().
If you use the idiom you quoted, LAST_INSERT_ID() will return either the ID of the new row that was inserted or the row that was updated.
I am working on MySQL database. I am new to it that is why I am facing a problem. The problem is populating the child table with foreign key which is referencing to the parent table. I have two tables employee which contains following columns
id as a primary key,
first_name
last_name
birth_date
and a borrowed table which contains following columns
ref as a primary key
employId as a foreign key
book
The employeeId is referencing the primary key id of the employee table. So simply it means the one employee with same id can borrow multiple books. When I insert some data into the employee table It get inserted, but when I have to insert data into the borrowed table, I have to manually insert the value in employeeId column. Isn't it supposed to be populated automatically. or I am misunderstanding the concept of the foreign key.
My SQL Code
$uname = "root";
$pass = "";
$sname ="localhost";
$db ="nady";
//Making database connection
$con = mysqli_connect($sname,$uname,$pass,$db);
$t1 = "CREATE TABLE IF NOT EXISTS employee (
id smallint(5) unsigned AUTO_INCREMENT NOT NULL,
firstname varchar(30),
lastname varchar(30),
birthdate date,
PRIMARY KEY (id)
) ENGINE=InnoDB";
$con->query($t1);
$t2 = "CREATE TABLE IF NOT EXISTS borrowed (
ref int(10) unsigned NOT NULL auto_increment,
employeeid smallint(5) unsigned NOT NULL,
book varchar(50),
PRIMARY KEY (ref),
FOREIGN KEY (employeeid) REFERENCES employee(id) ON UPDATE CASCADE ON DELETE CASCADE
) ENGINE=InnoDB";
$con->query($t2);
if(!$con->query($t2)){
echo $con->error;
}
$i1 = "INSERT INTO employee VALUES(NULL,\"Nadeem\",\"Ahmad\",22)";
$con->query($i1);
$i2 = "INSERT INTO borrowed VALUES(NULL,1,\"Ahmad\")";
$con->query($i2);
if(!$con->query($i2)){
echo $con->error;
}
Simple what I need is ; For example an employee with id 1. Who borrowed 3 books. So in the borrowed table the employeeId column will have three rows with values 1 and different books name. My point is how would I populate the employeeId column when I am inserting the data into it. Let say, John have have borrowed three books and have id 1 then how would I insert data to borrowed table with employeeId of john. I need the query for it. and also query to retrieve the books borrowed by john.
The foreign key is used to link two tables, indicating that the field in a column
(employId from borrowed, in your case) refers to the PRIMARY KEY of another table (id from employee).
When you're inserting a new line in borrowed, you have to indicate the user that is taking that book, to insert it in that line. You have to know the user that is doing it. If you have foreign key, you need the id of that user, which is supposed to be his unique identifier. To insert that John has taken a book, you need to know that John's id is 1.
If the user is already in your employee table and you know his first and last name, you can get the id with a simple select...
SELECT id FROM employee WHERE first_name='John' AND last_name='Smith'
... and then you can do the insert with the id obtained.
If it's new user, you need to add the user first to employee, then get the new id and then insert the new line in borrowed, to do this without having to re-query to employee table to get the new id, you can use the PHP mysqli::$insert_id/mysqli_insert_id function, that gives you the PRIMARY key of the last query. For example...
$con->query("INSERT INTO employee (first_name,last_name) VALUES ('Mark','Whatever')");
$newemployeeid = $con->insert_id;
$con->query("INSERT INTO borrowed (employeeid,book) VALUES (".$newemployeeid.",'Awesome Book Title')");
I hope it helps
Your just need change these lines
$employee_id = $con->insert_id;
$i2 = "INSERT INTO borrowed VALUES(NULL,".$employee_id.",\"Ahmad\")"
first you get last insert id as $employee_id through a inser_id mysql predefined function then you add this $employee_id in borrowed table inserted query.
You can also use the MySQL-function LAST_INSERT_ID(). This function fetches the id from any previous INSERT statement, in the OPs case after inserting a new employee into employee table.
So the INSERT statement can be shortened to this:
INSERT INTO borrowed (employeeid, book) VALUES(LAST_INSERT_ID(),'Ahmad')";
Also note, that it is not required (and probably not even allowed) to fill the column 'ref' since it has AUTO_INCREMENT.
Here's the link to MySQL's documentation/function reference about LAST_INSERT_ID().
I have the following table:
CREATE TABLE `my_table` (
composite_pk1 INT NOT NULL ,
composite_pk2 INT NOT NULL ,
data VARCHAR(255) NOT NULL ,
primary key (composite_pk1, composite_pk2)
) ENGINE=InnoDB;
For a given composite_pk1, I wish composite_pk2 to act as an autoincrement primary key. I don't wish to lock the table, and as such plan on using a trigger such as the following:
DELIMITER $$
CREATE TRIGGER my_trigger BEFORE INSERT ON my_table
FOR EACH ROW BEGIN
SET NEW.composite_pk2 = (
SELECT IFNULL(MAX(composite_pk2), 0) + 1
FROM issue_log
WHERE composite_pk1 = NEW.composite_pk1
);
END $$
I can now insert a record:
$stmt=$myDB->prepare('INSERT INTO my_table(composite_pk1, data) VALUES (?,?)');
$stmt->execute([123,'hello']);
How do I get the last inserted composite_pk2? PDO::lastInsertId only works with native autoincrement tables (i.e. not the trigger approach). I "could" later do a SELECT query to get the max value, however, there is no guarantee that another record has snuck in.
You can make composite_pk2 an unique key with auto_increment:
CREATE TABLE `my_table` (
composite_pk1 INT NOT NULL ,
composite_pk2 INT NOT NULL unique auto_increment,
data VARCHAR(255) NOT NULL ,
primary key (composite_pk1, composite_pk2)
) ENGINE=InnoDB;
Now last_insert_id() will return the recently created id for composite_pk2.
I'm building a small report in a PHP while loop.
The query I'm running inside the while() loop is this:
INSERT IGNORE INTO `tbl_reporting` SET datesubmitted = '2015-05-26', submissiontype = 'email', outcome = 0, totalcount = totalcount+1
I'm expecting the totalcount column to increment every time the query is run.
But the number stays at 1.
The UNIQUE index composes the first 3 columns.
Here's the Table Schema:
CREATE TABLE `tbl_reporting` (
`datesubmitted` date NOT NULL,
`submissiontype` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL,
`outcome` tinyint(1) unsigned NOT NULL DEFAULT '0',
`totalcount` mediumint(5) unsigned NOT NULL DEFAULT '0',
UNIQUE KEY `datesubmitted` (`datesubmitted`,`submissiontype`,`outcome`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
When I modify the query into a regular UPDATE statement:
UPDATE `tbl_reporting` SET totalcount = totalcount+1 WHERE datesubmitted = '2015-05-26' AND submissiontype = 'email' AND outcome = 1
...it works.
Does INSERT IGNORE not allow adding numbers? Or is my original query malformed?
I'd like to use the INSERT IGNORE, otherwise I'll have to query for the original record first, then insert, then eventually update.
Think of what you're doing:
INSERT .... totalcount=totalcount+1
To calculate totalcount+1, the DB has to retrieve the current value of totalcount... which doesn't exist yet, because you're CREATING a new record, and there is NO existing data to retrieve the "old" value from.
e.g. you're trying eat your cake before you ever went to the store to buy the ingredients, let alone mix/bake them.
Mysql table (migration_terms) fields are as follows
oldterm count newterm seed
I used the following create table statment.
CREATE TABLE `migration_terms`
(
`oldterm` varchar(255) DEFAULT NULL,
`count` smallint(6) DEFAULT '0',
`newterm` varchar(255) DEFAULT NULL,
`seed` int(11) NOT NULL AUTO_INCREMENT, PRIMARY KEY (`seed`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
And It works, no problems there.
but then when I used the following insert into statement to populate it;
"INSERT INTO migration_terms
SELECT looseterm as oldterm,
COUNT(seed) AS count
FROM looseterms
GROUP BY looseterm
ORDER BY count DESC "
I get this error;
Column count doesn't match value count at row 1
I cannot figure out why?
If you need the table structure of the looseterms table, it was created by the following create table statement.
CREATE TABLE looseterms
(
`seed` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
`looseterm` varchar(255)
)
You need to specify the columns if your select statement has fewer columns than the table
"INSERT INTO migration_terms
(oldterm,
count)
SELECT looseterm AS oldterm,
Count(seed) AS count
FROM looseterms
GROUP BY looseterm
ORDER BY count DESC "
From MySql docs on Insert Syntax
If you do not specify a list of column names for INSERT ... VALUES or
INSERT ... SELECT, values for every column in the table must be
provided by the VALUES list or the SELECT statement. If you do not
know the order of the columns in the table, use DESCRIBE tbl_name to
find out.
Your insert is adding 2 columns of data, whereas your table's definition has 4 columns