Update if record doesn't exist in MySQL DB - php

This is my table: (the unique main key is alias)
$sql = "CREATE TABLE IF NOT EXISTS Articls
(
id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(254) COLLATE utf8_persian_ci NOT NULL,
alias INT(10) UNSIGNED NOT NULL, # alias name for url
title VARCHAR(254) NOT NULL COLLATE utf8_persian_ci NOT NULL,
UNIQUE (alias)
) DEFAULT COLLATE utf8_persian_ci";
So I want to insert a new record to the DB if alias does not exist in the table or update the table if the alias already existed before.
I tried this without success.
$sqlname = "name,alias,title";
$sqlValue = "'".$node['name']."','".$node['alias']."','".$node['title']."'";
$sql = "INSERT INTO Articls (".$sqlname.")
VALUES (".$sqlValue.")
ON DUPLICATE KEY UPDATE
(".$sqlname.") VALUES (".$sqlValue.")";
I also tried this code with no success... It just creates a new record and doesn't update:
$sql = "INSERT INTO Articls (".$sqlname.")
VALUES (".$sqlValue.")
ON DUPLICATE KEY UPDATE title = 'test',alias = '".$node['alias']."'";

The synthax:
ON DUPLICATE KEY UPDATE
(".$sqlname.") VALUES (".$sqlValue.")";
is not correct.
Use:
ON DUPLICATE KEY UPDATE <fieldname> = <fieldvalue>, <fieldname> = <fieldvalue>...

Related

no entry into parent table but "0" or "blank" insert into FK in child table

Hi guys I am trying to solve one problem with inserting data to Parent - Child tables. Tables below and also ERR diagram show a structure and PK/FK keys. I am inserting data from webform and PHP is used to capture data and pass it to the database.
Fields in mainTable - F_Name, L_Name and Email are just input textfields,
fields in college tables are checkboxes.
Imagine that one teacher can teach at one, two or three colleges where he checks the checkbox for each college/school where he is teaching. But if he teaches only at one college there is when my problem comes. As all of the "college" tables are linked to "Teacher" with PK/FK.
My question is, is there any way how to store auto generated College ID's if for example teacher is teaching only at one college. At the moment with my PHP it fails and I don't know how to fix it.
I have a example of my PHP under the Schema structure. Just a small note that connection to database works properly.
If this or similar was already asked I do appologize.
Thanks for any tips.
-------------------------------------------------------
-- Schema test
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `test` DEFAULT CHARACTER SET latin1 ;
USE `test` ;
-- -----------------------------------------------------
-- Table `test`.`CollegeA`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test`.`CollegeA` (
`CollegeAID` INT(11) NOT NULL AUTO_INCREMENT,
`SchoolA` VARCHAR(45) NOT NULL,
`SchoolB` VARCHAR(45) NOT NULL,
`SchoolC` VARCHAR(45) NOT NULL,
PRIMARY KEY (`CollegeAID`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
-- -----------------------------------------------------
-- Table `test`.`CollegeB`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test`.`CollegeB` (
`CollegeBID` INT(11) NOT NULL AUTO_INCREMENT,
`School1` VARCHAR(45) NOT NULL,
`School2` VARCHAR(45) NOT NULL,
`School3` VARCHAR(45) NOT NULL,
PRIMARY KEY (`CollegeBID`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
-- -----------------------------------------------------
-- Table `test`.`CollegeC`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test`.`CollegeC` (
`CollegeCID` INT(11) NOT NULL AUTO_INCREMENT,
`School11` VARCHAR(45) NOT NULL,
`School22` VARCHAR(45) NOT NULL,
`School33` VARCHAR(45) NOT NULL,
PRIMARY KEY (`CollegeCID`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
-- -----------------------------------------------------
-- Table `test`.`Teacher`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test`.`Teacher` (
`TeacherId` INT(11) NOT NULL AUTO_INCREMENT,
`F_name` VARCHAR(45) NOT NULL,
`L_name` VARCHAR(45) NOT NULL,
`Email` VARCHAR(45) NOT NULL,
`CollegeAID` INT(11) NOT NULL,
`CollegeBID` INT(11) NOT NULL,
`CollegeCID` INT(11) NOT NULL,
PRIMARY KEY (`MainId`),
INDEX `CollegeAID_idx` (`CollegeAID` ASC),
INDEX `CollegeBID_idx` (`CollegeBID` ASC),
INDEX `CollegeCID_idx` (`CollegeCID` ASC),
CONSTRAINT `CollegeAID`
FOREIGN KEY (`CollegeAID`)
REFERENCES `test`.`CollegeA` (`CollegeAID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `CollegeBID`
FOREIGN KEY (`CollegeBID`)
REFERENCES `test`.`CollegeB` (`CollegeBID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `CollegeCID`
FOREIGN KEY (`CollegeCID`)
REFERENCES `test`.`CollegeC` (`CollegeCID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
SET SQL_MODE=#OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=#OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=#OLD_UNIQUE_CHECKS;
PHP example
if(empty($SchoolA) && empty($SchoolB) && empty($SchoolC)){
$CollegeAId = "";
}
else {
$queryCOLLEGEA = "
INSERT INTO CollegeA (SchoolA, SchoolB, SchoolC)
VALUES('$SchoolA','$SchoolB','$SchoolC')";
$result = mysqli_query($con, $queryCOLLEGEA);
$CollegeAId = mysqli_insert_id($con);
};
if(empty($School1) && empty($School2) && empty($School3)){
$CollegeBId = "";
}
else {
$queryCOLLEGEB = "
INSERT INTO CollegeB (School1, School2, School3)
VALUES('$School1','$School2','$School3')";
$result = mysqli_query($con, $queryCOLLEGEB);
$CollegeBId = mysqli_insert_id($con);
};
if(empty($School11) && empty($School22) && empty($School33)){
$CollegeCId = "";
}
else {
$queryCOLLEGEC = "
INSERT INTO CollegeB (School11, School22, School33)
VALUES('$School11','$School22','$School33')";
$result = mysqli_query($con, $queryCOLLEGEC);
$CollegeCId = mysqli_insert_id($con);
};
$queryMain = "
INSERT INTO Teacher (F_Name, L_Name, Email, CollegeAID, CollegeBID, CollegeCID)
VALUES ('$F_Name', '$L_Name', '$Email', '$CollegeAId', '$CollegeBId', '$CollegeCId')";
$result = mysqli_query($con, $queryMain);
You are using NOT NULL column as foreign key. In this case you cannot leave it empty, you must set here correct key from referenced table. You can change table definition to
CREATE TABLE IF NOT EXISTS `test`.`Teacher` (
`TeacherId` INT(11) NOT NULL AUTO_INCREMENT,
`F_name` VARCHAR(45) NOT NULL,
`L_name` VARCHAR(45) NOT NULL,
`Email` VARCHAR(45) NOT NULL,
`CollegeAID` INT(11),
`CollegeBID` INT(11),
`CollegeCID` INT(11),
PRIMARY KEY (`MainId`),
INDEX `CollegeAID_idx` (`CollegeAID` ASC),
INDEX `CollegeBID_idx` (`CollegeBID` ASC),
INDEX `CollegeCID_idx` (`CollegeCID` ASC),
CONSTRAINT `CollegeAID`
FOREIGN KEY (`CollegeAID`)
REFERENCES `test`.`CollegeA` (`CollegeAID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `CollegeBID`
FOREIGN KEY (`CollegeBID`)
REFERENCES `test`.`CollegeB` (`CollegeBID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `CollegeCID`
FOREIGN KEY (`CollegeCID`)
REFERENCES `test`.`CollegeC` (`CollegeCID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
In this table you can insert NULL values into CollegeAID, CollegeBID and CollegeCID. So, if teacher works in college, it will have value in appropriate CollegeID. If no - CollegeID will be NULL.
Also you will ned to change your code. Change you code like this
if(empty($SchoolA) && empty($SchoolB) && empty($SchoolC)){
$CollegeAId = null;
}
for all three colleges. You need null, not empty string.
And another change is needed here
$queryMain = "
INSERT INTO Teacher (F_Name, L_Name, Email, CollegeAID, CollegeBID, CollegeCID)
VALUES ('$F_Name', '$L_Name', '$Email', '$CollegeAId', '$CollegeBId', '$CollegeCId')";
Variable $CollegeAId now contains proper NULL value. But this query will be produced into
INSERT INTO Teacher (F_Name, L_Name, Email, CollegeAID, CollegeBID, CollegeCID)
VALUES ('F_Name', 'L_Name', 'Email', '', 'CollegeBId', 'CollegeCId')
See it? Still empty string instead of NULL! You need to change query string. It must looks like
INSERT INTO Teacher (F_Name, L_Name, Email, CollegeAID, CollegeBID, CollegeCID)
VALUES ('F_Name', 'L_Name', 'Email', NULL, 'CollegeBId', 'CollegeCId')
For example, you can do it this way for college A:
$CollegeAId = isset($CollegeAId) ? "'$CollegeAId'" : 'NULL';
$queryMain = "
INSERT INTO Teacher (F_Name, L_Name, Email, CollegeAID, CollegeBID, CollegeCID)
VALUES ('$F_Name', '$L_Name', '$Email', $CollegeAId, '$CollegeBId', '$CollegeCId')";

Symfony2 MySQL: INSERT SELECT syntax error

I am having problems with writing correct MySql query. I want to insert new collection for every user with id higher than 1000 but less than 10000.
$conn = $this->em->getConnection();
$stmt = $conn->prepare('INSERT INTO collection (name, type)
values(:name, :type)
SELECT * FROM user WHERE id<:endUser AND id>:startUser');
$stmt->bindValue('name', 'Default');
$stmt->bindValue('type', 0);
$stmt->bindValue('startUser', 1000);
$stmt->bindValue('endUser', 10000);
$stmt->execute();
This what I tried to write, but I get syntax error. Please explain me how to correct query
UPD
I should have given detailed structure of tables.
Collection
CREATE TABLE IF NOT EXISTS `collection` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`type` smallint(6) NOT NULL,
PRIMARY KEY (`id`),
KEY `IDX_FC4D6532A76ED395` (`user_id`)
);
User
CREATE TABLE IF NOT EXISTS `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
);
User has one-to-many relationship with Collection.
With a SELECT INTO you have to select the values you want to place in the new row and only those values. And you dont use the VALUES() clause.
As you are using static values for the new rows and not values from the user table you can do it like this.
Oh and I see in your edit you were using the wrong table name It should have been fos_user
Also as fos_user.user_id is a NOT NULL field you need to include that column in the list of fields in the insert.
$conn = $this->em->getConnection();
$stmt = $conn->prepare('INSERT INTO collection (user_id, name, type)
SELECT id, 'default', 0
FROM fos_user
WHERE id > :startUser AND id < :endUser');
$stmt->bindValue('startUser', 1000);
$stmt->bindValue('endUser', 10000);
$stmt->execute();

SQL/PHP - On key update

I have messed up my database design a bit. This was the original schema:
CREATE TABLE IF NOT EXISTS `xeon_stats_clicks` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`typ` enum('1','2','3','4','5','6','7','8','9') COLLATE utf8_bin NOT NULL,
`user` varchar(20) COLLATE utf8_bin NOT NULL,
`data` varchar(10) COLLATE utf8_bin NOT NULL,
`value` varchar(20) COLLATE utf8_bin NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `typ` (`typ`,`user`,`data`),
KEY `data` (`data`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=1 ;
As you can see, I have KEY on the following:
UNIQUE KEY `typ` (`typ`,`user`,`data`),
KEY `data` (`data`)
I have the following code execute:
"INSERT INTO `xeon_stats_clicks` (typ, user, data, value) VALUES ('1', :username, :date, 1) ON DUPLICATE KEY UPDATE value = value + 1"
However, above code doesn't work now, as my table schema now look like this:
CREATE TABLE `xeon_stats_clicks` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`typ` enum('1','2','3','4','5','6','7','8','9') COLLATE utf8_bin NOT NULL,
`user` varchar(20) COLLATE utf8_bin NOT NULL,
`data` varchar(10) COLLATE utf8_bin NOT NULL,
`value` varchar(20) COLLATE utf8_bin NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `idx_value` (`value`),
KEY `idx_typ` (`typ`),
KEY `idx_data` (`data`),
KEY `idx_user` (`user`),
KEY `data` (`data`),
KEY `data_2` (`data`)
) ENGINE=MyISAM AUTO_INCREMENT=991799 DEFAULT CHARSET=utf8 COLLATE=utf8_bin
How can I revert the changes made, and return to the first schema without messing up the data in the table?
I have no idea why your first schema + code doesn't work.
It works for value that is integer:
http://sqlfiddle.com/#!9/c3260/1
INSERT INTO `xeon_stats_clicks` (typ, user, data, value) VALUES
('2', 'user2', 'data3', 1) ON DUPLICATE KEY UPDATE `value` = `value` + 1
But if you will try on fiddle to apply that query to other lines it doesn't work. Because mysql can't convert VARCHAR to INT.
My guess you have wrong data in value column. For the combination of (typ, user, data, value) that you test.
UPDATE Here is the fiddle with your second schema in use:
http://sqlfiddle.com/#!9/5ea62b/1
As you can see your query works fine as well if you add
UNIQUE KEY `typ` (`typ`,`user`,`data`),
to that second schema.
and here is ALTER TABLE variant that works as well:
http://sqlfiddle.com/#!9/57b409/1
UPDATE 2 Another guess: You have broken uniqueness in your table now.
If I got you correctly you had
UNIQUE KEY `typ` (`typ`,`user`,`data`),
when start the project. After a while you did remove that UNIQUE KEY from schema. That change allowed mysql to insert duplicate records into that table. And apparently you inserted several (or a lot) of duplicates. And now you want to apply ALTER TABLE to get back unique key but mysql refuse that because of that.
Like here: http://sqlfiddle.com/#!9/4cbb5 <-- uncomment ALTER line to see error message
So you need to fix uniqueness first.
UPDATE 3 Delete duplicates:
http://sqlfiddle.com/#!9/85f228/1
DELETE FROM xeon_stats_clicks USING xeon_stats_clicks
INNER JOIN xeon_stats_clicks dup
ON xeon_stats_clicks.id < dup.id
AND xeon_stats_clicks.typ = dup.typ
AND xeon_stats_clicks.user = dup.user
AND xeon_stats_clicks.data = dup.data;

How would I be able to duplicate my auto_increment? DATABASE PHP

Hey how would I be able to duplicate my only auto increment key to another key, basically I want my (' id ') to display the same information on my (' user_id '), here is the code:
CREATE TABLE IF NOT EXISTS `".$db_table_prefix."users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(10) NOT NULL,
`user_name` varchar(50) NOT NULL,
`username` varchar(50) NOT NULL,
PRIMARY KEY (`id`),
KEY `user_id` (`id`)
How would I be able to input the same information from my id to my user_id?
Not sure what you mean but if you want to have the same value repeted two times in the same record It's pointless and redundant.
You can use the SQL aliases to achive what you want:
SELECT id as user_id FROM ...
If you really need to sync up the two field of your table you can do:
UPDATE table SET user_id = id WHERE user_id != id
Not sure why you would want to do this, but if you want to duplicate the information after an INSERT you would need to fetch the new ID and then perform an UPDATE
// get the newly inserted ID
$new_id = $db->insert_id;
// perform the update on the table
$db->query("UPDATE users SET user_id=".$db->escape($new_id)." WHERE id=".$db->escape($new_id));
Also, in your table definition the fields don't match: int(11) vs. int(10).

Why doesn't the primary key field exist in a MySQL database when creating a table?

The exact error I keep seeing is:
Key column 'alarmID' doesn't exist in table
alarmID is my primary key field.
Here is the code I have:
$sql = "CREATE TABLE IF NOT EXISTS alarms (
alaramID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (alarmID),
Title CHAR(30),
Description TEXT,
DT DATETIME
)";
Note: I am coding in PHP.
$sql = "CREATE TABLE IF NOT EXISTS alarms (
alaramID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (alaramID),
Title CHAR(30),
Description TEXT,
DT DATETIME
)";
alaramID
The primary key in your table is alaramID and note the error its alarmID.So correct the spelling in the query like this
$sql = "CREATE TABLE IF NOT EXISTS alarms (
alaramID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (alaramID),
Title CHAR(30),
Description TEXT,
DT DATETIME
)";

Categories