Foros del Web » Programando para Internet » PHP »

Contador para fotos vistas

Estas en el tema de Contador para fotos vistas en el foro de PHP en Foros del Web. Hola amigos, muy buen foro, felicidades y esperon me hagan el favor de ayudar. En algunas Galerías de Fotos he visto que aparece, debajo de ...
  #1 (permalink)  
Antiguo 27/10/2008, 16:20
 
Fecha de Ingreso: octubre-2008
Mensajes: 165
Antigüedad: 15 años, 6 meses
Puntos: 12
Contador para fotos vistas

Hola amigos, muy buen foro, felicidades y esperon me hagan el favor de ayudar.

En algunas Galerías de Fotos he visto que aparece, debajo de una foto el siguiente texto:
Esta foto ha sido vista 35 veces
por ejemplo.

¿Cómo puedo hacer un script en PHP y MySQL para que me vaya contando esas visitas y las guarde en la Base de Datos?

Gracias por leer mi post y colaborarme.
  #2 (permalink)  
Antiguo 27/10/2008, 16:30
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 11 meses
Puntos: 2135
Respuesta: Contador para fotos vistas

Hola disweb,

Necesitas poner un campo en tu tabla que se llame visitas, luego al abrir la foto haces un update sencillo algo así:
Código sql:
Ver original
  1. UPDATE `fotos` SET `visitas`=`visitas`+1 WHERE `idFoto`=1

Saludos.
  #3 (permalink)  
Antiguo 27/10/2008, 19:07
 
Fecha de Ingreso: octubre-2008
Mensajes: 165
Antigüedad: 15 años, 6 meses
Puntos: 12
Respuesta: Contador para fotos vistas

Gracias GatorV, en este momento voy a probarlo, a ver si lo hago funcionar.
  #4 (permalink)  
Antiguo 27/10/2008, 19:29
 
Fecha de Ingreso: octubre-2008
Mensajes: 165
Antigüedad: 15 años, 6 meses
Puntos: 12
Respuesta: Contador para fotos vistas

No hallo la forma de meter el contador, ni en dónde, mi código php es:

Código:
<?php require_once('Connections/Carrito1.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;
}
}

$colname_detalle = "-1";
if (isset($_GET['foto_id'])) {
  $colname_detalle = $_GET['foto_id'];
}
mysql_select_db($database_Carrito1, $Carrito1);
$query_detalle = sprintf("SELECT * FROM fotos_mias WHERE foto_id = %s", GetSQLValueString($colname_detalle, "int"));
$detalle = mysql_query($query_detalle, $Carrito1) or die(mysql_error());
$row_detalle = mysql_fetch_assoc($detalle);
$totalRows_detalle = mysql_num_rows($detalle);
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html><!-- InstanceBegin template="/Templates/carrito.dwt.php" codeOutsideHTMLIsLocked="false" -->
<head>
<!-- InstanceBeginEditable name="doctitle" -->
<title>P&aacute;gina de Detalles</title>
<!-- InstanceEndEditable --><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<!-- InstanceBeginEditable name="head" --><!-- InstanceEndEditable -->

<link href="estilos/fotos.css" rel="stylesheet" type="text/css">
</head>

<body>
<table width="100%"  border="0">
  <tr>
    <td>Aqui va el Logo </td>
  </tr>
  <tr>
    <td align="center"><table width="85%"  border="0">
      <tr align="center">
        <td><a href="index.php">INICIO</a></td>
        <td>ENLACE 2</td>
        <td>ENLACE 3 </td>
        <td>ENLACE 4</td>
      </tr>
    </table></td>
  </tr>
  <tr>
    <td><!-- InstanceBeginEditable name="Edicion" -->
<div id="detalle" align="center">
     <table width="100%"  border="0">
        <tr>
          <td align="center"><h2><?php echo $row_detalle['lugar']; ?></h2></td>
        </tr>
        <tr>
          <td align="center"><?php echo $row_detalle['descripcion']; ?></td>
        </tr>
        <tr>
          <td align="center">Esta foto ha sido vista <?php echo $row_detalle['hits']; ?> veces</td>
        </tr>
        <tr>
          <td align="center" class="detalle1"><img src="fotos/<?php echo $row_detalle['nombre']; ?>" width="400" height="598"></td>
        </tr>
      </table>
</div>
      
    <!-- InstanceEndEditable --></td>
  </tr>
</table>
</body>
<!-- InstanceEnd --></html>
<?php
mysql_free_result($detalle);
?>
Como ves estoy usando una plantilla y estoy trabajando en Dreamweaver. Gracias de nuevo.
  #5 (permalink)  
Antiguo 27/10/2008, 20:51
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 11 meses
Puntos: 2135
Respuesta: Contador para fotos vistas

Pues yo pondría el update bajo el select para obtener los datos de la foto.

Saludos.
  #6 (permalink)  
Antiguo 27/10/2008, 22:56
 
Fecha de Ingreso: octubre-2008
Mensajes: 165
Antigüedad: 15 años, 6 meses
Puntos: 12
Respuesta: Contador para fotos vistas

Disculpa GatorV, soy muy neófito en MySQL, y al pegarlo me da una serie de errores trato de dejar bien los campos de la Base de datos, pero nada. Agradezco tu paciencia y tus respuestas.
  #7 (permalink)  
Antiguo 28/10/2008, 06:35
Avatar de ACX_POISON  
Fecha de Ingreso: abril-2008
Ubicación: Talca-Chile
Mensajes: 750
Antigüedad: 16 años
Puntos: 7
Respuesta: Contador para fotos vistas

que errores..
__________________
Me junto con los que Saben, Queriendo Saber.
  #8 (permalink)  
Antiguo 28/10/2008, 20:23
 
Fecha de Ingreso: octubre-2008
Mensajes: 165
Antigüedad: 15 años, 6 meses
Puntos: 12
Respuesta: Contador para fotos vistas

Coloqué correctamente el nombre de las variables y ya no me salieron errores, pero no pasa nada en el contador, no aumenta. lo dejé así:
Código:
<?php require_once('Connections/Carrito1.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;
}
}

$colname_detalle = "-1";
if (isset($_GET['foto_id'])) {
  $colname_detalle = $_GET['foto_id'];
}
mysql_select_db($database_Carrito1, $Carrito1);
$query_detalle = sprintf("SELECT * FROM fotos_mias WHERE foto_id = %s", GetSQLValueString($colname_detalle, "int"));
$detalle = mysql_query($query_detalle, $Carrito1) or die(mysql_error());
$row_detalle = mysql_fetch_assoc($detalle);
$totalRows_detalle = mysql_num_rows($detalle);
$sql ="UPDATE `fotos_mias` SET `hits`=`hits`+1 WHERE `foto_id` = %s";
?>
Lo que he puesto en rojo fué lo que le agregué.
  #9 (permalink)  
Antiguo 28/10/2008, 20:39
 
Fecha de Ingreso: octubre-2008
Mensajes: 102
Antigüedad: 15 años, 6 meses
Puntos: 0
Respuesta: Contador para fotos vistas

tienes que ponerle un @mysql_query a eso ahora...
  #10 (permalink)  
Antiguo 28/10/2008, 21:04
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 11 meses
Puntos: 2135
Respuesta: Contador para fotos vistas

Exacto no solo con definir la variable con la consulta esta se ejecuta tienes que llamar a la función mysql_query para ejecutarla.

Saludos.
  #11 (permalink)  
Antiguo 28/10/2008, 21:06
okram
Invitado
 
Mensajes: n/a
Puntos:
Respuesta: Contador para fotos vistas

Y esa consulta que resaltas de rojo, donde la ejecutas? Porque ahi sólo la estás asignando como un string a la variable $sql.

@Zidencjb, a menos que se cuente con un sistema para el manejo de errores, no es recomendable usar el @. Primero porque puede ocultar errores que son pasados por alto y que después son inubicables, y segundo, porque se supone que un script bien programado, en este caso, una consulta bien elaborada, no tendría por qué dar algún tipo de error.

Saludos,
  #12 (permalink)  
Antiguo 28/10/2008, 21:19
 
Fecha de Ingreso: octubre-2008
Mensajes: 165
Antigüedad: 15 años, 6 meses
Puntos: 12
Respuesta: Contador para fotos vistas

Cita:
Iniciado por Zidencjb Ver Mensaje
tienes que ponerle un @mysql_query a eso ahora...
Se lo he puesto de esta forma, (lo que está en rojo):
Código:
...
mysql_select_db($database_Carrito1, $Carrito1);
$query_detalle = sprintf("SELECT * FROM fotos_mias WHERE foto_id = %s", GetSQLValueString($colname_detalle, "int"));
$detalle = mysql_query($query_detalle, $Carrito1) or die(mysql_error());
$row_detalle = mysql_fetch_assoc($detalle);
$totalRows_detalle = mysql_num_rows($detalle);
$sql ="UPDATE `fotos_mias` SET `hits`=`hits`+1 WHERE `foto_id`=%s";
$contando = mysql_query($contando, $Carrito1) or die(mysql_error());
?>
Pero me aparece lo siguiente en el navegador:
Query was empty

El campo de los hits es varchar.
  #13 (permalink)  
Antiguo 28/10/2008, 21:23
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 11 meses
Puntos: 2135
Respuesta: Contador para fotos vistas

Mmmm tu estas tratando de enviar en el query la variable $contando, sin embargo tu variable con el SQL es $sql.

Es por eso que te marca el error.

Saludos.
  #14 (permalink)  
Antiguo 28/10/2008, 21:26
okram
Invitado
 
Mensajes: n/a
Puntos:
Respuesta: Contador para fotos vistas

Y yo te pongo en azul lo que está mal:

$contando = mysql_query($contando, $Carrito1) or die(mysql_error());

Tu variable que contiene la consulta no es $sql?

Saludos, (¬¬)
  #15 (permalink)  
Antiguo 28/10/2008, 21:46
 
Fecha de Ingreso: octubre-2008
Mensajes: 165
Antigüedad: 15 años, 6 meses
Puntos: 12
Respuesta: Contador para fotos vistas

Ok, ya lo he modificado, pero ahora me sale en el navegador:
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 '%s' at line 1

Estoy utilizando XAMPP v1.6.8 y Dreamweaver CS3
que tiene PHP Version 5.2.6 y MySQL 5.0.67

GatorV y okram disculpen tanta molestadera y agradezco su atención
  #16 (permalink)  
Antiguo 28/10/2008, 21:50
okram
Invitado
 
Mensajes: n/a
Puntos:
Respuesta: Contador para fotos vistas

Si, ahora, me parece que estabas usando sprintf() para generar tu consulta. debería ser algo como:

Código PHP:
$sql sprintf("UPDATE `fotos_mias` SET `hits`=`hits`+1 WHERE `foto_id`=%s"$el_id_de_tu_foto); 
Saludos,
  #17 (permalink)  
Antiguo 28/10/2008, 22:06
 
Fecha de Ingreso: octubre-2008
Mensajes: 165
Antigüedad: 15 años, 6 meses
Puntos: 12
Respuesta: Contador para fotos vistas

Al final la línea la dejé así:
Código PHP:
$sql sprintf("UPDATE `fotos_mias` SET `hits`=`hits`+1 WHERE `foto_id`=%s"GetSQLValueString($colname_detalle"int")); 
El código GetSQLValueString($colname_detalle, "int")); se lo copié al SELECT.

Muchísimas gracias okram ya todo funciona perfectamente.
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:47.