Foros del Web » Programando para Internet » PHP »

Problemas con fecha y autor

Estas en el tema de Problemas con fecha y autor en el foro de PHP en Foros del Web. Hola intento explicr el problema Tengo un pequeño foro donde tengo Categoria 1 ( Tema 1, Tema 2 ) Lo que en verdad busco es ...
  #1 (permalink)  
Antiguo 04/01/2013, 13:59
 
Fecha de Ingreso: agosto-2011
Mensajes: 165
Antigüedad: 12 años, 8 meses
Puntos: 1
Problemas con fecha y autor

Hola intento explicr el problema

Tengo un pequeño foro donde tengo

Categoria 1 ( Tema 1, Tema 2 )
Lo que en verdad busco es el ultimo posteo de mensajes
Entro como administrador y pongo en la categoria 1 tema 1 un mensaje
me sale la fecha y autor todo bien.
pongo un segundo en la categoria 1 tema 2 y bien me saca fecha y autor.

Pero ahora cambio el usuario y entro.
categoria 1 tema 1 pongo un mensaje y lo insecta pero con la misma hora que el anterior y por eso no me cambia el autor.

<?php
mysql_select_db($database_libre, $libre);
$publicacion_sql = "SELECT mensaje FROM mensajes WHERE categoria = " .
$row_categorias['id_categoria'];
$ultimo_sql = "SELECT autor,fecha FROM mensajes WHERE categoria = " .
$row_categorias['id_categoria'] . " ORDER BY fecha DESC LIMIT 1";
$uPost = mysql_query($ultimo_sql) or die(mysql_error ());
$pTotales = mysql_query($publicacion_sql) or die(mysql_error());

<td align="center" class="centro3"><?php echo mysql_num_rows($pTotales);?></td>
<td align="center"><?php $up = mysql_fetch_assoc($uPost);
echo $up {'fecha'};
echo '<br/>';
echo $up {'autor'};?></td>

Sabeis algo de esto
?>
  #2 (permalink)  
Antiguo 04/01/2013, 14:40
Avatar de Triby
Mod on free time
 
Fecha de Ingreso: agosto-2008
Ubicación: $MX->Gto['León'];
Mensajes: 10.106
Antigüedad: 15 años, 8 meses
Puntos: 2237
Respuesta: Problemas con fecha y autor

Te inserta con la misma hora del anterior?, entonces es más útil el código del INSERT, porque el SELECT no sirve de mucho.

Usa la herramienta highlight para mostrar tu código, queda más legible.

Por cierto, para aligerar la carga de consultas en el foro es más recomendable tener en la tabla de categorías campos para último tema (con autor y fecha), así como último mensaje (con autor y fecha).

Sugiero que descargues algún prefabricado de foros como PhpBB, FluxBB u otro para que veas la estructura de tablas y el funcionamiento general, eso te ayudará a mejorar el tuyo.
__________________
- León, Guanajuato
- GV-Foto
  #3 (permalink)  
Antiguo 04/01/2013, 15:14
 
Fecha de Ingreso: agosto-2011
Mensajes: 165
Antigüedad: 12 años, 8 meses
Puntos: 1
Respuesta: Problemas con fecha y autor

Te inserta con la misma hora del anterior?, SIIIIIIII
entonces es más útil el código del INSERT, porque el SELECT no sirve de mucho.

Insect de la pagina publicaciones donde sube el mensaje a la tabla

Código PHP:
<form action="<?php echo $editFormAction?>" method="post" name="form1" id="form1">
        <table width="93%" align="center">
          <tr valign="baseline">
            <td nowrap="nowrap" align="right">Mensaje:</td>
            <td><textarea name="mensaje" cols="80" rows="10"></textarea></td>
          </tr>
          <tr valign="baseline">
            <td nowrap="nowrap" align="right">&nbsp;</td>
            <td><a href="acceso.php?nombre_user=<?php echo $row_usuarios['nombre_user']; ?>&amp;id_categoria=<?php echo $row_categorias['id_categoria']; ?>&amp;id_tema=<?php echo $row_temas['id_tema']; ?>">
              <input type="submit" class="rojo" value="Publicar Mensaje" />
            </a></td>
          </tr>
        </table>
        <input type="hidden" name="categoria" value="<?php echo $row_categorias['id_categoria']; ?>" />
        <input type="hidden" name="tema" value="<?php echo $row_temas['id_tema']; ?>" />
        <input type="hidden" name="autor" value="<?php echo $row_usuarios['nombre_user']; ?>" />
        <input type="hidden" name="fecha" value="<?php echo $row_mensajes['fecha']; ?>" />
        <input type="hidden" name="MM_insert" value="form1" />
      </form>
 
Usa la herramienta highlight para mostrar tu código, queda más legible
Espero haber insectado bien lo del codigo
  #4 (permalink)  
Antiguo 04/01/2013, 18:51
Avatar de Triby
Mod on free time
 
Fecha de Ingreso: agosto-2008
Ubicación: $MX->Gto['León'];
Mensajes: 10.106
Antigüedad: 15 años, 8 meses
Puntos: 2237
Respuesta: Problemas con fecha y autor

Lo del código en el highlight está bien, pero eso es el formulario y lo que necesitamos ver es cómo lo procesas e insertas la información en la base de datos.
__________________
- León, Guanajuato
- GV-Foto
  #5 (permalink)  
Antiguo 05/01/2013, 04:44
 
Fecha de Ingreso: agosto-2011
Mensajes: 165
Antigüedad: 12 años, 8 meses
Puntos: 1
Respuesta: Problemas con fecha y autor

Cita:
Iniciado por Triby Ver Mensaje
Lo del código en el highlight está bien, pero eso es el formulario y lo que necesitamos ver es cómo lo procesas e insertas la información en la base de datos.
Todo el codigo de la pagina

Código PHP:

<?php
if (!function_exists("GetSQLValueString")) {
function 
GetSQLValueString($theValue$theType$theDefinedValue ""$theNotDefinedValue ""
{
  if (
PHP_VERSION 6) {
    
$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_update"])) && ($_POST["MM_update"] == "form1")) {
  
$updateSQL sprintf("UPDATE mensajes SET mensaje=%s, categoria=%s, tema=%s, autor=%s, fecha=%s WHERE id_mensaje=%s",
                       
GetSQLValueString($_POST['mensaje'], "text"),
                       
GetSQLValueString($_POST['categoria'], "int"),
                       
GetSQLValueString($_POST['tema'], "int"),
                       
GetSQLValueString($_POST['autor'], "text"),
                       
GetSQLValueString($_POST['fecha'], "date"),
                       
GetSQLValueString($_POST['id_mensaje'], "int"));

  
mysql_select_db($database_libre$libre);
  
$Result1 mysql_query($updateSQL$libre) or die(mysql_error());

  
$updateGoTo "pulicaciones.php";
  if (isset(
$_SERVER['QUERY_STRING'])) {
    
$updateGoTo .= (strpos($updateGoTo'?')) ? "&" "?";
    
$updateGoTo .= $_SERVER['QUERY_STRING'];
  }
  
header(sprintf("Location: %s"$updateGoTo));
}

if ((isset(
$_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
  
$insertSQL sprintf("INSERT INTO mensajes (mensaje, categoria, tema, autor, fecha) VALUES (%s, %s, %s, %s, %s)",
                       
GetSQLValueString($_POST['mensaje'], "text"),
                       
GetSQLValueString($_POST['categoria'], "int"),
                       
GetSQLValueString($_POST['tema'], "int"),
                       
GetSQLValueString($_POST['autor'], "text"),
                       
GetSQLValueString($_POST['fecha'], "date"));

  
mysql_select_db($database_libre$libre);
  
$Result1 mysql_query($insertSQL$libre) or die(mysql_error());

  
$insertGoTo "acceso.php";
  if (isset(
$_SERVER['QUERY_STRING'])) {
    
$insertGoTo .= (strpos($insertGoTo'?')) ? "&" "?";
    
$insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  
header(sprintf("Location: %s"$insertGoTo));
}

$colname_mensajes "-1";
if (isset(
$_GET['id_tema'])) {
  
$colname_mensajes $_GET['id_tema'];
}
mysql_select_db($database_libre$libre);
$query_mensajes sprintf("SELECT * FROM mensajes WHERE tema = %s"GetSQLValueString($colname_mensajes"int"));
$mensajes mysql_query($query_mensajes$libre) or die(mysql_error());
$row_mensajes mysql_fetch_assoc($mensajes);

$colname_usuarios "-1";
if (isset(
$_GET['nombre_user'])) {
  
$colname_usuarios $_GET['nombre_user'];
}
mysql_select_db($database_libre$libre);
$query_usuarios sprintf("SELECT * FROM libre WHERE nombre_user = %s"GetSQLValueString($colname_usuarios"text"));
$usuarios mysql_query($query_usuarios$libre) or die(mysql_error());
$row_usuarios mysql_fetch_assoc($usuarios);
$totalRows_usuarios mysql_num_rows($usuarios);

$colname_mensajes "-1";
if (isset(
$_GET['id_tema'])) {
  
$colname_mensajes $_GET['id_tema'];
}
mysql_select_db($database_libre$libre);
$query_mensajes sprintf("SELECT * FROM mensajes WHERE tema = %s ORDER BY id_mensaje DESC"GetSQLValueString($colname_mensajes"int"));
$mensajes mysql_query($query_mensajes$libre) or die(mysql_error());
$row_mensajes mysql_fetch_assoc($mensajes);
$totalRows_mensajes mysql_num_rows($mensajes);

$colname_temas "-1";
if (isset(
$_GET['id_tema'])) {
  
$colname_temas $_GET['id_tema'];
}
mysql_select_db($database_libre$libre);
$query_temas sprintf("SELECT * FROM temas WHERE id_tema = %s ORDER BY id_tema ASC"GetSQLValueString($colname_temas"int"));
$temas mysql_query($query_temas$libre) or die(mysql_error());
$row_temas mysql_fetch_assoc($temas);
$totalRows_temas mysql_num_rows($temas);

$colname_categorias "-1";
if (isset(
$_GET['id_categoria'])) {
  
$colname_categorias $_GET['id_categoria'];
}
mysql_select_db($database_libre$libre);
$query_categorias sprintf("SELECT * FROM categorias WHERE id_categoria = %s"GetSQLValueString($colname_categorias"int"));
$categorias mysql_query($query_categorias$libre) or die(mysql_error());
$row_categorias mysql_fetch_assoc($categorias);
$totalRows_categorias mysql_num_rows($categorias);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><!-- InstanceBegin template="/Templates/base.dwt.php" codeOutsideHTMLIsLocked="false" -->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- InstanceBeginEditable name="doctitle" -->
<title>Mensajes publicaciones</title>
<!-- InstanceEndEditable -->
<link href="tables.css" rel="stylesheet" type="text/css" />
<!-- InstanceBeginEditable name="head" -->
<!-- InstanceEndEditable -->
<style type="text/css">
body {
    background-image: url();
    background-color: #D3E4E5;
}
.centro {
    text-align: center;
}
irq {
    text-align: left;
}
</style>
</head>

<body bgcolor="#D3E4E5">
<table width="54" border="0" align="center" cellpadding="3" cellspacing="0">
  <tr>
    <td align="center" valign="middle" class="centro"><img src="imagen/logo_final_.jpg" width="877" height="195" align="middle" /><Marquee  style="font-size: 16px; color:#000" 
bgcolor="#B6C34F"  >
    </Marquee>      <br /></td>
  </tr>
  <tr>
    <td><!-- InstanceBeginEditable name="panel de control" -->
      <table width="60%" border="0" align="center" cellpadding="3" cellspacing="0">
        <tr>
          <td class="centro">Publicaciones del foro</td>
        </tr>
      </table>
      <p><a href="acceso.php">Ir a Panel de Control</a></p>
      <form action="<?php echo $editFormAction?>" method="post" name="form1" id="form1">
        <table width="93%" align="center">
          <tr valign="baseline">
            <td nowrap="nowrap" align="right">Mensaje:</td>
            <td><textarea name="mensaje" cols="80" rows="10"></textarea></td>
          </tr>
          <tr valign="baseline">
            <td nowrap="nowrap" align="right">&nbsp;</td>
            <td><a href="acceso.php?nombre_user=<?php echo $row_usuarios['nombre_user']; ?>&amp;id_categoria=<?php echo $row_categorias['id_categoria']; ?>&amp;id_tema=<?php echo $row_temas['id_tema']; ?>">
              <input type="submit" class="rojo" value="Publicar Mensaje" />
            </a></td>
          </tr>
        </table>
        <input type="hidden" name="categoria" value="<?php echo $row_categorias['id_categoria']; ?>" />
        <input type="hidden" name="tema" value="<?php echo $row_temas['id_tema']; ?>" />
        <input type="hidden" name="autor" value="<?php echo $row_usuarios['nombre_user']; ?>" />
        <input type="hidden" name="fecha" value="<?php echo $row_mensajes['fecha']; ?>" />
        <input type="hidden" name="MM_insert" value="form1" />
      </form>
      <p></p>
<p></p>
<?php if ($totalRows_mensajes 0) { // Show if recordset not empty ?>
  <table width="93%" border="0" align="center" cellpadding="3" cellspacing="0">
    <tr class="negro">
      <td width="53%">Mensajes del foro:</td>
      <td width="20%">Autor del Mensaje</td>
      <td width="27%">Fecha</td>
    </tr>
    <?php do { ?>
      <tr class="fer">
        <td class="irz"><?php echo $row_mensajes['mensaje']; ?>
          <?php if($_SESSION['MM_UserGroup']=="admin"){
                            
?>
          <a href="editar_mensajes.php?nombre_user=<?php echo $row_usuarios['nombre_user']; ?>&amp;mensaje=<?php echo $row_mensajes['mensaje']; ?>">Editar</a><a href="borrar_confirma_tema.php?nombre_user=<?php echo $row_usuarios['nombre_user']; ?>">
<?php  }   ?>
<?php 
if($_SESSION['MM_UserGroup']=="admin"){
                            
?>
</a><a href="borrar_confirma_mensaje.php?nombre_user=<?php echo $row_usuarios['nombre_user']; ?>&amp;mensaje=<?php echo $row_mensajes['mensaje']; ?>">Eliminar</a><a href="borrar_confirma_tema.php?nombre_user=<?php echo $row_usuarios['nombre_user']; ?>">
<?php  }   ?>
</a></td>
        <td><a href="perfil_usuario.php?autor=<?php echo $row_mensajes['autor']; ?>"><?php echo $row_mensajes['autor']; ?></a></td>
        <td align="center"><?php echo $row_mensajes['fecha']; ?></td>
      </tr>
      <?php } while ($row_mensajes mysql_fetch_assoc($mensajes)); ?>
  </table>
  <?php // Show if recordset not empty ?>
<p></p>
<p></p>
    <!-- InstanceEndEditable --></td>
  </tr>
</table>
</body>
<!-- InstanceEnd --></html>
<?php
mysql_free_result
($usuarios);

mysql_free_result($mensajes);

mysql_free_result($temas);

mysql_free_result($categorias);
?>
  #6 (permalink)  
Antiguo 05/01/2013, 13:01
Avatar de Triby
Mod on free time
 
Fecha de Ingreso: agosto-2008
Ubicación: $MX->Gto['León'];
Mensajes: 10.106
Antigüedad: 15 años, 8 meses
Puntos: 2237
Respuesta: Problemas con fecha y autor

Código PHP:
Ver original
  1. /* ... */
  2. GetSQLValueString($_POST['fecha'], "date"));

Estás pasando la fecha por $_POST?, deberías asignarla directamente con date() y el formato adecuado para el tipo de campo en tu tabla.
__________________
- León, Guanajuato
- GV-Foto
  #7 (permalink)  
Antiguo 06/01/2013, 05:02
 
Fecha de Ingreso: agosto-2011
Mensajes: 165
Antigüedad: 12 años, 8 meses
Puntos: 1
Respuesta: Problemas con fecha y autor

Como! me podrias poner un ejemplo
  #8 (permalink)  
Antiguo 06/01/2013, 14:31
Avatar de Triby
Mod on free time
 
Fecha de Ingreso: agosto-2008
Ubicación: $MX->Gto['León'];
Mensajes: 10.106
Antigüedad: 15 años, 8 meses
Puntos: 2237
Respuesta: Problemas con fecha y autor

Busca en el manual de la función date() y encontrarás ejemplos, seguramente alguno está ya con el formato adecuado para insertar en la tabla, y quedaría algo como:

Código PHP:
Ver original
  1. /* ... */
  2. GetSQLValueString(date(/* Aquí el formato adecuado */), "date"));
__________________
- León, Guanajuato
- GV-Foto

Etiquetas: autor, fecha, mysql, sql, usuarios
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 09:53.