Foros del Web » Programando para Internet » PHP »

Guardar fecha actual en campo

Estas en el tema de Guardar fecha actual en campo en el foro de PHP en Foros del Web. Hola a todos. He realizado un formulario donde guardo unos registros y me anda bien. El problema es que necesito capturar la fecha actual y ...
  #1 (permalink)  
Antiguo 24/07/2012, 23:47
 
Fecha de Ingreso: julio-2012
Mensajes: 51
Antigüedad: 11 años, 9 meses
Puntos: 0
Guardar fecha actual en campo

Hola a todos.

He realizado un formulario donde guardo unos registros y me anda bien. El problema es que necesito capturar la fecha actual y hora del sistema y que me aparezca en el campo de texto FechaEnvio automaticamente y que el usuario no pueda modificarlo para poder ser ingresado a la base de datos. me podrian ayudar con este paso? o hay otro metodo de enviar la fecha y hora actual por medio del formulario cuando se le haga clic? muchas gracias.

Dejo el codigo de lo que estoy haciendo. Gracias

Código PHP:
<?php require_once('../../../../Connections/conex.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function 
GetSQLValueString($theValue$theType$theDefinedValue ""$theNotDefinedValue ""
{
  
$theValue get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

  
$theValue function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch (
$theType) {
    case 
"text":
      
$theValue = ($theValue != "") ? "'" $theValue "'" "NULL";
      break;    
    case 
"long":
    case 
"int":
      
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case 
"double":
      
$theValue = ($theValue != "") ? "'" doubleval($theValue) . "'" "NULL";
      break;
    case 
"date":
      
$theValue = ($theValue != "") ? "'" $theValue "'" "NULL";
      break;
    case 
"defined":
      
$theValue = ($theValue != "") ? $theDefinedValue $theNotDefinedValue;
      break;
  }
  return 
$theValue;
}
}

$editFormAction $_SERVER['PHP_SELF'];
if (isset(
$_SERVER['QUERY_STRING'])) {
  
$editFormAction .= "?" htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset(
$_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
  
$insertSQL sprintf("INSERT INTO guia (FechaEnvio, Remitente, Destinatario, Prioridad, Destinos, TipoEnvio, Transporte, NomRemitente, MovilRemitente, EmailRemitente, NomDestino, MovilDestino, EmailDestino, FechaLlegada, ConfirmaRecepcion, EstadoEnvio, Observacion, Numero) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
                       
GetSQLValueString($_POST['FechaEnvio'], "date"),
                       
GetSQLValueString($_POST['Remitente'], "text"),
                       
GetSQLValueString($_POST['Destinatario'], "text"),
                       
GetSQLValueString($_POST['Prioridad'], "text"),
                       
GetSQLValueString($_POST['Destinos'], "text"),
                       
GetSQLValueString($_POST['TipoEnvio'], "text"),
                       
GetSQLValueString($_POST['Transporte'], "text"),
                       
GetSQLValueString($_POST['NomRemitente'], "text"),
                       
GetSQLValueString($_POST['MovilRemitente'], "text"),
                       
GetSQLValueString($_POST['EmailRemitente'], "text"),
                       
GetSQLValueString($_POST['NomDestino'], "text"),
                       
GetSQLValueString($_POST['MovilDestino'], "text"),
                       
GetSQLValueString($_POST['EmailDestino'], "text"),
                       
GetSQLValueString($_POST['FechaLlegada'], "date"),
                       
GetSQLValueString($_POST['ConfirmaRecepcion'], "text"),
                       
GetSQLValueString($_POST['EstadoEnvio'], "text"),
                       
GetSQLValueString($_POST['Observacion'], "text"),
                       
GetSQLValueString($_POST['Numero'], "text"));

  
mysql_select_db($database_conex$conex);
  
$Result1 mysql_query($insertSQL$conex) or die(mysql_error());
}
?>
<!DOCTYPE html >

<html>

<head>
    <title></title>
    <meta  charset="iso-8859-1" />
    <link href="../css/style.css" rel="stylesheet" type="text/css" />
    <!--[if IE 6]>
        <link href="css/ie6.css" rel="stylesheet" type="text/css" />
    <![endif]-->
    <!--[if IE 7]>
        <link href="css/ie7.css" rel="stylesheet" type="text/css" />  
    <![endif]-->
    <link href="../../../css/ie6.css" rel="stylesheet" type="text/css">
    <link href="../../../css/ie7.css" rel="stylesheet" type="text/css">
    <link href="../../../css/style.css" rel="stylesheet" type="text/css">
    <link href="../../css/style.css" rel="stylesheet" type="text/css">
    <style type="text/css">
<!--
.Estilo1 {
    font-size: 20px;
    font-weight: bold;
}
-->
    </style>
</head>

<body>


      <div id="background">
              <div id="page">
              
                     <div class="header">
                        <div class="footer">
                            <div class="body">
                              <div id="sidebar"><a href="../index.html"><img id="logo" src="../../../../images/logo.gif" with="154" height="74" alt="" title=""/></a>
<ul class="navigation">
                                                <li><a  href="../PanelAdministrador.php">Panel Admistrador</a><a  href="../PanelAdministrador.php"></a></li>
                                              <li ></li>
                                </ul>
                                        
                              </div>
<div id="content">
                                                <div class="content">
                                               <ul class="article">
                                                    <li>
                                                      <h2 align="right">Bienvenido: </h2>
                                                 </li>
                                                    
                                                    <li><?

$Fecha
date('Y-m-d');
$Horadate('H:i:s');


echo 
"Fecha: ".$Fecha;
echo 
"<br>";
echo 
"Hora: ".$Hora;


?> </li>
                                                    <li>
                                                      <form method="post" name="form1" action="<?php echo $editFormAction?>">
                                                        <table align="center">
                                                          <tr valign="baseline">
                                                            <td nowrap align="right">FechaEnvio:</td>
                                                            <td><input name="FechaEnvio" type="text" size="32"></td>
                                                          </tr>
                                                          <tr valign="baseline">
                                                            <td nowrap align="right">Remitente:</td>
                                                            <td><input type="text" name="Remitente" value="" size="32"></td>
                                                          </tr>
                                                          <tr valign="baseline">
                                                            <td nowrap align="right">Destinatario:</td>
                                                            <td><input type="text" name="Destinatario" value="" size="32"></td>
                                                          </tr>
                                                          <tr valign="baseline">
                                                            <td nowrap align="right">Prioridad:</td>
                                                            <td><input type="text" name="Prioridad" value="" size="32"></td>
                                                          </tr>
                                                          <tr valign="baseline">
                                                            <td nowrap align="right">Destinos:</td>
                                                            <td><input type="text" name="Destinos" value="" size="32"></td>
                                                          </tr>
                                                          <tr valign="baseline">
                                                            <td nowrap align="right">TipoEnvio:</td>
                                                            <td><input type="text" name="TipoEnvio" value="" size="32"></td>
                                                          </tr>
                                                          <tr valign="baseline">
                                                            <td nowrap align="right">Transporte:</td>
                                                            <td><input type="text" name="Transporte" value="" size="32"></td>
                                                          </tr>
                                                          <tr valign="baseline">
                                                            <td nowrap align="right">NomRemitente:</td>
                                                            <td><input type="text" name="NomRemitente" value="" size="32"></td>
                                                          </tr>
                                                          <tr valign="baseline">
                                                            <td nowrap align="right">&nbsp;</td>
                                                            <td><input type="submit" value="Insertar registro"></td>
                                                          </tr>
                                                        </table>
                                                        <input type="hidden" name="MM_insert" value="form1">
                                                      </form>
                                                      <p>&nbsp;</p>
                                                    </li>
                                                 <li><strong>Cerrar sesi&oacute;n </strong><strong><img src="../../../../images/Icons/Panel/Clave.png" alt="Cerrar Sesion" width="48" height="48"></strong></li>
                                                 <p>&nbsp;</p>
                                               </ul>
            </div>
                              </div>
                            </div>
                        </div>
                </div>
                     <div class="shadow">
                     </div>
              </div>    
      </div>    
    
</body>
</html>
  #2 (permalink)  
Antiguo 24/07/2012, 23:55
 
Fecha de Ingreso: enero-2011
Ubicación: DF
Mensajes: 898
Antigüedad: 13 años, 2 meses
Puntos: 155
Respuesta: Guardar fecha actual en campo

por que tipo texto ? no seria mejor datetime el campo?

http://dev.mysql.com/doc/refman/5.5/...l#function_now

cheka
http://www.php.net/manual/es/function.date.php

formatea la hora que necesitas guárdala en una variable e insertarla o si no pos directo
__________________
No me interesan ni las gracias ni los karmas , pero si que se genere conocimiento, si se dio con la respuesta por favor confirmalo
  #3 (permalink)  
Antiguo 25/07/2012, 00:08
 
Fecha de Ingreso: julio-2012
Mensajes: 51
Antigüedad: 11 años, 9 meses
Puntos: 0
Respuesta: Guardar fecha actual en campo

Cita:
Iniciado por mogurbon Ver Mensaje
por que tipo texto ? no seria mejor datetime el campo?

[url]http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_now[/url]

cheka
[url]http://www.php.net/manual/es/function.date.php[/url]

formatea la hora que necesitas guárdala en una variable e insertarla o si no pos directo

Muchas gracias por la respuesta, no claro como dices por que en campo de texto, si esolo tengo claro...solo que quiero es que aparezca la fecha actual y hora en un echo mientras lleno el formulario, pero cuando ya le de clic al boton de enviar el formulario para guardar en la base de datos tambien quiero que me guarde en ese instante junto con esos datos la fecha y hora, me hago entender? esto con el fin que el usuario no digite fecha y hora actual, gracias.
  #4 (permalink)  
Antiguo 25/07/2012, 00:54
 
Fecha de Ingreso: diciembre-2009
Mensajes: 125
Antigüedad: 14 años, 4 meses
Puntos: 7
Respuesta: Guardar fecha actual en campo

Puedes crear una variable con date y pasarla en el formulario como hidden, con valor el echo de dicha variable.

Saludos
  #5 (permalink)  
Antiguo 25/07/2012, 06:26
 
Fecha de Ingreso: julio-2012
Mensajes: 51
Antigüedad: 11 años, 9 meses
Puntos: 0
Respuesta: Guardar fecha actual en campo

Y como seria pasar la variable con hiden?, me explicar por favor. gracias.
  #6 (permalink)  
Antiguo 25/07/2012, 07:23
 
Fecha de Ingreso: enero-2011
Ubicación: DF
Mensajes: 898
Antigüedad: 13 años, 2 meses
Puntos: 155
Respuesta: Guardar fecha actual en campo

http://www.echoecho.com/htmlforms07.htm

aunque no lo veo como una buena idea, se pondria en el value del input hidden el valor de una fecha con una hora ya impreso, pero para cuando se mande probablemente el usuario ya se echo ahi una media hora llenando el formulario, por que se puso a yutubear sus pornochas
__________________
No me interesan ni las gracias ni los karmas , pero si que se genere conocimiento, si se dio con la respuesta por favor confirmalo
  #7 (permalink)  
Antiguo 25/07/2012, 10:37
 
Fecha de Ingreso: julio-2012
Mensajes: 51
Antigüedad: 11 años, 9 meses
Puntos: 0
Respuesta: Guardar fecha actual en campo

Bueno y si se pone un reloj en javasscript y se captura al momento de enviar el formulario la hora y fecha, se puede hacer? como? o hacer un reloj en php se podria?
  #8 (permalink)  
Antiguo 25/07/2012, 10:45
 
Fecha de Ingreso: julio-2012
Mensajes: 51
Antigüedad: 11 años, 9 meses
Puntos: 0
Respuesta: Guardar fecha actual en campo

Hola a todos ya tengo el codigo de un reloj con fecha en java script, ahora lo que necesito es capturar en el momento de hacer el submit o insertar datos a la base la fecha y hora que esta mmostrando, alguien me puede ayudar???

reloj java


Código PHP:
<html>
<head>
<title>el reloJ</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script language="JavaScript" type="text/JavaScript">
    var Hoy = new Date("<?php echo date("d M Y G:i:s");?>");
function Reloj(){ 
    Hora = Hoy.getHours() 
    Minutos = Hoy.getMinutes() 
    Segundos = Hoy.getSeconds() 
    if (Hora<=9) Hora = "0" + Hora 
    if (Minutos<=9) Minutos = "0" + Minutos 
    if (Segundos<=9) Segundos = "0" + Segundos 
    var Dia = new Array("Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo"); 
    var Mes = new Array("Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"); 
    var Anio = Hoy.getFullYear(); 
    var Fecha = Dia[Hoy.getDay()] + ", " + Hoy.getDate() + " de " + Mes[Hoy.getMonth()] + " de " + Anio + ", a las "; 
    var Inicio, Script, Final, Total 
    Inicio = "<font size=3 color=black>" 
    Script = Fecha + Hora + ":" + Minutos + ":" + Segundos 
    Final = "</font>" 
    Total = Inicio + Script + Final 
    document.getElementById('Fecha_Reloj').innerHTML = Total 
    Hoy.setSeconds(Hoy.getSeconds() +1)
    setTimeout("Reloj()",1000) 

</script>
</head>
<body onload="Reloj()">
<div id="Fecha_Reloj"></div>
</body>
</html>
  #9 (permalink)  
Antiguo 25/07/2012, 10:45
Avatar de jotaincubus  
Fecha de Ingreso: mayo-2005
Ubicación: Medellin - Colombia
Mensajes: 1.797
Antigüedad: 18 años, 10 meses
Puntos: 394
Respuesta: Guardar fecha actual en campo

No se porque tanta vuelta para algo tan simple...

Código PHP:
Ver original
  1. <input name="FechaEnvio" type="text" size="32" value="<?php echo date('Y-m-d H:i:s'); ?>" disabled="disabled">

o

Código PHP:
Ver original
  1. <input name="FechaEnvio" type="text" size="32" value="<?php echo date('Y-m-d H:i:s'); ?>" onFocus="blur()">
__________________
Por que existe gente que no agradece después de que se le ha brindado tiempo y ayuda ???
  #10 (permalink)  
Antiguo 25/07/2012, 10:49
 
Fecha de Ingreso: enero-2011
Ubicación: DF
Mensajes: 898
Antigüedad: 13 años, 2 meses
Puntos: 155
Respuesta: Guardar fecha actual en campo

mis propuestas: si el campo de la base de datos no es datetime

Código PHP:
Ver original
  1. <?
  2.  
  3. if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
  4.   $fecha=date("formato");
  5.   $insertSQL = sprintf("INSERT INTO guia (FechaEnvio, Remitente, Destinatario, Prioridad, Destinos, TipoEnvio, Transporte, NomRemitente, MovilRemitente, EmailRemitente, NomDestino, MovilDestino, EmailDestino, FechaLlegada, ConfirmaRecepcion, EstadoEnvio, Observacion, Numero) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
  6.                        GetSQLValueString($fecha, "date"),
  7.                        GetSQLValueString($_POST['Remitente'], "text"),
  8.                        GetSQLValueString($_POST['Destinatario'], "text"),
  9.                        GetSQLValueString($_POST['Prioridad'], "text"),
  10.                        GetSQLValueString($_POST['Destinos'], "text"),
  11.                        GetSQLValueString($_POST['TipoEnvio'], "text"),
  12.                        GetSQLValueString($_POST['Transporte'], "text"),
  13.                        GetSQLValueString($_POST['NomRemitente'], "text"),
  14.                        GetSQLValueString($_POST['MovilRemitente'], "text"),
  15.                        GetSQLValueString($_POST['EmailRemitente'], "text"),
  16.                        GetSQLValueString($_POST['NomDestino'], "text"),
  17.                        GetSQLValueString($_POST['MovilDestino'], "text"),
  18.                        GetSQLValueString($_POST['EmailDestino'], "text"),
  19.                        GetSQLValueString($_POST['FechaLlegada'], "date"),
  20.                        GetSQLValueString($_POST['ConfirmaRecepcion'], "text"),
  21.                        GetSQLValueString($_POST['EstadoEnvio'], "text"),
  22.                        GetSQLValueString($_POST['Observacion'], "text"),
  23.                        GetSQLValueString($_POST['Numero'], "text"));
  24.  
  25.   mysql_select_db($database_conex, $conex);
  26.   $Result1 = mysql_query($insertSQL, $conex) or die(mysql_error());
  27. }

si si es datetime

Código PHP:
Ver original
  1. if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
  2.   $fecha=date("formato");
  3.   $insertSQL = sprintf("INSERT INTO guia (FechaEnvio, Remitente, Destinatario, Prioridad, Destinos, TipoEnvio, Transporte, NomRemitente, MovilRemitente, EmailRemitente, NomDestino, MovilDestino, EmailDestino, FechaLlegada, ConfirmaRecepcion, EstadoEnvio, Observacion, Numero) VALUES (NOW(), %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
  4.                        GetSQLValueString($_POST['Remitente'], "text"),
  5.                        GetSQLValueString($_POST['Destinatario'], "text"),
  6.                        GetSQLValueString($_POST['Prioridad'], "text"),
  7.                        GetSQLValueString($_POST['Destinos'], "text"),
  8.                        GetSQLValueString($_POST['TipoEnvio'], "text"),
  9.                        GetSQLValueString($_POST['Transporte'], "text"),
  10.                        GetSQLValueString($_POST['NomRemitente'], "text"),
  11.                        GetSQLValueString($_POST['MovilRemitente'], "text"),
  12.                        GetSQLValueString($_POST['EmailRemitente'], "text"),
  13.                        GetSQLValueString($_POST['NomDestino'], "text"),
  14.                        GetSQLValueString($_POST['MovilDestino'], "text"),
  15.                        GetSQLValueString($_POST['EmailDestino'], "text"),
  16.                        GetSQLValueString($_POST['FechaLlegada'], "date"),
  17.                        GetSQLValueString($_POST['ConfirmaRecepcion'], "text"),
  18.                        GetSQLValueString($_POST['EstadoEnvio'], "text"),
  19.                        GetSQLValueString($_POST['Observacion'], "text"),
  20.                        GetSQLValueString($_POST['Numero'], "text"));
  21.  
  22.   mysql_select_db($database_conex, $conex);
  23.   $Result1 = mysql_query($insertSQL, $conex) or die(mysql_error());
  24. }

no le veo caso dar chance de capturar esa fecha , que tal si le pone el usuario una fecha distinta?
__________________
No me interesan ni las gracias ni los karmas , pero si que se genere conocimiento, si se dio con la respuesta por favor confirmalo
  #11 (permalink)  
Antiguo 25/07/2012, 10:52
 
Fecha de Ingreso: enero-2011
Ubicación: DF
Mensajes: 898
Antigüedad: 13 años, 2 meses
Puntos: 155
Respuesta: Guardar fecha actual en campo

Cita:
Iniciado por jotaincubus Ver Mensaje
No se porque tanta vuelta para algo tan simple...

Código PHP:
Ver original
  1. <input name="FechaEnvio" type="text" size="32" value="<?php echo date('Y-m-d H:i:s'); ?>" disabled="disabled">

o

Código PHP:
Ver original
  1. <input name="FechaEnvio" type="text" size="32" value="<?php echo date('Y-m-d H:i:s'); ?>" onFocus="blur()">
que onda si se tarda 15 mins en llenar todo el formulario? la hora de ese input sera retrasada , opino que se necesitaria agregar un valor al input de Fechainput obtenido por medio de ajax con la fecha en el momento de hacer el submit , si se quisiera hacer de esta forma pero se me hace complicarse la vida
__________________
No me interesan ni las gracias ni los karmas , pero si que se genere conocimiento, si se dio con la respuesta por favor confirmalo
  #12 (permalink)  
Antiguo 25/07/2012, 10:52
Avatar de jotaincubus  
Fecha de Ingreso: mayo-2005
Ubicación: Medellin - Colombia
Mensajes: 1.797
Antigüedad: 18 años, 10 meses
Puntos: 394
Respuesta: Guardar fecha actual en campo

Cita:
Iniciado por jotaincubus Ver Mensaje
No se porque tanta vuelta para algo tan simple...

Código PHP:
Ver original
  1. <input name="FechaEnvio" type="text" size="32" value="<?php echo date('Y-m-d H:i:s'); ?>" disabled="disabled">

o

Código PHP:
Ver original
  1. <input name="FechaEnvio" type="text" size="32" value="<?php echo date('Y-m-d H:i:s'); ?>" onFocus="blur()">

Edit: El único problema con el código anterior es que el usuario llene el FORM se vaya a tomar café vuelva en 8 horas y presione submit. Si quiere ser mas exacto puede crear una variable con la HORA después de verificar si se presiono el submit.
__________________
Por que existe gente que no agradece después de que se le ha brindado tiempo y ayuda ???

Etiquetas: actual, fecha, formulario, html, mysql, registro, sql, usuarios, campos
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 07:21.