Foros del Web » Programando para Internet » PHP »

[SOLUCIONADO] Enviar correo dentro de un case switch

Estas en el tema de Enviar correo dentro de un case switch en el foro de PHP en Foros del Web. Saludos chicos, aqui expondre un ejemplo a ver si me orientan a como es la manera mas correcta de hacer lo que deseo. Deseo enviar ...
  #1 (permalink)  
Antiguo 14/02/2017, 08:57
(Desactivado)
 
Fecha de Ingreso: septiembre-2008
Ubicación: Maracay edo Aragua Venezuela
Mensajes: 48
Antigüedad: 15 años, 7 meses
Puntos: 3
Pregunta Enviar correo dentro de un case switch

Saludos chicos, aqui expondre un ejemplo a ver si me orientan a como es la manera mas correcta de hacer lo que deseo.

Deseo enviar un correo en el mismo momento que se ejecuta una accion de guardar datos en una BD, esta parte ya esta funcionando y la web para que envie el correo tambien esta funcionando pero me gustaria que cuando se llame la accion de actualizar se ejecute tambien enviar.php

en el index.php
Código PHP:
<?php
session_start
();
if(!isset(
$_SESSION["user_id"]) || $_SESSION["user_id"]==null){
    print 
"<script>alert(\"Acceso invalido!\");window.location='../../login.php';</script>";
}
require_once 
'usuario.entidad.php';
require_once 
'usuario.model.php';

// Logica
$alm = new Usuario();
$model = new UsuarioModel();

if(isset(
$_REQUEST['action']))
{
    switch(
$_REQUEST['action'])
    {
        case 
'actualizar':
            
$alm->__SET('id',          $_REQUEST['id']);
            
$alm->__SET('Rif',         $_REQUEST['Rif']);
            
$alm->__SET('Nombre',      $_REQUEST['Nombre']);
            
$alm->__SET('Producto',    $_REQUEST['Producto']);
            
$alm->__SET('sistema_enc'$_REQUEST['sistema_enc']);
            
$alm->__SET('nro_cupon',   $_REQUEST['nro_cupon']);
            
$alm->__SET('fecha_envio'$_REQUEST['fecha_envio']);
            
$alm->__SET('nota',        $_REQUEST['nota']);

            
$model->Actualizar($alm);
            
header('Location: index.php');
            break;

        case 
'registrar':
            
$alm->__SET('Rif',          $_REQUEST['Rif']);
            
$alm->__SET('Nombre',       $_REQUEST['Nombre']);
            
$alm->__SET('Producto',     $_REQUEST['Producto']);
            
$alm->__SET('sistema_enc',  $_REQUEST['sistema_enc']);
            
$alm->__SET('nro_cupon',    $_REQUEST['nro_cupon']);
            
$alm->__SET('fecha_envio',  $_REQUEST['fecha_envio']);
            
$alm->__SET('nota',         $_REQUEST['nota']);

            
$model->Registrar($alm);
            
header('Location: index.php');
            break;        

        case 
'enviar':
            
$alm->__SET('Rif',          $_REQUEST['Rif']);
            
$alm->__SET('Nombre',       $_REQUEST['Nombre']);
            
$alm->__SET('Producto',     $_REQUEST['Producto']);
            
$alm->__SET('sistema_enc',  $_REQUEST['sistema_enc']);
            
$alm->__SET('nro_cupon',    $_REQUEST['nro_cupon']);
            
$alm->__SET('fecha_envio',  $_REQUEST['fecha_envio']);
            
$alm->__SET('nota',         $_REQUEST['nota']);

            
$model->enviar($alm);
            
header('Location: ../mail/envio.php');
            break;        

        case 
'eliminar':
            
$model->Eliminar($_REQUEST['id']);
            
header('Location: index.php');
            break;

        case 
'editar':
            
$alm $model->Obtener($_REQUEST['id']);
            break;
    }
}

?>

<!DOCTYPE html>
<html lang="es">
<head>
    <title>SIGENVIOS</title>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" >
    <link rel="stylesheet" type="text/css" href="../../../admin/config/css/estilo2.css">
</head>
    <body style="padding:15px;">

        <div class="pure-g">
            <div class="pure-u-1-12">
                
                <form action="?action=<?php echo $alm->id ?  'actualizar' 'registrar'?>" method="post" class="pure-form "style="margin-bottom:30px;">
                    <input type="hidden" name="id" value="<?php echo $alm->__GET('id'); ?>" />
                    
                    <table style="width:500px;">
                        <tr>
                            <th style="text-align:left;">Rif</th>
                            <td><input type="text" name="Rif" value="<?php echo $alm->__GET('Rif'); ?>" style="width:100%;" /></td>
                        </tr>
                        <tr>
                            <th style="text-align:left;">Nombre</th>
                            <td><input type="text" name="Nombre" value="<?php echo $alm->__GET('Nombre'); ?>" style="width:100%;" /></td>
                        </tr>
                                               <tr>
                            <th style="text-align:left;">Producto</th>
                            <td><input type="text" name="Producto" value="<?php echo $alm->__GET('Producto'); ?>" style="width:100%;" /></td>
                        </tr>
                        <tr>
                            <th style="text-align:left;">Encomienda</th>
                            <td><input type="text" name="sistema_enc" value="<?php echo $alm->__GET('sistema_enc'); ?>" style="width:100%;" /></td>
                        </tr>
                        <tr>
                        <tr>
                            <th style="text-align:left;">Numero Cupon</th>
                            <td><input type="text" name="nro_cupon" value="<?php echo $alm->__GET('nro_cupon'); ?>" style="width:100%;" /></td>
                        </tr>
                        <tr>
                            <th style="text-align:left;">Fecha de Envio</th>
                            <td><input type="text" name="fecha_envio" value="<?php echo $alm->__GET('fecha_envio'); ?>" style="width:100%;" /></td>
                        </tr>
                        <tr>
                        <th style="text-align:left;">Nota</th>
                            <td><input type="text" name="nota" value="<?php echo $alm->__GET('nota'); ?>" style="width:100%;" /></td>
                        </tr>                        
                        <tr>
                            <td colspan="2">
                                <button type="submit" class="pure-button pure-button-primary">Guardar</button>
                            </td>
                        </tr>
                    </table>
                </form>

                <table class="pure-table pure-table-horizontal">
                    <thead>
                        <tr>
                            <th style="text-align:left;">Rif</th>
                            <th style="text-align:left;">Nombre</th>
                            <th style="text-align:left;">Producto</th>
                            <th style="text-align:left;">Encomienda</th>
                            <th style="text-align:left;">Nro Cupon</th>
                            <th style="text-align:left;">Fecha Envio</th>
                            <th style="text-align:left;">Nota</th>
                            <th></th>
                            <th></th>
                        </tr>
                    </thead>
                    <?php foreach($model->Listar() as $r): ?>
                        <tr>
                            <td><?php echo $r->__GET('Rif'); ?></td>
                            <td><?php echo $r->__GET('Nombre'); ?></td>
                            <td><?php echo $r->__GET('Producto'); ?></td>
                            <td><?php echo $r->__GET('sistema_enc'); ?></td>
                            <td><?php echo $r->__GET('nro_cupon'); ?></td>
                            <td><?php echo $r->__GET('fecha_envio'); ?></td>
                            <td><?php echo $r->__GET('nota'); ?></td>
                            <td>
                                <a href="?action=editar&id=<?php echo $r->id?>">Editar</a>
                            </td>
                            <td>
 <!-- esta linea activa la opcion de borrar row de mysql-->
 <a href="?action=eliminar&id=<?php echo $r->id?>">Eliminar</a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </table>     
              
            </div>
        </div>

    </body>
</html>
enviar.php

Código PHP:
<?php
$rif
$_REQUEST['Rif'];
$nombre$_REQUEST['Nombre'];
$producto$_REQUEST['Producto'];
$sistema_enc$_REQUEST['sistema_enc'];
$nro_cupon$_REQUEST['nro_cupon'];
$fecha_envio$_REQUEST['fecha_envio'];
$nota$_REQUEST['nota'];
$from="JESYMCA SISTEMA INTERNO";
$to="[email protected]";
$asunto="Test desde Archivo Mail PHP";
$msg='<html>
<head>
  <title>Actualizacion en Status de Despacho</title>
</head>
<body>
  <table>
  <tr><td>
  <img src="http://www.jesuministrosymas.com.ve/LOGO.png" width="400" height="74" alt="J.E SUMINISTROS Y MAS, C.A." longdesc="LOGO J.E SUMINISTROS Y MAS, C.A." id="logo" align="left">
  </tr></td>
    <tr>
      <td>Saludos Cordiales Estimado/a '
$nombre.'</td>
    </tr>
    <tr>
      <td>Sally</td>
    </tr>
  </table>
</body>
</html>'
;
$cabeceras  'MIME-Version: 1.0' "\r\n";
$cabeceras .= 'Content-type: text/html; charset=iso-8859-1' "\r\n";
$cabeceras .= "To: $to" "\r\n";
$cabeceras .= "From: $from" "\r\n";

// mail($to,$subj,$msg,"From: $from");
$res mail $to$asunto$msg,$cabeceras);
var_export$res );

?>
Si ejecuto el archivo enviar.php solo perfectamente se ejecuta el envio de correo al correo de prueba, como podria hacer para que se ejecute una accion de 3 casos al mismo tiempo al dar al boton guardar y que a su vez se efectue el envio del correo con los datos respectivos, Gracias a quienes se tomen el tiempo en ayudarme..!!
  #2 (permalink)  
Antiguo 14/02/2017, 12:16
 
Fecha de Ingreso: julio-2014
Mensajes: 334
Antigüedad: 9 años, 9 meses
Puntos: 30
Respuesta: Enviar correo dentro de un case switch

No te llega porque estás llamando a "envio.php" en vez de enviar.php".

Llevas pocos días programando verdad? De lo contrario sabrias que para eso no debes de hacerlo así, si no llamar a una función y poner ahí el contenido de enviar.php

De todas formas, tengo un ratito y quisiera ayudarte en algo extra que te ayudará en el futuro para usar menos lineas de código pues cuanto más largo sea, hay más probabilidades de que falle. Siempre hay una manera más corta de hacer lo mismo, es cuestión de conocer los atajos.

Te comparto tus archivos modificados, con menos repeticiones y con menos lineas de código (aún se podría reducir más esa lógica de index.php si se modificase la estrctura del "usuario.model.php" y quizá también de "usuario.entidad.php".

index.php (solo php, el html sigue igual)
Código PHP:
<?php 
session_start
(); 
if(!isset(
$_SESSION["user_id"]) || $_SESSION["user_id"]==null){ 
    print 
"<script>alert(\"Acceso invalido!\");window.location='../../login.php';</script>"

require_once 
'usuario.entidad.php'
require_once 
'usuario.model.php';

# Incluimos el archivo enviar que contendrá la función para enviar correos y podrá ser llamada desde cualquier lugar donde se necesite enviar el correo
include 'enviar.php'

// Logica 
$alm = new Usuario(); 
$model = new UsuarioModel(); 

$page 'index';

if(isset(
$_REQUEST['action'])) 
{
    foreach(
$_REQUEST as $key => $value) {
        $
$key $value# Convertimos el índice en una variable al cual le asignamos el valor correspondiente

        
if($action == 'actualizar' && $key == 'id')
            
$alm->__SET($key$value); # Solo si estamos actualizando, se añadirá a __SET el id del registro para actualizarlo

        
$alm->__SET($key$value); # Como estamos dentro de un bucle, estamos seteando cada valor de $_REQUEST dentro de la función __SET
    
}

    if(
$action == 'eliminar')
        
$model->$action($id);
    else if(
$action == 'editar')
        
$model->Obtener($id); # Podrías eliminar esta linea, y dejar solo la de arriba si en vez de Obtener, fuese "Editar" .
    
else
        
$model->$action($alm); 

    if(
$action == 'enviar')
        
$page '../mail/enviar';

    if(
$action != 'editar')
        
header('Location: ' $page '.php'); 

?>
enviar.php (fijate que se incluyó este archivo dentro de index.php, después de los requires_one, para asi poder llamar a enviarCorreo desde cualquier lugar en index.php

Código PHP:
<?php
  
function envioCorreo($data) {
    foreach(
$data as $key => $value) {
        $
$key $value# Convertimos el índice en una variable al cual le asignamos el valor correspondiente

        
$from="JESYMCA SISTEMA INTERNO"
        
$to="[email protected]"
        
$asunto="Test desde Archivo Mail PHP"
        
$msg='<html> 
        <head> 
          <title>Actualizacion en Status de Despacho</title> 
        </head> 
        <body> 
          <table> 
          <tr><td> 
          <img src="http://www.jesuministrosymas.com.ve/LOGO.png" width="400" height="74" alt="J.E SUMINISTROS Y MAS, C.A." longdesc="LOGO J.E SUMINISTROS Y MAS, C.A." id="logo" align="left"> 
          </tr></td> 
            <tr> 
              <td>Saludos Cordiales Estimado/a '
$nombre.'</td> 
            </tr> 
            <tr> 
              <td>Sally</td> 
            </tr> 
          </table> 
        </body> 
        </html>'

        
$cabeceras  'MIME-Version: 1.0' "\r\n"
        
$cabeceras .= 'Content-type: text/html; charset=iso-8859-1' "\r\n"
        
$cabeceras .= "To: $to" "\r\n"
        
$cabeceras .= "From: $from" "\r\n"

        
// mail($to,$subj,$msg,"From: $from"); 
        
$res mail $to$asunto$msg,$cabeceras); 
        
var_export$res ); 
  }
  #3 (permalink)  
Antiguo 14/02/2017, 12:23
 
Fecha de Ingreso: julio-2014
Mensajes: 334
Antigüedad: 9 años, 9 meses
Puntos: 30
Respuesta: Enviar correo dentro de un case switch

No sé pq vainas me sale una captcha para editar algo,

en "enviar", cambia

Código PHP:
$page '../mail/enviar'
por
Código PHP:
envioCorreo($_REQUEST); 
  #4 (permalink)  
Antiguo 14/02/2017, 17:14
(Desactivado)
 
Fecha de Ingreso: septiembre-2008
Ubicación: Maracay edo Aragua Venezuela
Mensajes: 48
Antigüedad: 15 años, 7 meses
Puntos: 3
Respuesta: Enviar correo dentro de un case switch

Saludos, gracias por tomarse la molestia en revisar mi codigo, y de hecho tienes razon poco tiempo programando con PHP7 de hecho este sistema lo llegue a tener con PHP2 bajo ambiente Oscommerce pero ya ese codigo esta obsoleto y me ha tocado hacer las cosas de nuevo y leyendo las nuevas formas de hacer los llamados etc etc..!!
He implementado el codigo que me indicas y no se si es por el contenido de mis archivos 'usuario.entidad.php' y 'usuario.model.php' se los dejare por aca a ver si por la misma naturaleza de dichos archivos que el codigo que usted me sugiere no esta funcionando, y una vez mas gracias por la didactica que emplea al explicar lo que sucedera en cada codigo, igual le dejare punticos por ello.

usuario.model.php
Código PHP:
Ver original
  1. <?php
  2. class UsuarioModel
  3. {
  4.     private $pdo;
  5.  
  6.     public function __CONSTRUCT()
  7.     {
  8.         try
  9.         {
  10.             $this->pdo = new PDO('mysql:host=localhost;dbname=datos', 'usuario', 'clave');
  11.  
  12.             $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);               
  13.         }
  14.         catch(Exception $e)
  15.         {
  16.             die($e->getMessage());
  17.         }
  18.     }
  19.  
  20.     public function Listar()
  21.     {
  22.         try
  23.         {
  24.             $result = array();
  25.  
  26.             $stm = $this->pdo->prepare("SELECT * FROM ingreso ORDER BY id DESC  LIMIT 5");
  27.             $stm->execute();
  28.  
  29.             foreach($stm->fetchAll(PDO::FETCH_OBJ) as $r)
  30.             {
  31.                 $alm = new Usuario();
  32.  
  33.                 $alm->__SET('id', $r->id);
  34.                 $alm->__SET('Rif', $r->rif);
  35.                 $alm->__SET('Nombre', $r->nombre);
  36.                 $alm->__SET('Producto', $r->producto);
  37.                 $alm->__SET('sistema_enc', $r->sistema_enc);
  38.                 $alm->__SET('nro_cupon', $r->nro_cupon);
  39.                 $alm->__SET('fecha_envio', $r->fecha_envio);
  40.                 $alm->__SET('nota', $r->nota);
  41.  
  42.                 $result[] = $alm;
  43.             }
  44.  
  45.             return $result;
  46.         }
  47.         catch(Exception $e)
  48.         {
  49.             die($e->getMessage());
  50.         }
  51.     }
  52.  
  53.     public function Obtener($id)
  54.     {
  55.         try
  56.         {
  57.             $stm = $this->pdo
  58.                       ->prepare("SELECT * FROM ingreso WHERE id = ?");
  59.                      
  60.  
  61.             $stm->execute(array($id));
  62.             $r = $stm->fetch(PDO::FETCH_OBJ);
  63.  
  64.             $alm = new Usuario();
  65.  
  66.                 $alm->__SET('id', $r->id);
  67.                 $alm->__SET('Rif', $r->rif);
  68.                 $alm->__SET('Nombre', $r->nombre);
  69.                 $alm->__SET('Producto', $r->producto);
  70.                 $alm->__SET('sistema_enc', $r->sistema_enc);
  71.                 $alm->__SET('nro_cupon', $r->nro_cupon);
  72.                 $alm->__SET('fecha_envio', $r->fecha_envio);
  73.                 $alm->__SET('nota', $r->nota);
  74.  
  75.             return $alm;
  76.         } catch (Exception $e)
  77.         {
  78.             die($e->getMessage());
  79.         }
  80.     }
  81.  
  82.     public function Eliminar($id)
  83.     {
  84.         try
  85.         {
  86.             $stm = $this->pdo
  87.                       ->prepare("DELETE FROM ingreso WHERE id = ?");                     
  88.  
  89.             $stm->execute(array($id));
  90.         } catch (Exception $e)
  91.         {
  92.             die($e->getMessage());
  93.         }
  94.     }
  95.  
  96.     public function Actualizar(Usuario $data)
  97.     {
  98.         try
  99.         {
  100.             $sql = "UPDATE ingreso SET
  101.                         rif                 = ?,
  102.                         nombre              = ?,
  103.                         producto            = ?,
  104.                         sistema_enc         = ?,
  105.                         nro_cupon           = ?,
  106.                         fecha_envio         = ?,
  107.                         nota                = ?
  108.                     WHERE id = ?";
  109.             $sql2 = "INSERT INTO vitacora (rif,nombre,producto,sistema_enc,nro_cupon,fecha_envio,nota,id)
  110.                 VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
  111.                    
  112.  
  113.             $this->pdo->prepare($sql)
  114.                  ->execute(
  115.                 array(
  116.                     $data->__GET('Rif'),
  117.                     $data->__GET('Nombre'),
  118.                     $data->__GET('Producto'),
  119.                     $data->__GET('sistema_enc'),
  120.                     $data->__GET('nro_cupon'),
  121.                     $data->__GET('fecha_envio'),
  122.                     $data->__GET('nota'),
  123.                     $data->__GET('id')
  124.                    
  125.                     )
  126.                            
  127.                 );
  128.             $this->pdo->prepare($sql2)
  129.                  ->execute(
  130.                 array(
  131.                     $data->__GET('Rif'),
  132.                     $data->__GET('Nombre'),
  133.                     $data->__GET('Producto'),
  134.                     $data->__GET('sistema_enc'),
  135.                     $data->__GET('nro_cupon'),
  136.                     $data->__GET('fecha_envio'),
  137.                     $data->__GET('nota'),
  138.                     $data->__GET('id')
  139.                    
  140.                     )
  141.                            
  142.                 );             
  143.         }
  144.        
  145.        
  146.         catch (Exception $e)
  147.         {
  148.             die($e->getMessage());
  149.         }
  150.     }
  151.  
  152.     public function Registrar(Usuario $data)
  153.     {
  154.         try
  155.         {
  156.         $sql = "INSERT INTO ingreso (rif,nombre,producto,sistema_enc,nro_cupon,fecha_envio,nota)
  157.                 VALUES (?, ?, ?, ?, ?, ?, ?)";
  158.  
  159.         $this->pdo->prepare($sql)
  160.              ->execute(
  161.             array(
  162.                     $data->__GET('Rif'),
  163.                     $data->__GET('Nombre'),
  164.                     $data->__GET('Producto'),
  165.                     $data->__GET('sistema_enc'),
  166.                     $data->__GET('nro_cupon'),
  167.                     $data->__GET('fecha_envio'),
  168.                     $data->__GET('nota'),
  169.                 )
  170.             );
  171.         } catch (Exception $e)
  172.         {
  173.             die($e->getMessage());
  174.         }
  175.     }
  176.  
  177.    
  178. }

y el archivo usuario.entidad.php
Código PHP:
Ver original
  1. <?php
  2. class Usuario
  3. {
  4.     private $id;
  5.     private $rif;
  6.     private $nombre;
  7.     private $producto;
  8.     private $sistema_enc;
  9.     private $nro_cupon;
  10.     private $fecha_envio;
  11.     private $nota;
  12.  
  13.  
  14.     public function __GET($k){ return $this->$k; }
  15.     public function __SET($k, $v){ return $this->$k = $v; }
  16. }
  #5 (permalink)  
Antiguo 14/02/2017, 21:27
(Desactivado)
 
Fecha de Ingreso: septiembre-2008
Ubicación: Maracay edo Aragua Venezuela
Mensajes: 48
Antigüedad: 15 años, 7 meses
Puntos: 3
Respuesta: Enviar correo dentro de un case switch

Acabo de verificar y he comentado el include
Código PHP:
Ver original
  1. //include 'enviar.php';
y alli la web si carga, pero al tratar de ejecutar las acciones de editar o de crear un dato nuevo con el codigo propuesto se pone en blanco la web, es decir no ejecuta las funciones. Seguire igual tratando de comprender donde esta el error..! Estare atento por aca..!
  #6 (permalink)  
Antiguo 15/02/2017, 06:52
 
Fecha de Ingreso: julio-2014
Mensajes: 334
Antigüedad: 9 años, 9 meses
Puntos: 30
Respuesta: Enviar correo dentro de un case switch

No entiendo el por qué del archivo "usuario.entidad.php", no le veo la lógica para su uso, es decir, no lo veo necesario.

Mientras yo reviso tu código en cuanto pueda, porque´no me dices los errores que te saltan en el archivo .log de php cuando utilizas la lógica que te compartí.

Si no los compartes no podemos saber donde está falllando.
Gracias
  #7 (permalink)  
Antiguo 15/02/2017, 07:24
 
Fecha de Ingreso: julio-2014
Mensajes: 334
Antigüedad: 9 años, 9 meses
Puntos: 30
Respuesta: Enviar correo dentro de un case switch

He modificado la lógica de index.php, pues la clase Usuario no sirve para nada así que la he eliminado. También he modificado la clase UsuarioModel al haber eliminado la otra clase.

Esta modificación no está extenta de fallos, no la he probado, la he modificado en base a mi experiencia pero no te preocupes, el archivo .log te dirá donde están los fallos (que serán leves) y de ahí ya lo podrás arreglar todos tu solo.

index.php
Código PHP:
<?php 
session_start
(); 
if(!isset(
$_SESSION["user_id"]) || $_SESSION["user_id"]==null){ 
    print 
"<script>alert(\"Acceso invalido!\");window.location='../../login.php';</script>"


require_once 
'usuario.model.php';
include 
'enviar.php'

$model = new UsuarioModel(); 

$page 'index';

if(isset(
$_REQUEST['action'])) {
    foreach(
$_REQUEST as $key => $value) {
        if(
$key == 'action')
            $
$key $value# Convertimos el índice actino en una variable al cual le asignamos el valor correspondiente para cargar las diferentes funciones de $model de manera dinámica con solo usar su valor

        
if($action == 'actualizar' && $key == 'id')
            
$alm->__SET($key$value); # Solo si estamos actualizando, se añadirá a __SET el id del registro para actualizarlo

        
$alm->__SET($key$value); # Como estamos dentro de un bucle, estamos seteando cada valor de $_REQUEST dentro de la función __SET
    
}

    if(
$action == 'eliminar' || $action == 'editar')
        
$model->$action($id);
    else if(
$action != 'enviar')
        
$model->$action($alm); 

    if(
$action == 'enviar')
        
envioCorreo($_REQUEST);

    if(
$action != 'editar')
        
header('Location: ' $page '.php'); 
}
usuario.model.php
Código PHP:
<?php
class UsuarioModel {
    private 
$pdo;
 
    public function 
__CONSTRUCT()
    {
        try {
            
$this->pdo = new PDO('mysql:host=localhost;dbname=datos''usuario''clave');
            
$this->pdo->setAttribute(PDO::ATTR_ERRMODEPDO::ERRMODE_EXCEPTION);                
        } catch(
Exception $e) {
            die(
$e->getMessage());
        }
    }
 
    public function 
Listar()
    {
        try {
            
$stm $this->pdo->prepare("SELECT * FROM ingreso ORDER BY id DESC  LIMIT 5");
            
$stm->execute();
            
            while (
$row $stmt->fetch(PDO::FETCH_ASSOC))
                
$rows[] = $row;

            return 
$rows;

        } catch(
Exception $e) {
            die(
$e->getMessage());
        }
    }
 
    public function 
Editar($id)
    {
        try {
            
$stm $this->pdo->prepare("SELECT * FROM ingreso WHERE id = ?");
            
$stm->execute(array($id));

            while (
$row $stmt->fetch(PDO::FETCH_ASSOC))
                
$rows[] = $row;
 
            return 
$rows;

        } catch (
Exception $e) {
            die(
$e->getMessage());
        }
    }
 
    public function 
Eliminar($id)
    {
        try {
            
$stm $this->pdo->prepare("DELETE FROM ingreso WHERE id = ?");                      
            
$stm->execute(array($id));

        } catch (
Exception $e) {
            die(
$e->getMessage());
        }
    }
 
    public function 
Actualizar($data)
    {
        try {
            
$sql "UPDATE ingreso SET 
                        rif                 = ?,
                        nombre              = ?,
                        producto            = ?,
                        sistema_enc         = ?,
                        nro_cupon           = ?,
                        fecha_envio         = ?,
                        nota                = ?
                    WHERE id = ?"
;
            
$sql2 "INSERT INTO vitacora (rif, nombre, producto, sistema_enc, nro_cupon, fecha_envio, nota, id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
                    
            
$this->pdo->prepare($sql)->execute($data);
            
$this->pdo->prepare($sql2)->execute($data); 

        } catch (
Exception $e) {
            die(
$e->getMessage());
        }
    }
 
    public function 
Registrar($data) {
        try {
            
$sql "INSERT INTO ingreso (rif,nombre,producto,sistema_enc,nro_cupon,fecha_envio,nota) VALUES (?, ?, ?, ?, ?, ?, ?)";
 
            
$this->pdo->prepare($sql)->execute($data);
        
        } catch (
Exception $e) {
            die(
$e->getMessage());
        }
    }    
}
  #8 (permalink)  
Antiguo 15/02/2017, 13:41
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: Enviar correo dentro de un case switch

El problema es solo enviar el correo al actualizar los datos?

Sugerencia: en enviar.php toma la información desde el modelo (o entidad), en vez de $_REQUEST y, después de $modelo->actualizar($alm); agrega $modelo->enviar($alm);

Con eso debería funcionar.
__________________
- León, Guanajuato
- GV-Foto

Etiquetas: correo
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 18:17.