Ver Mensaje Individual
  #2 (permalink)  
Antiguo 07/02/2011, 16:22
Avatar de nquerce
nquerce
 
Fecha de Ingreso: febrero-2011
Ubicación: Buenos Aires - Argentina
Mensajes: 5
Antigüedad: 13 años, 3 meses
Puntos: 0
Respuesta: IF EXISTS, ALERT, ELSE INSERT -- Como Hago??

Bueno gente, al final lo solucione de otra manera.

El formulario del php donde esta el recordset, solamente manda mes y año otro php que con esos datos mas el id del usuario que esta en una variabla de sesion, hace un select en la base ddjj, buscando registros que coincidan con mes y el año y el id empresa.

El php tiene dos regiones, una que se muestra si el recordset esta vacio y otro si tiene al menos un registro.

Si esta vacio,
Muestra la region donde tengo un form que en dos texto ocultos toma las variables mes y año que pase por GET.
Al enviar :
1)Genera una tabla temporal con registros desde la tabla empleados que sean de este id empresa y que el campo activo diga "activo",
2) Le agrega las columnas mes y año,
3) Le hace un Update set a esas columnas escribiendo mes y año desde las var GET,
4)hace un insert into ddjj from temporal,
5) finalmente un DROP a la tabla temporal.

cuando termina envia a un php con el mensaje de exito.

Si tiene al menos un registro
Muestra la segunda region donde simpleemente tengo un texto que dice que la empresa nro (var session ide_mpresa) ya tiene hecho una declaracion jurada para el mes (var get mes)y año (var get año).

No si es lo mas rapido, lo mas eficiente, o lo mejor, pero es lo que se me ocurrio y la solucion que pude encontrar con las herramientas que tengo.

Código:
<?php require_once('../../Connections/x.php'); ?>
<?php
// Aca va todo la parte de session que incluye el dreamweaver
?>
<?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;
}
}
$currentPage = $_SERVER["PHP_SELF"];
$colname_ddjj = "-1";
if (isset($_SESSION['MM_id_empresa'])) {
  $colname_ddjj = $_SESSION['MM_id_empresa'];
}
$coolname_ddjj = "-1";
if (isset($_GET['mes'])) {
  $coolname_ddjj = $_GET['mes'];
}
$cooolname_ddjj = "-1";
if (isset($_GET['anio'])) {
  $cooolname_ddjj = $_GET['anio'];
}
mysql_select_db($database_bapro, $bapro);
$query_ddjj = sprintf("SELECT id_empresa FROM ddjj WHERE id_empresa = %s AND ddjj.mes_ddjj=%s  AND ddjj.anio_ddjj=%s", GetSQLValueString($colname_ddjj, "int"),GetSQLValueString($coolname_ddjj, "int"),GetSQLValueString($cooolname_ddjj, "int"));
$ddjj = mysql_query($query_ddjj, $bapro) or die(mysql_error());
$row_ddjj = mysql_fetch_assoc($ddjj);
$totalRows_ddjj = mysql_num_rows($ddjj);
// COMIENZA INSERT
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")){
$insertSQL1 = sprintf("CREATE TABLE ddjj_temp SELECT * FROM empleados WHERE `id_empresa` =1 AND `activo` = Activo");
  mysql_select_db($database_bapro, $bapro);
  $Result1 = mysql_query($insertSQL1, $bapro) or die(mysql_error());
 
$insertSQL2 = sprintf("ALTER TABLE `ddjj_temp` ADD `mes_ddjj` VARCHAR( 2 ) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL , ADD `anio_ddjj` VARCHAR( 4 ) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL");
  mysql_select_db($database_bapro, $bapro);
  $Result2 = mysql_query($insertSQL2, $bapro) or die(mysql_error());
 
$insertSQL3 = sprintf("ALTER TABLE `ddjj_temp` ADD `id_ddjj` INT NOT NULL FIRST");
  mysql_select_db($database_bapro, $bapro);
  $Result3 = mysql_query($insertSQL3, $bapro) or die(mysql_error());
 
$insertSQL4 = sprintf("UPDATE ddjj_temp SET mes_ddjj =$mes_ddjj,anio_ddjj =$anio_ddjj WHERE `id_empresa` =1");
  mysql_select_db($database_bapro, $bapro);
  $Result4 = mysql_query($insertSQL4, $bapro) or die(mysql_error());
 
$insertSQL5 = sprintf("INSERT INTO ddjj SELECT * FROM ddjj_temp");
  mysql_select_db($database_bapro, $bapro);
  $Result5 = mysql_query($insertSQL5, $bapro) or die(mysql_error());
$insertSQL6 = sprintf("DROP TABLE `ddjj_temp`");
  mysql_select_db($database_bapro, $bapro);
  $Result6 = mysql_query($insertSQL6, $bapro) or die(mysql_error());
$insertGoTo = "ddjj_alta_ok";
if (isset($_SERVER['QUERY_STRING'])) {
$insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
$insertGoTo .= $_SERVER['QUERY_STRING'];
}
  header(sprintf("Location: %s", $insertGoTo));
}
// FIN INSERT
$queryString_ddjj = "";
if (!empty($_SERVER['QUERY_STRING'])) {
  $params = explode("&", $_SERVER['QUERY_STRING']);
  $newParams = array();
  foreach ($params as $param) {
    if (stristr($param, "pageNum_ddjj") == false && 
        stristr($param, "totalRows_ddjj") == false) {
      array_push($newParams, $param);
    }
  }
  if (count($newParams) != 0) {
    $queryString_ddjj = "&" . htmlentities(implode("&", $newParams));
  }
}
$queryString_ddjj = sprintf("&totalRows_ddjj=%d%s", $totalRows_ddjj, $queryString_ddjj);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "[URL]http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd[/URL]">
<html xmlns="[URL]http://www.w3.org/1999/xhtml[/URL]">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Documento sin t&iacute;tulo</title>
<link href="../css/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<p><span class="tittabla">Union del Personal Panaderias y Afines</span><br />
  Sistema  De Gesti&oacute;n On Line </p>
<?php if ($totalRows_ddjj == 0) { // Show if recordset empty ?>
  <p><strong>IMPORTANTE: Las declaraciones juradas pueden relizarse s&oacute;lo una vez por cada per&iacute;odo. <br />
  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Adem&aacute;s no se permite modificar ni borrar una declaraci&oacute;n jurada despu&eacute;s de haberla realizado.</strong></p>
  <p align="center"><strong><span class="no">Por favor, revise y verifique los datos antes de realizar esta declaraci&oacute;n jurada!</span></strong></p>
  <form id="proc_ddjj" name="proc_ddjj" method="post" action="<?php echo $editFormAction; ?>">
    <label>
    <table width="100%" border="0" cellspacing="0" cellpadding="3">
      <tr>
        <td colspan="2" class="tablatop">Realizar una declaracion jurada para el per&iacute;odo:</td>
      </tr>
      <tr>
        <td width="200" align="right" class="tablabody">Mes</td>
        <td class="tablabody"><strong> <?php echo $mes; ?>
          <input name="mes_ddjj" type="hidden" id="mes_ddjj" value="<?php echo $mes; ?>" />
          </strong></td>
      </tr>
      <tr>
        <td width="200" align="right" class="tablabody">A&ntilde;o</td>
        <td class="tablabody"><strong> <?php echo $anio;?>
          <input name="anio_ddjj" type="hidden" id="anio_ddjj" value="<?php echo $anio;?>" />
          </strong></td>
      </tr>
      <tr>
        <td width="200" class="tablabody">&nbsp;</td>
        <td class="tablabody"><input type="submit" name="button" id="button" value="Realizar Declaraci&oacute;n Jurada" /></td>
      </tr>
    </table>
    <input type="hidden" name="MM_insert" value="form1" />
    </label>
  </form>
  <?php } // Show if recordset empty ?>
<?php if ($totalRows_ddjj > 0) { // Show if recordset not empty ?>
  <p><span class="no"><strong><img src="../images/no.gif" width="51" height="49" hspace="3" vspace="3" align="absmiddle" />Esta empresa ya ha realizado una declaraci&oacute;n jurada para el per&iacute;odo <?php echo $mes; ?> / <?php echo $anio;?> . </strong></span></p>
  <p><strong>IMPORTANTE: Las declaraciones juradas pueden relizarse s&oacute;lo una vez por cada per&iacute;odo. <br />
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Adem&aacute;s no se permite modificar ni borrar una declaraci&oacute;n jurada despu&eacute;s de haberla realizado.</strong></p>
  <?php } // Show if recordset not empty ?>
<p><a href="admin.php">Panel Admin</a> - <a href="javascript:history.go(-1);">Volver</a> - <a href="login.php">Cambiar Usuario</a> - <a href="<?php echo $logoutAction ?>">Desconectar</a></p>
</body>
</html>
<?php
mysql_free_result($ddjj);
?>
Que raro que cuando escribi esta solucion habian pasado mas de 100 visitas y ningun aporte....era realmente tan raro lo que queria hacer??

Gracias a todos!