I am trying to insert timestamp to my MySQL database using PHP. But there is shown an error off
Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter
number: parameter was not defined in
/opt/lampp/htdocs/e-exam/user.message.php on line 22
But
Here line 22 is ':sent_at' => $timestamp
$timestamp = date('Y-m-d G:i:s');
//message sending
$sql3 = "INSERT INTO message(title, content, sender_id, sent_at ) VALUES (:title, :content, :sender_id, :sent_at)";
$stmt3 = $pdo->prepare($sql3);
$stmt3->execute(array(
':title' => $_POST['title'],
':content' => $_POST['content'],
':email' => $_SESSION['active_user'],
':sent_at' => $timestamp
));
Please help me to solve this error
If you only want to insert the sent_at ( current time ) , there is easier way, by using NOW() at first you create the table.
the other way is by change the line into this
"INSERT INTO message(title, content, sender_id, sent_at ) VALUES (:title, :content, :sender_id, NOW())";
take a lot at NOW() in the query.
you can try the query
select NOW()
it will result something like this 2018-07-04 18:17:49
in mysql you can use data type datetime
Related
I have connected to the db and able to update a record.
I have a variable named "action" that is either "update" or "add".
I use it in a switch statement to set my query to either "SELECT" or "INSERT".
SELECT statement works.
INSERT statement does not.
I get this error on $pdo->execute($data).
PHP Fatal error: Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined in ...
PDOStatement->execute(Array)
The error is thrown by the PDOStatement
Here is what I have tried, seems pretty straight-forward, but i'm struggling with it.
$data = [
'firstName'=> $firstName,
'lastName'=> $lastName,
'badge'=> $badge,
'department'=> $department,
'image'=> $image,
'active'=> $active,
'stars'=> $stars,
'email'=> $email,
'primary_key'=> $primaryKey,
];
$sql = "INSERT INTO `team`
(`primary_key`,`firstName`, `lastName`, `badge`, `department`, `image`, `active`, `stars`, `email`)
VALUES
(NULL, :firstName, :lastName, :badge, :department, :image, :active, :stars, :email)";
$pdo->prepare($sql);
$pdo->execute($data); <- error is here
When I simply echo my $data array to see if there is something odd. I don't see anything based off all the sites, I've read.
//$data array DATA
primary_key =
firstName = test
lastName = test
badge = 9000
department = marketing
image = 9000.jpg
active = 1
stars = 0
email = tester#test.com
primary_key in db is auto-increment
primary_key is $_post[] on update query and NULL insert query (auto increment db column)
Any errors that would prevent this INSERT query from working that you can see? I'm stuck. I know it the array has 9 variables, there are 9 fields to insert, and 9 values listed.
I know it the array has 9 variables, there are 9 fields to insert, and 9 values listed.
Count the parameters. There are 8 of them. The array includes a value called primary_key for which there is no parameter in the query.
primary_key in db is auto-increment
Then don't insert a value for it:
$sql = "INSERT INTO `team`
(`firstName`, `lastName`, `badge`, `department`, `image`, `active`, `stars`, `email`)
VALUES
(:firstName, :lastName, :badge, :department, :image, :active, :stars, :email)";
And remove primary_key from the $data array.
I'm trying to insert the current date into a database for each entry within an array. I've found documentation for inserting the current date, but nothing that explains how to do it within an array.
<?php
$connect = new PDO("mysql:host=localhost;dbname=testing",
"root", "");
$query = "
INSERT INTO tbl_test
(full_name, id_number, email, pin_rank, team_name)
VALUES (:full_name, :id_number, :email, :pin_rank, :team_name)
";
for($count = 0; $count<count($_POST['hidden_full_name']); $count++)
{
$data = array(
':full_name' => $_POST['hidden_full_name'][$count],
':id_number' => $_POST['hidden_id_number'][$count],
':email' => $_POST['hidden_email'][$count],
':pin_rank' => $_POST['hidden_pin_rank'][$count],
':team_name' => $_POST['hidden_team_name']
);
$statement = $connect->prepare($query);
$statement->execute($data);
}
?>
I would like the current date to display in the last column within the table. Any help would be appreciated.
Assuming you've some kind of date column (date, datetime, etc...) and it's named in my example date_time, just do the following:
$query = "
INSERT INTO tbl_test
(full_name, id_number, email, pin_rank, team_name, date_time)
VALUES (:full_name, :id_number, :email, :pin_rank, :team_name, NOW())
"
Note, if you've got anything other than a date field, you'll get the time along this as well.
I'm not a big fan of the DB NOW because the DB uses it's own timezone settings separate from PHP.
So you can change the TimeZone in PHP and not in MySql and wind up with dates that are wrong (found that out the hard way one time).
And as that has been shown already, I'll show you how to do it with just PHP.
$query = "
INSERT INTO tbl_test
(full_name, id_number, email, pin_rank, team_name, created)
VALUES (:full_name, :id_number, :email, :pin_rank, :team_name, :created)
";
$today = (new DateTime)->format('Y-m-d H:i:s');
#$today = date('Y-m-d H:i:s'); //procedural
for($count = 0; $count<count($_POST['hidden_full_name']); $count++)
{
$data = array(
':full_name' => $_POST['hidden_full_name'][$count],
':id_number' => $_POST['hidden_id_number'][$count],
':email' => $_POST['hidden_email'][$count],
':pin_rank' => $_POST['hidden_pin_rank'][$count],
':team_name' => $_POST['hidden_team_name'],
':created' => $today
);
$statement = $connect->prepare($query);
$statement->execute($data);
}
You can of course get the date and time, within the loop if you need second precision but it's less efficient, due to multiple calls to DateTime.
The insert statement using PDO displays the following errors
Fatal error: Call to undefined function NOW() in C:\xampp\htdocs\copytimeline\timeline1\insert.php
it seems that NOW() belongs in sql statements not in the array. can someone help me to fix that.
thanks
$statement = $db->prepare('INSERT INTO tb ( session_id,timing)
values
( :session_id,:timing)');
$statement->execute(array(
':session_id' => $session_id,
':timing'=> NOW()
));
The MySQL function NOW() can't be passed as a variable. You need to include it in your query.
$statement = $db->prepare('INSERT INTO tb (session_id, timing)
values
(:session_id, NOW())');
$statement->execute(array(
':session_id' => $session_id
));
See MySQL PDO NOW() as assigned value - is it possible?
This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 8 years ago.
I have been staring at the below code for over an hour any cannot see any issues.
public function add($data){
$sql = 'INSERT INTO ' . $this->name . '(fbid, userAccessToken, name, location, story, gender, email, email_md5, referrer, date, use, optin) VALUES (:fbid, :userAccessToken, :name, :location, :story, :gender, :email, :email_md5, :referrer, :date, :use, :optin)';
$mysqldate = date('Y-m-d G:i:s');
$result = $this->dbh->prepare($sql);
if($result->execute(array(
':fbid' => $data['fbid'],
':userAccessToken' => $data['userAccessToken'],
':name' => $data['name'],
':location' => $data['location'],
':story' => $data['story'],
':gender' => $data['gender'],
':email' => $data['email'],
':email_md5' => md5($data['email']),
':referrer' => $data['referrer'],
':date' => $mysqldate,
':use' => $data['use'],
':optin' => $data['optin']
))){
$return = $this->dbh->lastInsertId();
}
}
The error is
PHP Warning: PDOStatement::execute() [pdostatement.execute]:
SQLSTATE[42000]: Syntax error or access violation: 1064 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 'use, optin)
VALUES ('517371547', 'no-auth', 'Shane Jones', 'Manchest' at line 1
USE is a reserved word in mySQL.
You need to put it in backticks, or use a different column name.
use is a keyword in MySQL. If you want to use it as a column identifier, enclose it in backticks:
$sql = 'INSERT INTO `' . $this->name . '` ( `fbid`, `userAccessToken`, `name`, `location`, `story`, `gender`, `email`, `email_md5`, `referrer`, `date`, `use`, `optin`) VALUES (:fbid, :userAccessToken, :name, :location, :story, :gender, :email, :email_md5, :referrer, :date, :use, :optin)';
Anyway you should always enclose all identifiers in backticks, to prevent such errors!
USE is a reserved keyword that must be enclosed with backticks ` (see documentation).
Your problem comes from the fact that you are building your query manually.
While with whatever sane database abstraction library which will take the duty of building syntactically correct queries for you, the code become as small as few short lines:
public function add($data){
global $db;
$data['date'] = date('Y-m-d G:i:s');
$db->query('INSERT INTO ?n SET ?u',$this->name,$data);
return $db->insertId();
}
and raise no error on any of nearly hundred reserved words even if you know none of them.
I try to execute insert statement with "on duplicate" part. As I know Zend doesn`t support this, so I use simple statement:
$sql = "INSERT INTO agent(`inn`, `name`, `created`) VALUES(:inn, :name, :created) ON
DUPLICATE KEY UPDATE `inn` = :inn, `name` = :name, `created` = :created";
$stmt = $this->db->prepare($sql);
$stmt->execute($bind);
Where $bind - is array:
array(
'inn'=>1234567890,
'name'=>'test user',
'created' = new Zend_Db_Expr('NOW()')
);
If I try this query through phpMyAdmin - all works fine,
but after script execution the "created" column value is '0000-00-00 00:00:00'.
WTF?
You can't use an expression as an argument to a placeholder in a prepared statement. It will be interpreted as a string. This has nothing to do with zend framework.
You can either created a formatted date string in php and use that, or use now() in the prepared statement like
VALUES(:inn, :name, NOW())
Another solution, if you need to sometimes supply a datetime, and sometimes use NOW(), is using conditionals to check for that specific case
VALUES(:inn, :name, IF(:created = 'NOW()', NOW(), :created))