Foros del Web » Programando para Internet » PHP »

Agregar la funcion unlik al codigo php

Estas en el tema de Agregar la funcion unlik al codigo php en el foro de PHP en Foros del Web. Hola, que tal !! Estoy haciendo un sistema de registro, el cual se registran los usuarios con sus datos personales, incluyendo una imagen, esta ultima ...
  #1 (permalink)  
Antiguo 19/08/2012, 23:04
 
Fecha de Ingreso: mayo-2012
Ubicación: Distrito Federal
Mensajes: 49
Antigüedad: 11 años, 11 meses
Puntos: 9
Pregunta Agregar la funcion unlik al codigo php

Hola, que tal !!

Estoy haciendo un sistema de registro, el cual se registran los usuarios con sus datos personales, incluyendo una imagen, esta ultima ademas de guardarse en la bd tambien se almacena en una carpeta.

Este sistema tambien tiene una pagina de busqueda (en modo administrador) que al encontrar los datos en la bd muestra un enlace para eliminar dichos datos.

El enlace de eliminar funciona correctamente, puesto que borra los registros de la bd, pero no borra las imagenes almacenadas en la carpeta.

He leido que esto se hace con la funcion unlink pero la verdad no se como implementarla en mi codigo. Miren estos son los codigos de que utilizo:


procesar_formulario.php
Código:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Guardar formulario</title>
</head>

<body>

<?php
$target = "imagenes/imagenes_jugadores/";
$target = $target . basename( $_FILES['imagen']['name']);

$nombre=$_POST['nombre'];
$ap_pat=$_POST['ap_pat'];
$ap_mat=$_POST['ap_mat'];
$apodo=$_POST['apodo'];
$nacionalidad=$_POST['nacionalidad'];
$edad=$_POST['edad'];
$altura=$_POST['altura'];
$peso=$_POST['peso'];
$posicion=$_POST['posicion'];
$numero=$_POST['numero'];
$imagen = $_FILES['imagen']['name'];
$tamano = $_FILES['imagen']['size']; 
$tipo_archivo = $_FILES['imagen']['type']; 
$habilidad=$_POST['habilidad'];
$comentarios=$_POST['comentarios'];

mysql_connect("localhost", "usuario", "contraseña") or die(mysql_error()) ;
mysql_select_db("base_de_datos") or die(mysql_error()) ;

if ($tamano == 0 or $tamano > 1000000) { 
    echo "<script> alert(\"La imagen debe pesar 1 MB maximo\"); </script>";
	echo "<script language=Javascript> location.href=\"FORMULARIO.php\"; </script>";
	
}

        else{  

             if(move_uploaded_file($_FILES['imagen']['tmp_name'], $target)) {
				 
            mysql_query("INSERT INTO datos_jugador (nombre, ap_pat, ap_mat, apodo, nacionalidad, edad, altura, peso, posicion,            numero, imagen, habilidad, comentarios) VALUES ('$nombre', '$ap_pat', '$ap_mat', '$apodo', '$nacionalidad', '$edad',            '$altura', '$peso', '$posicion', '$numero', '$imagen', '$habilidad', '$comentarios')") ;

            echo "<script> alert(\"Datos agregados correctamente\"); </script>";
            echo "<script language=Javascript> location.href=\"FORMULARIO.php\"; </script>";
           
		    }
 
                 else {

                         echo "<script> alert(\"Hubo un problema al guardar los datos\"); </script>";
                         echo "<script language=Javascript> location.href=\"FORMULARIO.php\"; </script>";
                       }
}


?>

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

$colname_mostrar_datos = "-1";
if (isset($_POST['busqueda'])) {
  $colname_mostrar_datos = $_POST['busqueda'];
}
mysql_select_db($database_futbol, $futbol);
$query_mostrar_datos = sprintf("SELECT * FROM datos_jugador WHERE nombre LIKE %s", GetSQLValueString("%" . $colname_mostrar_datos . "%", "text"));
$mostrar_datos = mysql_query($query_mostrar_datos, $futbol) or die(mysql_error());
$row_mostrar_datos = mysql_fetch_assoc($mostrar_datos);
$totalRows_mostrar_datos = mysql_num_rows($mostrar_datos);
?>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Busqueda</title>


<script src="mootools/mootools.js" type="text/javascript"></script>
<script src="mootools/sexyalertbox.v1.1.js" type="text/javascript"></script>

<script type="text/javascript">
window.addEvent('domready', function() {
Sexy = new SexyAlertBox();
});
</script>

<link rel="stylesheet" href="mootools/sexyalertbox.css" type="text/css" media="all" />


<script type="text/javascript">
window.addEvent('domready', function () {
    $$('a.borrar').each(function (el) {
        el.addEvent('click', function (e) {
            e.stop();
            Sexy.confirm('<h1>¿QUIERES IR A LA PAGINA?</h1>',{ 
                onComplete: function(returnvalue) {
                    if (returnvalue) {
                        window.location.href = el.get('href');
                    }
                },
                textBoxBtnOk: 'SI',
                textBoxBtnCancel: 'No'
            });
        });
    });
});

</script>



<style type="text/css">
<!--
#apDiv1 {
	position:absolute;
	width:817px;
	height:115px;
	z-index:1;
	left: 130px;
	top: 85px;
}
#apDiv2 {
	position:absolute;
	width:457px;
	height:46px;
	z-index:2;
	left: 326px;
	top: 21px;
}
-->
</style>
</head>

<body>
<div id="apDiv1">
  <table width="810" border="1">
    <tr>
      <td width="322">NOMBRE</td>
      <td width="140">APODO</td>
      <td width="182">NACIONALIDAD</td>
      <td width="138">BORRAR</td>
    </tr>
    <tr>
      <td><?php echo $row_mostrar_datos['nombre']; ?> <?php echo $row_mostrar_datos['ap_pat']; ?> <?php echo $row_mostrar_datos['ap_mat']; ?></td>
      <td><?php echo $row_mostrar_datos['apodo']; ?></td>
<td><?php echo $row_mostrar_datos['nacionalidad']; ?></td>
      <td><a href="ELIMINAR.php?id_jugador=<?php echo $row_mostrar_datos['id_jugador']; ?>" class="borrar">BORRAR</a></td>
    </tr>
  </table>
</div>
<div id="apDiv2">
  <form id="form1" name="form1" method="post" action="BUSQUEDA.php">
    ESCRIBE UN NOMBRE 
    <label>
      <input type="text" name="busqueda" id="busqueda" />
    </label>
    <label>
      <input type="submit" name="enviar" id="enviar" value="BUSCAR" />
    </label>
  </form>
</div>
</body>
</html>
<?php
mysql_free_result($mostrar_datos);
?>

eliminar.php
Código:
<?php 

$conexion = mysql_connect ("localhost", "usuario", "contraseña");
mysql_select_db ("base_de_datos");

$query=mysql_query ("DELETE FROM datos_jugador WHERE id_jugador=".$_REQUEST["id_jugador"]);
    
	echo "<script> alert(\"LOS DATOS HAN SIDO BORRADOS CORRECTAMENTE\"); </script>";
	
	echo "<script language=Javascript> location.href=\"busqueda.php\"; </script>";

?>
  #2 (permalink)  
Antiguo 19/08/2012, 23:15
Avatar de raco_hernandez  
Fecha de Ingreso: agosto-2012
Mensajes: 39
Antigüedad: 11 años, 8 meses
Puntos: 4
Respuesta: Agregar la funcion unlik al codigo php

Yo lo hago asi mira

Cita:
if (file_exists("RUTA ARCHIVO")){
unlink("RUTA ARCHIVO");
}
  #3 (permalink)  
Antiguo 19/08/2012, 23:16
 
Fecha de Ingreso: agosto-2012
Mensajes: 5
Antigüedad: 11 años, 7 meses
Puntos: 0
Respuesta: Agregar la funcion unlik al codigo php

raco puedes ayudarme en mi post?
  #4 (permalink)  
Antiguo 19/08/2012, 23:17
Avatar de raco_hernandez  
Fecha de Ingreso: agosto-2012
Mensajes: 39
Antigüedad: 11 años, 8 meses
Puntos: 4
Respuesta: Agregar la funcion unlik al codigo php

Cita:
Iniciado por firstminister Ver Mensaje
raco puedes ayudarme en mi post?
Claro yo uso esa función que te acabo de pasar para borrar imagen por imagen
  #5 (permalink)  
Antiguo 19/08/2012, 23:22
 
Fecha de Ingreso: agosto-2012
Mensajes: 5
Antigüedad: 11 años, 7 meses
Puntos: 0
Respuesta: Agregar la funcion unlik al codigo php

raco, mi post es otro, el de filtrar numeros de un textarea, de otro! leelo por favor :(
  #6 (permalink)  
Antiguo 20/08/2012, 12:04
 
Fecha de Ingreso: mayo-2012
Ubicación: Distrito Federal
Mensajes: 49
Antigüedad: 11 años, 11 meses
Puntos: 9
Respuesta: Agregar la funcion unlik al codigo php

Entiendo que debo poner la ruta o almenos definirla, pero no se como, ya que no es un archivo en especifico, sino es el resultado de una busqueda del usuario
  #7 (permalink)  
Antiguo 20/08/2012, 13:31
 
Fecha de Ingreso: mayo-2012
Ubicación: Distrito Federal
Mensajes: 49
Antigüedad: 11 años, 11 meses
Puntos: 9
Respuesta: Agregar la funcion unlik al codigo php

Hola de nuevo, miren trate de modificar el codigo para agregarle la funcion unlink.

El codigo hace la funcion de borrar sin ningun tipo de error pero la foto sigue sin borrarse de la carpeta. Este es el codigo:

Código:
<?php 

$conexion = mysql_connect ("localhost", "root", "");
mysql_select_db ("sistema");


$borrar_datos=$_REQUEST["id_jugador"];

$ruta = "../imagenes/imagenes_jugadores/".$_REQUEST["id_jugador"];


$query=mysql_query ("DELETE FROM datos_jugador WHERE id_jugador = $borrar_datos");


       if(file_exists($ruta)) unlink($ruta );
    
	echo "<script> alert(\"LOS DATOS HAN SIDO BORRADOS CORRECTAMENTE\"); </script>";
	
	echo "<script language=Javascript> location.href=\"BUSQUEDA.php\"; </script>";

?>
  #8 (permalink)  
Antiguo 20/08/2012, 17:36
Avatar de raco_hernandez  
Fecha de Ingreso: agosto-2012
Mensajes: 39
Antigüedad: 11 años, 8 meses
Puntos: 4
Respuesta: Agregar la funcion unlik al codigo php

Tienes que asegurarte que la imagen o archivo exista en esa ruta

$ruta = "../imagenes/imagenes_jugadores/".$_REQUEST["id_jugador"];

Puede que te este arrojando algo como

$ruta = "../imagenes/imagenes_jugadores/ARCHIVO

Y la ruta real sea

imagenes/imagenes_jugadores/ARCHIVO
../imagenes/imagenes_jugadores/ARCHIVO
../../imagenes/imagenes_jugadores/ARCHIVO
../../../imagenes/imagenes_jugadores/ARCHIVO

Me explico

Etiquetas: formulario, funcion, html, imagenes, mysql, registro, 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 11:19.