I'm using PDO to handle (MYSQL)Database.When i save the result this SQL didn't update the column values it will create a new line with new saving values.What is the mistake i done.Is there anyone can help me to understand this behavior with PDO
$SQL =<<<'EOD'
CREATE TABLE IF NOT EXISTS pard_admin_config(
title varchar(255) NOT NULL,
online varchar(100),
offline varchar(100),
email varchar(100),
metades varchar(200),
metakey varchar(200),
copyright varchar(200),
pard_host varchar(100),
pard_database varchar(100),
username varchar(100),
password varchar(100)
)
EOD;
$pardConfig->query($SQL);
$stmt = $pardConfig->prepare("INSERT INTO pard_admin_config (title, online, offline, email, metades, metakey, copyright, pard_host, pard_database, username, password) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
title='?', online='?', offline='?', email='?', metades='?', metakey='?', copyright='?', pard_host='?', pard_database='?', username='?', password='?'");
$ConfigData = array($adminConfig->TITLE,
$adminConfig->ONLINE,
$adminConfig->OFFLINE,
$adminConfig->EMAIL,
$adminConfig->METADESCRIPTION,
$adminConfig->METAKEYWORDS,
$adminConfig->COPYRIGHT,
$adminConfig->HOST,
$adminConfig->DATABASE,
$adminConfig->USERNAME,
$adminConfig->PASSWORD);
$stmt->execute($ConfigData);
this is not PDO behavior, but mysql
You need to specify either the same values twice, or use values() function
ON DUPLICATE KEY UPDATE
title= values(title), online=values(online), and so on
also note that placing placeholders in quotes makes no sense.
Related
Ok when trying to execute the following insert I'm getting an 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 '2, 3, 4, 5)' at line 1
$insertSQL = sprintf("INSERT INTO applicants (id_file, address_file, photo, transcript, essay1, essay2) VALUES (%s, %s, %s, %s, %s, %s)",
$passport_file,
$address_file,
$photo_file,
$transcript_file,
$essay1_file,
$essay2_file);
mysqli_select_db($STCi, $database_STC);
$Result1 = mysqli_query($STCi, $insertSQL) or die(mysql_error($STCi));
Those variables are being set using the following code
$_FILES['id_file']['error'] == UPLOAD_ERR_OK?$passport_file=filesDB('id_file'):$passport_file = NULL;
$_FILES['address_file']['error'] == UPLOAD_ERR_OK?$address_file = filesDB('address_file'):$address_file = NULL;
$_FILES['photo']['error'] == UPLOAD_ERR_OK?$photo_file = filesDB('photo'):$photo_file = NULL;
$_FILES['transcript']['error'] == UPLOAD_ERR_OK?$transcript_file = filesDB('transcript'):$transcript_file = NULL;
$_FILES['essay1']['error'] == UPLOAD_ERR_OK?$essay1_file = filesDB('essay1'):$essay1_file = NULL;
$_FILES['essay2']['error'] == UPLOAD_ERR_OK?$essay2_file = filesDB('essay2'):$essay2_file = NULL;
filesDB is my own function I'm running to rename the uploaded files and move them into the correct locations and any that are running through that are fine. The problem comes out with 'address_file' as it is an optional file and whenever nothing is uploaded for it I get the error.
So basically MySQL is throwing an error when I'm trying to insert NULL, or am I missing something obvious?
CREATE TABLE `applicants` (
`applicant_id` int(11) NOT NULL AUTO_INCREMENT,
`id_file` varchar(200) CHARACTER SET latin1 DEFAULT NULL,
`address_file` varchar(200) CHARACTER SET latin1 DEFAULT NULL,
`photo` varchar(200) CHARACTER SET latin1 DEFAULT NULL,
`name_change` varchar(200) CHARACTER SET latin1 DEFAULT NULL,
`transcript` varchar(200) CHARACTER SET latin1 DEFAULT NULL,
`english_result` varchar(200) CHARACTER SET latin1 DEFAULT NULL,
`essay1` varchar(200) CHARACTER SET latin1 DEFAULT NULL,
`essay2` varchar(200) CHARACTER SET latin1 DEFAULT NULL,
`stage` varchar(20) DEFAULT 'New',
`date_applied` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`applicant_id`)
) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8;
use a prepared stamement instead of manually creating a query with sprintf:
if ($stmt = mysqli_prepare($STCi, "INSERT INTO applicants
(id_file, address_file, photo, transcript, essay1, essay2)
VALUES (?, ?, ?, ?, ?, ?)"))
{
mysqli_stmt_bind_param($stmt, "ssssss",
$passport_file,
$address_file,
$photo_file,
$transcript_file,
$essay1_file,
$essay2_file);
mysqli_stmt_execute($stmt) or die(mysql_error($STCi));;
}
You're doing an sprintf, and inserting 'NULL', meaning you have a PHP varaible that is NULL.
Your SQL query should look like this after the sprintf:
INSERT INTO applicants (id_file, address_file, photo, transcript, essay1, essay2)
VALUES (null, 2,3,4,5,6)"
but it looks like this:
INSERT INTO applicants (id_file, address_file, photo, transcript, essay1, essay2)
VALUES ( , 2,3,4,5,6)"
And that's an error.
To fix this, you could actually insert the string null here (if you insert it without ', it will not be seen as a string, as you are not using prepared statements). So you query would look like so:
INSERT INTO applicants (id_file, address_file, photo, transcript, essay1, essay2)
VALUES ( null , 2,3,4,5,6)"
Do this by not assiging NULL to the variable, but just assign 'null'. Verify by first echoing your query. It should have the null in it wihtout any quotes.
A better method is to use actual prepared statements: http://php.net/manual/en/mysqli.prepare.php
I think you are confusing the php null value and the mysql null value - they arent the same thing. I think you want something like:
$_FILES['id_file']['error'] == UPLOAD_ERR_OK?$passport_file=filesDB('id_file'):$passport_file = 'NULL';
Note I have quoted the "null". This will put a text null into the sql statement, which will then be interpreted as the keyword 'null' in mysql.
If you leave the php assignment as the value null then a sort of blanky thing is passed to mysql, when it wants the text string 'null' :)
in order to insert null values you should be using prepared statements
$stmt = $STCi->prepare("INSERT INTO applicants (id_file, address_file, photo, transcript, essay1, essay2) VALUES (?, ?, ?, ?, ?, ?)");
$stmt->bind_param("ssssss",
$passport_file,
$address_file,
$photo_file,
$transcript_file,
$essay1_file,
$essay2_file);
$stmt->execute();
I'm working in MySQL 5.5.
I've got a Contacts table like this
CREATE TABLE Contacts
(
ID INTEGER NOT NULL UNIQUE PRIMARY KEY AUTO_INCREMENT,
Name VARCHAR(255) NOT NULL,
Institution VARCHAR(255),
Address VARCHAR(255),
Email VARCHAR(255) NOT NULL UNIQUE,
Phone VARCHAR(10)
);
and an Inventories tables like this
CREATE TABLE Inventories
(
ID INTEGER NOT NULL UNIQUE PRIMARY KEY AUTO_INCREMENT,
InventoryParametersID INTEGER NOT NULL UNIQUE,
ContactID INTEGER NOT NULL,
LocationID INTEGER NOT NULL,
Year INTEGER,
DateUploaded TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
Comments VARCHAR(255),
FOREIGN KEY (ContactID) REFERENCES Contacts(ID)
);
In my webform, contacts upload inventories. Here's the behavior I want:
- When a new contact uploads an inventory, do an insert with their new info
- When an existing contact (determined by email address) uploads another inventory, update their info AND retain referential integrity with the Inventories table
How do I do this?
Here's what I've tried:
CASE
FOREIGN KEY (ContactID) REFERENCES Contacts(ID)
REPLACE INTO Contacts (`Name`, `Institution`, `Address`, `Email`, `Phone`) VALUES (?, ?, ?, ?, ?);
RESULT
No change
CASE
FOREIGN KEY (ContactID) REFERENCES Contacts(ID)
ON UPDATE CASCADE
REPLACE INTO Contacts (`Name`, `Institution`, `Address`, `Email`, `Phone`) VALUES (?, ?, ?, ?, ?);
RESULT
No change
A REPLACE deletes find row and add a new. So your ON UPDATE CASCADE doesn't work. Why do you not use an INSERT ... ON DUPLICATE KEY UPDATE?
INSERT INTO Contacts (Name, Institution, Address, Email, Phone)
VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE
Name = VALUES(NAME),
Institution = VALUES(Institution) ...
MySQL DOC
I´m inserting data with prepared statements.
How can I assign a variable to CURRENT_TIMESTAMP and bind the value?
I have a database table with the columns "name, lastfed, lastdoc and id". The 2 columns called lastfed and lastdoc are of type timestamp.
I have a function and once I run it I want lastfed and lastdoc to register the current date and time.
$lastfed = CURRENT_TIMESTAMP;
$lastdoc = CURRENT_TIMESTAMP;
$query = $db->prepare("INSERT INTO test (`name`, `lastfed`, `lastdoc`, `id`) VALUES (?, ?, ?, ?)");
$query->bindValue(1, $name);
$query->bindValue(2, $lastfed);
$query->bindValue(3, $lastdoc);
$query->bindValue(4, $user);
INSERT INTO test (`name`, `lastfed`, `lastdoc`, `id`)
VALUES (?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, ?)
Or you set CURRENT_TIMESTAMP as default to these columns DB wise. Then you can leave them from your insert statement:
INSERT INTO test (`name`, `id`)
VALUES (?, ?)
I have two tables main_jobs and sub_jobs with the structures below:
$query="create table if not exists main_jobs (
id int not null auto_increment, primary key(id),
industry int(3),
company_name varchar(255),
job_title varchar(255),
email varchar(255),
website varchar(255),
introduction text not null,
application_details text,
advert_date date,
expiry_date date,
upload_date date,
no_deadline int(1) default 0,
logo varchar(255),
featured varchar(20),
source varchar(10) default 'admin',
email_status int default 0,
views int(11) default 1,
short_url varchar(100),
tags varchar(255),
FOREIGN KEY (industry) REFERENCES industry (id))";
if(mysql_query($query,$link)){echo "main_jobs created<br>";} else{ die(mysql_error()); }
$query="create table if not exists sub_jobs (
id int not null auto_increment, primary key(id),
parent_id int(11) not null, FOREIGN KEY (parent_id) REFERENCES main_jobs (id),
title varchar(255),
description text not null,
category int (3), FOREIGN KEY (category) REFERENCES category (id),
job_type varchar(20),
job_level varchar(50),
min_qualification varchar(50),
min_experience int(3),
max_experience int(3),
min_salary int(11),
max_salary int(11),
show_salary int(1) default 1,
denomination varchar(10),
views int(11) default 1,
short_url varchar(100),
email varchar(255),
website varchar(255))";
if(mysql_query($query,$link)){echo "sub_jobs created<br>";} else{ die(mysql_error()); }
I want to insert records but it shows up this error:
Cannot add or update a child row: a foreign key constraint fails (`myjobmag_db`.`sub_jobs`, CONSTRAINT `sub_jobs_ibfk_1` FOREIGN KEY (`parent_id`) REFERENCES `main_jobs` (`id`))
These are mysql queries and have been staring at them for hours but cannot identify the problem:
Insert into main_jobs (Runs successfully)
$resultobj=otherquery("insert into main_jobs(industry, company_name, job_title, email, website, introduction, application_details, advert_date, expiry_date, upload_date, no_deadline, logo) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", "ssssssssssss", array($industry, $company_name, $job_name, $email, $website, $profile, $application, $advert_date, $expiry_date, $date_uploaded, $no_deadline, $logo));
I pick the id of the last insert (confirms that it exists in main_jobs table, this is do manually because of the error) and run insert into sub_jobs
$parent= $resultobj['obj']->insert_id;
mysql_query("insert into sub_jobs(id, parent_id, title, description, category, job_type, job_level, min_qualification, min_experience, max_experience, min_salary, max_salary, show_salary, denomination, email, website) values('', $parent, '$subtitle', '$description', '$category', '$type', '$level', '$min_qualification', '$min_experience', '$max_experience', '$min_salary', '$max_salary', '$show_salary', '$denomination', '$sub_email', '$sub_website')", $link) or die(mysql_error($link));
In my last test the id in main_jobs table is 2616 and it actually exists, yet i get an error.
Kindly assist!
The table is currently this:
CREATE TABLE `feed_items` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`feed_id` int(11) NOT NULL,
`remote_id` varchar(32) NOT NULL DEFAULT '',
`title` varchar(255) NOT NULL DEFAULT '',
`link` varchar(255) NOT NULL DEFAULT '',
`updated_time` datetime NOT NULL,
`created_time` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
I need to find a way so that if i pull multiple RSS feeds into one table, and articles with the same Title have the same value of 'remote_id', how can i make sure I do not insert a duplicate value?
I am currently using
$this->db->query('INSERT INTO feed_items(feed_id, remote_id, link, title, created_time, updated_time) VALUES (?, ?, ?, ?, ?, NOW()) ON DUPLICATE KEY UPDATE remote_id=remote_id', array($this->feed_id, $this->remote_id, $this->link, $this->title, $this->created_time, $this->remote_id));
I was wondering if there is a better way?
Add a UNIQUE constraint to those two columns.
ALTER TABLE `feed_items` ADD UNIQUE INDEX `constraint` (`link`, `remote_id`);
You can use ON DUPLICATE for avoiding such conditions: Check: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
Hope it helps
Try this:
$this->db->query('INSERT INTO feed_items(feed_id, remote_id, link, title, created_time, updated_time) SELECT ?, ?, ?, ?, ?, NOW() WHERE not exists(SELECT 1 FROM feed_items f2 WHERE f2.title = ? and f2.remote_id = ?)', array($this->feed_id, $this->remote_id, $this->link, $this->title, $this->created_time, $this->title, $this->remote_id));
Just to clarify - this solution changes the insert into ... values statement to an insert into...select statement, with a not exists() clause attached. This not exists clause will prevent the insert from doing anything if it finds a record that matches one that is already present. It won't throw an error if there is a pre-existing record.
Thanks for the replies!
I actually managed to solve it a few hours after posting this, I made the remote_id a unique column and then did the following for the SQL
INSERT INTO feed_items(feed_id, remote_id, link, title, created_time, updated_time) VALUES (?, ?, ?, ?, ?, NOW()) ON DUPLICATE KEY UPDATE remote_id=remote_id