Insert CURRENT_TIMESTAMP with prepared statement - php

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 (?, ?)

Related

Why am I getting an SQL error when trying to insert a null?

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();

Conversion from MySQL to mysqli not working

I am in a process of converting my Existing MySQL to mysqli
But I can't get this piece of code correct
mysql_query("INSERT INTO `sendmsg`(`sendname`, `recievename`, `subject`, `body` , `mdate`, `mtime`) VALUES ('$sendname','$recievename','$subject','$body','$msgdate','$msgtime')");
$new_id = mysql_insert_id();
mysql_query("INSERT INTO `recievemsg`(`msgid`, `sendname`, `recievename`, `subject`, `body`, `mdate`, `mtime`, `status`) VALUES ($new_id,'$sendname','$recievename','$subject','$body','$msgdate','$msgtime','UNREAD')");
What I tried is given below but didn't work
$mysqli->query("INSERT INTO `sendmsg`(`sendname`, `recievename`, `subject`, `body` , `mdate`, `mtime`) VALUES ('$sendname','$recievename','$subject','$body','$msgdate','$msgtime')");
$new_id = mysqli_insert_id();
$mysqli->query("INSERT INTO `recievemsg`(`msgid`, `sendname`, `recievename`, `subject`, `body`, `mdate`, `mtime`, `status`) VALUES ($new_id,'$sendname','$recievename','$subject','$body','$msgdate','$msgtime','UNREAD')");
The Problem is with the $new_id = mysqli_insert_id(); statement bcoz the first query is executing
For mysqli Object oriented style to get the last inserted id use this
$mysqli->insert_id ;
http://www.php.net/manual/en/mysqli.insert-id.php
So your queries will be as
$mysqli->query("INSERT INTO `sendmsg`(`sendname`, `recievename`, `subject`, `body` , `mdate`, `mtime`) VALUES ('$sendname','$recievename','$subject','$body','$msgdate','$msgtime')");
$new_id = $mysqli->insert_id;
$mysqli->query("INSERT INTO `recievemsg`(`msgid`, `sendname`, `recievename`, `subject`, `body`, `mdate`, `mtime`, `status`) VALUES ($new_id,'$sendname','$recievename','$subject','$body','$msgdate','$msgtime','UNREAD')");

DUPLICATE KEY UPDATE in PRO Prepaid Statement

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.

PDO 2300 upon insert though no rows exist

$compost = $dbh->prepare("INSERT INTO `table`
(`PRIMARY`, `some`, `content`, `rows`, `and`, `boolean`)
VALUES ('', :binded, :param, :inputs, :blah, 0)") ;
the primary key iterates automatically and clasicaly this means my inserts do not need to give actual input for that column just ' ' is fine.
However this keeps throwing a 2300 error.
no rows are indexes or keys just the primary and a dumped all the table rows before attempting this script.
So I removed the primary
$compost = $dbh->prepare("INSERT INTO `table`
( `some`, `content`, `rows`, `and`, `boolean`)
VALUES ( :binded, :param, :inputs, :blah, 0)") ;
but it still throws the error, going to make a new table and try that
Leave the primary key if it is auto increment.
$compost = $dbh->prepare("INSERT INTO `table`
(`some`, `content`, `rows`, `and`, `boolean`)
VALUES (:binded, :param, :inputs, :blah, 0)") ;
If your PRIMARY column name is 'PRIMARY' you can try:
$compost = $dbh->prepare("INSERT INTO `table`
(`PRIMARY`, `some`, `content`, `rows`, `and`, `boolean`)
VALUES (PRIMARY, :binded, :param, :inputs, :blah, 0)") ;
or just not to mention that field at all:
$compost = $dbh->prepare("INSERT INTO `table`
(`some`, `content`, `rows`, `and`, `boolean`)
VALUES (:binded, :param, :inputs, :blah, 0)") ;

Need to insert SQL without duplicates

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

Categories