Jump to content

Todays date NOW() function in PHP


payney

Recommended Posts

Hi all, this is my first post. Its a pretty simple question which I have googled but cant find the answer to. I simply want to add todays date when inserting into MYSQL.

 

  $query = "insert INTO home_page (title, content, date) ";

  $query = $query . " VALUES ('$title',$content, NOW()) ";

 

I keep getting the error:

 

Call to undefined function showerror().......

 

Thanks

 

P

Link to comment
Share on other sites

   $query = "insert INTO home_page (title, content, date) ";
   $query = $query . " VALUES ('$title',$content, NOW()) "; 

 

Does this NOW() works, i doubt it. IT should be date();, you can store the date() value in a variable and save it.

 

You are getting error in showerror() this function. This function is not included i think....

Link to comment
Share on other sites

Thanks for the speedy response. Here is the full code.

 

PS: I can insert ok if i remove the date bit.

 

<?php

  require ('db.inc');

$title = $_POST["title"];

  $content = $_POST["content"];

 

if (!($connection = @ mysql_pconnect($hostname, $username, $password)))

    die("Could not connect to database");

 

  if (!mysql_select_db($databaseName, $connection))

    showerror(); 

 

  $query = "insert INTO home_page (title, content, date) ";

  $query = $query . " VALUES ('$title',$content, NOW()) ";      

 

 

  if (!(@ mysql_query ($query, $connection)))

    showerror(); 

 

 

?>

 

Link to comment
Share on other sites

n~ link=topic=162053.msg709118#msg709118 date=1191514850]

   $query = "insert INTO home_page (title, content, date) ";
   $query = $query . " VALUES ('$title',$content, NOW()) "; 

 

Does this NOW() works, i doubt it. IT should be date();, you can store the date() value in a variable and save it.

 

You are getting error in showerror() this function. This function is not included i think....

NOW() is perfectly valid.

 

http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_now

Link to comment
Share on other sites

Thanks for the speedy response. Here is the full code.

 

PS: I can insert ok if i remove the date bit.

 

<?php

  require ('db.inc');

$title = $_POST["title"];

   $content = $_POST["content"];

 

if (!($connection = @ mysql_pconnect($hostname, $username, $password)))

     die("Could not connect to database");

 

  if (!mysql_select_db($databaseName, $connection))

     showerror();   

   

   $query = "insert INTO home_page (title, content, date) ";

   $query = $query . " VALUES ('$title',$content, NOW()) ";      

   

 

  if (!(@ mysql_query ($query, $connection)))

     showerror();   

 

 

?>

 

PHP doesn't recognize that function.  It's not in the PHP manual either.

Link to comment
Share on other sites

 

mysql> SELECT NOW();

        -> '1997-12-15 23:50:26'

mysql> SELECT NOW() + 0;

        -> 19971215235026

 

This is for MYSQL , I am talking in php

 

In php

$mydate = NOW(); 
echo $mydate;

 

It does not work.

But try this,

<?php
  require ('db.inc');
      $title = $_POST["title"];               
      $content = $_POST["content"];   
  $cur_date = date();
  

	if (!($connection = mysql_connect($hostname, $username, $password)))
     die("Could not connect to database");

  if (!mysql_select_db($databaseName, $connection))
     echo "Error here";   
            
   $query = "insert INTO home_page (title, content, date) VALUES ('$title','$content','$cur_date')";
   //$query = $query . " VALUES ($title,$content, $cur_date)";             
   

  if (!(mysql_query($query, $connection)))
     echo "Error here";            


?>

Link to comment
Share on other sites

@ the OP

Let's start backwards and work our way into it.  Your error is Call to undefined function showerror(), which is a PHP error.  You are calling this function when your query fails, but it is not a built in function and you didn't write the actual function so PHP can not find it and creates an error.  To get rid of the PHP error, write a function:

  function showerror(){
    echo mysql_error();
  }

 

showerror() is only called when the query fails, so the next step is to determine why it is failing.  There are two possible reasons that it could fail.  The first depends on $content.  I highly suspect that $content should be enclosed within single quotes inside your query.  The second reason is your table contains a column named datedate is a reserved word in MySQL so you must enclose it in backticks (the unshifted key above the tab key on your keyboard).

Try replacing your query generating lines with this:

  $query = "insert INTO home_page (title, content, `date`) ";
             . " VALUES ('$title','$content', NOW()) "; 

 

Two general comments about your code.  If you're doing many concatenations on a string variable its slightly more efficient to do so the way I have written in the fixed query.  The reason is because every line below the first contains as much of the string as possible and since there is no assignment except for the first line, it is slightly easier to read that all of it is happening to the variable on the first line.  The second is that you have if statements with no curly braces; I know that they are optional if the body of the statement is a single line, but I highly recommend always using them, as well as with loops.

 

@ ~n[EO]n~

Does this NOW() works, i doubt it. IT should be date();, you can store the date() value in a variable and save it.

The OP was placing the call to NOW() as part of his query, not as part of his PHP code.  What he was doing was perfectly valid and also the recommended method.  You should always strive to place as much of the work as possible on the database engine.  Why bother with creating extra PHP to generate the time, assign it to a variable, and then insert that into the query when you can just write NOW() inside the query where the PHP-generated date would have appeared?

 

@ both of you

Neither of you cleaned your data with mysql_real_escape_string() so both sets of code are vulnerable to database attacks.

 

Also, be consistent with your capitalization in your MySQL, it just makes it easier to read.

Link to comment
Share on other sites

The OP was placing the call to NOW() as part of his query, not as part of his PHP code.  What he was doing was perfectly valid and also the recommended method.  You should always strive to place as much of the work as possible on the database engine.  Why bother with creating extra PHP to generate the time, assign it to a variable, and then insert that into the query when you can just write NOW() inside the query where the PHP-generated date would have appeared?

 

If you had never told, I would have never known  ;D, . One more question if we used NOW() as done by payney in the query itself we can't format the date as we want right (or can we) ???

Link to comment
Share on other sites

One more question if we used NOW() as done by payney in the query itself we can't format the date as we want right (or can we)

DATE fields in MySQL are stored as 'YYYY-MM-DD'.  Any time you insert into one of these fields MySQL will try and coerce the value you're inserting into that format.  If it can do so, it will.  If it can not, it will use NULL or '0000-00-00'.  So the end result doesn't matter if you use PHP's date() function to create and format it or MySQL's NOW() function; in both cases the date appears in the same format, 'YYYY-MM-DD'.

 

Many PHP programmer's, especially beginners, will extract the date from the DB just as it appears and then use PHP's functions to format it.  Some people will use multiple calls to substr or explode to break the date string down into the individual parts and then create a timestamp with PHP's mktime function.  A more efficient method in PHP is to just use strtotime().

 

The best method that thorpe hinted at but didn't elaborate on, is to use another MySQL function DATE_FORMAT():

http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_date-format

 

Let's say that you are extracting the date and want to display it as a more readable format.

  SELECT DATE_FORMAT(dateCol, '%b. %D,  %Y') AS `dateCol_disp`
  FROM myTable WHERE ...

What this will do is format the column dateCol to something like Jan. 1st, 2007.  Now you don't have to do any formatting in your PHP!  While looping over the result set you can just say echo $row['dateCol_disp'].  Notice how the name referred to the column in PHP is the one in the query where it says AS alias.  Whenever you return an aliased column, I recommend giving it a name that is not used by any of the columns in any of the tables in the query; it is not necessary to do so, but it helps avoid difficult to find bugs in the WHERE and ORDER BY parts of a query.

 

MySQL also has other functions to extract just parts of a date, such as the year or month; they are listed on the same page as the DATE_FORMAT() function I linked you to.

Link to comment
Share on other sites

I cant seem to get my head around this.

 

All I want to do is insert todays date and time into an insert statement.

 

So, I should do the following, minus db connection etc:

 

 

$cur_date = date("Y-m-d T"); // But I am sure this will remove the time part of the format? So what is date_time?

 

$query = "insert INTO home_page (title, content, date_posted) VALUES ('$title','$content','$cur_date')"; 

 

 

This works and inserts just the date, I also need time.

 

Also, how the hell do you work with NOW()? Do you have an example peice of code etc?

 

Thanks guys

Link to comment
Share on other sites

$today = date("F j, Y, g:i a");                 // October 5, 2007, 3:13 pm
it will come in this format 

see the php date and time function in www.php.net

 

and for NOW() see the link given by Thorpe

 

<?php
// Assuming today is: March 10th, 2001, 5:16:18 pm

$today = date("F j, Y, g:i a");                 // March 10, 2001, 5:16 pm
$today = date("m.d.y");                         // 03.10.01
$today = date("j, n, Y");                       // 10, 3, 2001
$today = date("Ymd");                           // 20010310
$today = date('h-i-s, j-m-y, it is w Day z ');  // 05-16-17, 10-03-01, 1631 1618 6 Fripm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.');   // It is the 10th day.
$today = date("D M j G:i:s T Y");               // Sat Mar 10 15:16:08 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h');     // 17:03:17 m is month
$today = date("H:i:s");                         // 17:16:17
?> 

Link to comment
Share on other sites

payney, I gave you an example of how to use the NOW() function, but here it is again:

 

 

$query = "insert INTO home_page (title, content, `date`) ";
             . " VALUES ('$title','$content', NOW()) "; 

 

NOW() is a MySQL function, which means you can't call it in PHP.  In other words, PHP doesn't execute NOW().

 

You place NOW() in your query just as if it were any other value, except you don't put it inside single quotes.  Basically, your final query has to look like this:

  INSERT INTO table (datetime_column) VALUES (NOW())

 

MySQL sees NOW() and replaces the function call with the actual time and uses that value.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.