0

I am currently learning OOP, but I can't figure out how to insert date into database. I have tried:

$time=date('now');
$time=date("timestamp");
$time=date("Y-m-d H:i:s");
$time=date("m/d/y g:i A");

When I submit I get 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 '2014-03-11 14:18:07'' at line 1

I can't figure this out. Before I did use:

$result = mysql_query ("INSERT INTO test (title,url,time) VALUES ('$title','$url',now())");

I tried to use now() , but it does not seem to work. :/

Update:

Insert:

public function insert($cat,$title,$article,$author,$image,$time)
{
    $sql=mysql_query("INSERT INTO blog_posts(cat, title, article, time, author, image) VALUES('$cat', '$title', '$article', '$author', '$image, '$time'");
    if(!$sql)
    {
        echo mysql_error();
    }
}

proccess file:

  $cat=$_POST['cat'];
    $title=$_POST['title'];
    $article= $_POST['article'];
    $author=$_POST['author'];
    $image=$_POST['image'];
    $time= date( 'Y-m-d H:i:s' );

    $n=new db();
    $n->connect();
    $n->insert($cat,$title,$article,$author,$image,$time);
John Conde
  • 217,595
  • 99
  • 455
  • 496
MeChris
  • 717
  • 1
  • 7
  • 11

3 Answers3

1

You're missing a quote:

'$author', '$image, '$time'"
               ^^^^^
                HERE

INSERT INTO blog_posts(cat, title, article, time, author, image) VALUES('$cat', '$title', '$article', '$author', '$image', '$time'"

Your parameters are also out of order.

Columns: cat, title, article, time, author, image
Values: '$cat', '$title', '$article', '$author', '$image', '$time'
John Conde
  • 217,595
  • 99
  • 455
  • 496
0

Forget about the mysql_* functions.

If you want to create future-proof applications you will use PDO. This is OOP.

$db = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
$db->exec('SET NAMES utf8'); // Set this transfer's charset to utf-8

$title = 'here is a title';
$url = 'here is a URL';
$time= date( 'Y-m-d H:i:s' ); // I dont know what type the time column is. (date, datetime, timestamp)-> ??

$prepare = $db->prepare("INSERT INTO test (title, url, time) VALUES (:title, :url, :time)");
$prepare->bindParam(':title', $title);
$prepare->bindParam(':url', $url);
$prepare->bindParam(':time', $time);

$prepare->execute(); // Run the query, in this case, insert!

If the time column is of type date or datetime, you can use NOW() or CURDATE() like so:

$prepare = $db->prepare("INSERT INTO test (title, url, time) VALUES (:title, :url, NOW())");
Gilly
  • 9,212
  • 5
  • 33
  • 36
-1

theres nothing to do with objects in this code.

and the first snippet of code is bascily overwriting all over so its left with the latest. what exactly are you trying to achieve? could you post some more of your code?

if you wish to use mysql OBJECT oriented, use MySQLi or PDO driver.

bountyh
  • 165
  • 9