How to insert current timestamp to database? - php

I have been trying this query and researching but I can not understand why it does not work.
The IP record(VARCHAR) is saved in the table on the database, but I can not save the record DATETIME, when the record is inserted.
$sql = "INSERT INTO ips (ip, fecha) VALUES (:ip, :CURRENT_TIMESTAMP)";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
':ip' => htmlentities($_POST['ip']),
':CURRENT_TIMESTAMP' => htmlentities(CURRENT_TIMESTAMP)
));

Use PHP's time function:
$sql = "INSERT INTO ips (ip, fecha) VALUES (:ip, :CURRENT_TIMESTAMP)";
$t = time();
$today = date("Y-m-d", $t);
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
':ip' => htmlentities($_POST['ip']),
':CURRENT_TIMESTAMP' => $today

Related

Convert from mysqli to PDO add empty string

I'm trying to convert mysqli to PDO but I'm getting one string empty, all the rest is fine.
My code mysqli:
$sql="SELECT uid FROM userprofile WHERE `name` = '$_POST[name]'";
$result=mysqli_query($con,$sql);
if($result&&mysqli_num_rows($result)>0){
$dwID = mysqli_fetch_array($result);
$time=time().'000';
$time1=time();
switch($_POST['t3']){
case ''.$mail_9.'':{
$b=bin2hex($_POST['type1'].','.$_POST['ts1'].','.$_POST['ts2']);
$b1=($_POST['type1'].','.$_POST['ts1'].','.$_POST['ts2']);
mysqli_query($con,"INSERT INTO mail (uid, toUser, title, contents, rewardId, itemIdFlag, status, type, rewardStatus, saveFlag, createTime, reply) VALUES (md5($time), '$dwID[0]','$_POST[titlegift]','$_POST[titlegift]', 0x$b,'1','0','13','0','0','$time','0')")or die('2');
And now I'm trying to converto to PDO like this:
$sql = "SELECT * from userprofile where `uid`='$_POST[name]'";
$query = $dbh2 -> prepare($sql);
$query->execute();
$result=$query->fetch(PDO::FETCH_OBJ);
$cnt=1;
$uid = $query->$result;
$time = time().'000';
$gifttitle = $_POST['gifttitle'];
$b = bin2hex($_POST['type1'].','.$_POST['itemid'].','.$_POST['quantity']);
$sql1 = "INSERT INTO mail (uid, toUser, title, contents, rewardId, itemIdFlag, `status`, `type`, rewardStatus, saveFlag, creatTime, reply) VALUES (md5($time), '$uid', '$_POST[gifttitle]', '$_POST[gifttitle]', 0x$b, '1', '0', '13', '0', '0', '$time', '0')";
$query = $dbh2 -> prepare($sql1);
$query -> execute();
But when I run var_dump (SQL) it add all the fields and only $uid is empty.
Sorry for the code mysqli I know it is a messy.
This is wrong:
$uid = $query->$result;
$result is an object containing the row that was fetched from the table. It's not the name of a property of the $query object.
That should be:
$uid = $result->uid;
You should also use a prepared statement rather than substituting variables into the SQL string.
$sql1 = "INSERT INTO mail (uid, toUser, title, contents, rewardId, itemIdFlag, `status`,
`type`, rewardStatus, saveFlag, creatTime, reply)
VALUES (md5(:time), :uid, :gifttitle, :gifttitle, UNHEX(:rewardid), '1', '0',
'13', '0', '0', :time, '0')";
$query = $dbh2 -> prepare($sql1);
$query->bindParam(':time', $time);
$query->bindParam(':uid', $uid);
$query->bindParam(':rewardid', $b);
$query->bindParam(':gifttitle', $_POST['gifttitle']);
$query->execute();

Query conditions to insert data from a form

What I'm trying to do is:
If the age input in my form = 28, 30, 25 or 21 then I want to auto insert value 8 in the column (VE), else keep it empty. Is this the right way to do that?
if($form_data->action == 'Insert')
{
$age=array(28, 30, 25, 21);
$age_str=implode("','", $age);
if($form_data->age == $age_str){
$query="INSERT INTO tbl
(VE) VALUE ('8') WHERE id= '".$form_data->id."'
";
$statement = $connect->prepare($query);
$statement->execute();
}
$data = array(
':date' => $date,
':first_name' => $first_name,
':last_name' => $last_name,
':age' => $age
);
$query = "
INSERT INTO tbl
(date, first_name, last_name, age) VALUES
(:date, :first_name, :last_name, :age)
";
$statement = $connect->prepare($query);
if($statement->execute($data))
{
$message = 'Data Inserted';
}
}
Also, how do I insert the new row with the row id from the other form data going into tbl?
Use php's in_array instead of trying to compare a string. To get the id of the query where you insert the form data, you can return the id of the insert row from your prepared statement.
if ($form_data->action == 'Insert') {
// assuming $age, $date, $first_name, $last_name
// already declared prior to this block
$data = array(
':date' => $date,
':first_name' => $first_name,
':last_name' => $last_name,
':age' => $age
);
$query = "
INSERT INTO tbl
(date, first_name, last_name, age) VALUES
(:date, :first_name, :last_name, :age)
";
$statement = $connect->prepare($query);
if ($statement->execute($data)) {
$message = 'Data Inserted';
// $id is the last inserted id for (tbl)
$id = $connect->lastInsertID();
// NOW you can insert your child row in the other table
$ages_to_insert = array(28, 30, 25, 21);
// in_array uses your array...so you don't need
// if($form_data->age == $age_str){
if (in_array($form_data->age, $ages_to_insert)) {
$query="UPDATE tbl SER VE = '8' WHERE id= '".$id."'";
$statement2 = $connect->prepare($query);
$statement2->execute();
}
}
}

How to insert the current date within an 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.

Insert and update same table with transactions

Since I can't/don't know how to auto_increment two columns in one table I trying to do this with transactions. This is what I trying
$pdo->beginTransaction();
try
{
$sql = "INSERT INTO users ( username, password, firstname, lastname, email, user_image, path)
VALUES (:username, :password, :firstname, :lastname, :email, :user_image, :path)";
$q = $pdo->prepare($sql);
$q->execute(array(
':username' => $username,
':password' => sha1($password),
':firstname' => $firstname,
':lastname' => $lastname,
':email' => $email,
':user_image' => $forDB,
':path' => $path,
));
$lastInsertID = $pdo->lastInsertId();
$sql = $pdo->prepare("INSERT INTO users (usertype)
VALUE (:user_id)");
$sql->execute(array(
':user_id' => $lastInsertID
));
$pdo->commit();
}
// any errors from the above database queries will be catched
catch (PDOException $e)
{
// roll back transaction
$pdo->rollback();
// log any errors to file
ExceptionErrorHandler($e);
exit;
}
So basically I want to insert in column usertype the ID of this record (user_id) both columns must be equal.
Now when I try with this .. it is save empty fields except for the usertype which is updated with lastInsertID
Change
$sql = $pdo->prepare("INSERT INTO users (usertype)
VALUE (:user_id)");
to this
$sql = $pdo->prepare("UPDATE users SET usertype=:user_id WHERE user_id=:user_id");

Cannot insert new data into database with pdo

I have a problem trying to insert new data into database,
i don't even get any error
$db = new MyPDO();
$datauser = array(
'account' => $acc,
'tid' => $tid,
'email' => $email,
'amount' => $amount,
'date' => 'NOW()',
'obj_id' => $object_id);
$sql = $db->query("INSERT INTO account_reg_log
(account, tid, email, amount, date, obj_id) VALUES
(:account, :tid, :email, :amount, :date, :obj_id)");
$sql->execute($datauser);
Checking database after running the script and see no new rows..
Any ideas how can i fix hat?
You need to prepare your statement instead of running a query directly with placeholders.
Change:
$sql = $db->query("INSERT INTO account_reg_log
(account, tid, email, amount, date, obj_id) VALUES
(:account, :tid, :email, :amount, :date, :obj_id)");
To:
$sql = $db->prepare("INSERT INTO account_reg_log
(account, tid, email, amount, date, obj_id) VALUES
(:account, :tid, :email, :amount, :date, :obj_id)");
You should also add error handling in your MyPDO class so that PDO will throw exceptions and tell you exactly what goes wrong when it goes wrong.

Categories