简体   繁体   中英

MySQL PHP: Geting 0000-00-00 00:00:00 when using NOW() in a datetime column

Using the SQL in the below code:

public function saveOrder() {
  $id = $this->getUserId();
  $this->db->query("INSERT INTO orders VALUES (null, '$id', '$this->basket_lines', '$this->total', NOW() )");
  return $this->db->id();  
}

Where the last column in the above is a DATETIME field, the result in the database keeps defaulting to 0000-00-00 00:00:00 .

I have tried the column format as timestamp too and used:

ALTER TABLE  `content ` CHANGE  `date`  `date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP

from another post but to no avail.

Can anyone spot whats wrong?

Thanks

Edit: BTW I am escaping my SQL statement from within the DB class using

    $this->SQL = $this->mysqli->real_escape_string($SQL);
    $this->result = $this->mysqli->query($SQL);

Edit 2: I am now escaping pre query with

 $i=mysql_real_escape_string($id);
    $b=mysql_real_escape_string($this->basket_lines);
    $t=mysql_real_escape_string($this->total);
    $this->db->query("INSERT INTO orders VALUES (null, '$i', '$b', '$t', NOW() )"); 

Still not working, this all all rather odd?

You aren't escaping any data. In all likelihood, your data is messing up the rest of your query. It's also very likely that you are wide open to SQL injection. At a minimum, you should be using mysql_real_escape_string() , but it would be better to use prepared queries with PDO .

If the field is of type TIMESTAMP

try

$this->db->query("INSERT INTO orders VALUES (null, '$id', '$this->basket_lines', '$this->total', CURRENT_TIMESTAMP() )");

I don't see anything wrong with the query itself.

However I would like to advise you to read these 2 links.
http://nl.php.net/manual/en/book.pdo.php
http://nl3.php.net/manual/en/function.mysql-real-escape-string.php
The way you're using mysql is a HUGE security risk.

You got the escaping concept wrong, you need to escape the data you will insert in DB, to prevent SQL injection, not the whole query: So you should do something like:

$id=$this->mysqli->real_escape_string($id);
$basketlines=$this->mysqli->real_escape_string($this->basket_lines);
$total=$this->mysqli->real_escape_string($this->total);   
$SQL="INSERT INTO orders VALUES (null, '$id', '$basketlines', '$total', NOW() )");
$this->result = $this->mysqli->query($SQL);

I am pretty sure that all your problem is because when escaping the whole query, then query becomes malformed and not a valid SQL query anymore.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM