Foros del Web » Programando para Internet » PHP »

Como restar valores de un formulario con php y mysql?

Estas en el tema de Como restar valores de un formulario con php y mysql? en el foro de PHP en Foros del Web. Buenas tardes, tengo una base de datos con dos tablas, una para los usuarios y otra para los formularios y estoy trabajando con sesiones. Lo ...
  #1 (permalink)  
Antiguo 23/05/2017, 14:29
 
Fecha de Ingreso: septiembre-2013
Mensajes: 10
Antigüedad: 10 años, 7 meses
Puntos: 0
Como restar valores de un formulario con php y mysql?

Buenas tardes, tengo una base de datos con dos tablas, una para los usuarios y otra para los formularios y estoy trabajando con sesiones.

Lo que quiero es ponerla Prepago, que yo pueda ponerle a cada usuario el saldo inicial y se valla restando y al llegar a cero si intentan enviar un formulario le arroje un alerta que diga que su saldo no es suficiente.

Espero pueda ayudarme.
Gracias de antemano.
  #2 (permalink)  
Antiguo 23/05/2017, 14: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: Como restar valores de un formulario con php y mysql?

Tienes ya algún código?, sería conveniente que lo muestres para ver si podemos ayudarte.
__________________
- León, Guanajuato
- GV-Foto
  #3 (permalink)  
Antiguo 23/05/2017, 15:29
 
Fecha de Ingreso: septiembre-2013
Mensajes: 10
Antigüedad: 10 años, 7 meses
Puntos: 0
Respuesta: Como restar valores de un formulario con php y mysql?

Ok los codigos son los siguientes:

index.php

Código:
<?php require_once('Connections/conex.php'); ?>
<?php
//initialize the session
if (!isset($_SESSION)) {
  session_start();
}

// ** Logout the current user. **
$logoutAction = $_SERVER['PHP_SELF']."?doLogout=true";
if ((isset($_SERVER['QUERY_STRING'])) && ($_SERVER['QUERY_STRING'] != "")){
  $logoutAction .="&". htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_GET['doLogout'])) &&($_GET['doLogout']=="true")){
  //to fully log out a visitor we need to clear the session varialbles
  $_SESSION['MM_Username'] = NULL;
  $_SESSION['MM_UserGroup'] = NULL;
  $_SESSION['PrevUrl'] = NULL;
  unset($_SESSION['MM_Username']);
  unset($_SESSION['MM_UserGroup']);
  unset($_SESSION['PrevUrl']);
	
  $logoutGoTo = "login.php";
  if ($logoutGoTo) {
    header("Location: $logoutGoTo");
    exit;
  }
}
?>
<?php
if (!isset($_SESSION)) {
  session_start();
}
$MM_authorizedUsers = "Nivel 1,Nivel 2";
$MM_donotCheckaccess = "false";

// *** Restrict Access To Page: Grant or deny access to this page
function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { 
  // For security, start by assuming the visitor is NOT authorized. 
  $isValid = False; 

  // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. 
  // Therefore, we know that a user is NOT logged in if that Session variable is blank. 
  if (!empty($UserName)) { 
    // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. 
    // Parse the strings into arrays. 
    $arrUsers = Explode(",", $strUsers); 
    $arrGroups = Explode(",", $strGroups); 
    if (in_array($UserName, $arrUsers)) { 
      $isValid = true; 
    } 
    // Or, you may restrict access to only certain users based on their username. 
    if (in_array($UserGroup, $arrGroups)) { 
      $isValid = true; 
    } 
    if (($strUsers == "") && false) { 
      $isValid = true; 
    } 
  } 
  return $isValid; 
}

$MM_restrictGoTo = "login.php";
if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) {   
  $MM_qsChar = "?";
  $MM_referrer = $_SERVER['PHP_SELF'];
  if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&";
  if (isset($_SERVER['QUERY_STRING']) && strlen($_SERVER['QUERY_STRING']) > 0) 
  $MM_referrer .= "?" . $_SERVER['QUERY_STRING'];
  $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer);
  header("Location: ". $MM_restrictGoTo); 
  exit;
}
?>
<?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_login = "-1";
if (isset($_SESSION['MM_Username'])) {
  $colname_login = $_SESSION['MM_Username'];
}
mysql_select_db($database_conex, $conex);
$query_login = sprintf("SELECT * FROM usuarios WHERE usuario = %s", GetSQLValueString($colname_login, "text"));
$login = mysql_query($query_login, $conex) or die(mysql_error());
$row_login = mysql_fetch_assoc($login);
$totalRows_login = mysql_num_rows($login);
$_SESSION['name'] = $row_login['name'];


mysql_select_db($database_conex, $conex);
$res=mysql_query("SELECT precio FROM autogestion WHERE usuario = '".$_SESSION['MM_Username']."'");
while($row=mysql_fetch_assoc($res))
$total-=$row['precio'];

?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>.:Sistema de Autogestion Virtual:.</title>

<link href="css/estilos.css" rel="stylesheet" type="text/css">
<link href="fonts/style.css" rel="stylesheet" type="text/css">
</head>
<body background="images/bground.jpg" oncontextmenu="return false">

<div id="container">
<div id="header"><div id="logo">Sistema de Autogestion Virtual</div>
<div id="botones">
    <ul>  
		<li><a href="<?php echo $logoutAction ?>"><span class=" icon-swich"></span> Salir</a></li>  
		<li><a href="contacto.php" target="link"><span class=" icon-phone"></span> Contacto</a></li>
		<li><a href="registrar_pago.php" target="link"><span class="icon-credit-card"></span> Registrar Pago</a></li>
		<li><a href="perfil_de_usuario.php?usuario=<?php echo $_SESSION['MM_Username']; ?>" target="link"><span class="icon-user"></span> Perfil</a></li>
        <li><a href="index.php"><span class="icon-home"></span> Inicio</a></li>

    </ul>
    </div></div>
  <div id="main">
  <div id="notificacion"><div id="nombre"><div id="welcome">Bienvenido <?php echo $_SESSION['name']; ?></div></div><div id="search"></div><div id="precio"><div id="saldo">Su Saldo Es: <?php echo $total; ?> Bs.</div></div></div>
	<div id="menu">
    <div id="titulo">Menu Principal</div>
    <div id="nav">
    <ul>    
        <li><a href="activacion_de_lineas.php" target="link">Activacion de Lineas</a></li>
        <li><a href="lineas.php" target="link">Lineas HEX y MEID</a></li>
        <li><a href="cambio_de_serial.php" target="link">Cambio de Serial</a></li>
        <li><a href="cambio_de_plan.php" target="link">Cambio de Plan</a></li>
        <li><a href="servicios_de_datos.php" target="link">Servicios de Datos</a></li>
        <li><a href="consulta_de_datos.php" target="link">Consulta de Datos</a></li>
		<li><a href="recarga_de_saldo.php" target="link">Recarga de Saldo</a></li>
        <li><a href="actualizacion_de_datos.php" target="link">Actualizacion de Datos</a></li>
        <li><a href="consulta_negativo.php" target="link">Consulta de Negativos</a></li>
        <li><a href="agl.php" target="link">Atencion en Linea</a></li>
        <li><a href="http://ovam.movilnet.com.ve/OvamExtranet/Vistas/validar_usuario2.php" target="link">Extranet de Agentes</a></li>
 
    </ul>
    </div></div>
      <div id="contenido">
        <iframe src="listar.php" scrolling="auto"  name="link" frameborder="0">	</iframe>
      </a></div>
      <div id="footer">Diseñado Por Campos Technology &copy; 2017 Todos Los Derechos Reservados</div>
																																																																																															
  </div>
</div>
</body>
</html>
<?php
mysql_free_result($login);
?>
  #4 (permalink)  
Antiguo 23/05/2017, 15:31
 
Fecha de Ingreso: septiembre-2013
Mensajes: 10
Antigüedad: 10 años, 7 meses
Puntos: 0
Respuesta: Como restar valores de un formulario con php y mysql?

Formulario.php

Código:
<?php require_once('Connections/conex.php'); ?>
<?php
if (!isset($_SESSION)) {
  session_start();
}
$MM_authorizedUsers = "Nivel 1,Nivel 2";
$MM_donotCheckaccess = "false";

// *** Restrict Access To Page: Grant or deny access to this page
function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { 
  // For security, start by assuming the visitor is NOT authorized. 
  $isValid = False; 

  // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. 
  // Therefore, we know that a user is NOT logged in if that Session variable is blank. 
  if (!empty($UserName)) { 
    // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. 
    // Parse the strings into arrays. 
    $arrUsers = Explode(",", $strUsers); 
    $arrGroups = Explode(",", $strGroups); 
    if (in_array($UserName, $arrUsers)) { 
      $isValid = true; 
    } 
    // Or, you may restrict access to only certain users based on their username. 
    if (in_array($UserGroup, $arrGroups)) { 
      $isValid = true; 
    } 
    if (($strUsers == "") && false) { 
      $isValid = true; 
    } 
  } 
  return $isValid; 
}

$MM_restrictGoTo = "acceso.php";
if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) {   
  $MM_qsChar = "?";
  $MM_referrer = $_SERVER['PHP_SELF'];
  if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&";
  if (isset($_SERVER['QUERY_STRING']) && strlen($_SERVER['QUERY_STRING']) > 0) 
  $MM_referrer .= "?" . $_SERVER['QUERY_STRING'];
  $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer);
  header("Location: ". $MM_restrictGoTo); 
  exit;
}
?>
<?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_insert"])) && ($_POST["MM_insert"] == "form")) {
  $insertSQL = sprintf("INSERT INTO autogestion (usuario, operacion, precio, name, cedula, fn, serial, plan) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)",
                       GetSQLValueString($_POST['usuario'], "text"),
                       GetSQLValueString($_POST['operacion'], "text"),
					   GetSQLValueString($_POST['precio'], "text"),
                       GetSQLValueString($_POST['name'], "text"),
                       GetSQLValueString($_POST['cedula'], "text"),
                       GetSQLValueString($_POST['fn'], "text"),
                       GetSQLValueString($_POST['serial'], "text"),
					   GetSQLValueString($_POST['plan'], "text"));

  mysql_select_db($database_conex, $conex);
  $Result1 = mysql_query($insertSQL, $conex) or die(mysql_error());

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

mysql_select_db($database_conex, $conex);
$query_sagv = "SELECT * FROM autogestion";
$sagv = mysql_query($query_sagv, $conex) or die(mysql_error());
$row_sagv = mysql_fetch_assoc($sagv);
$totalRows_sagv = mysql_num_rows($sagv);
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">

<title>Documento sin título</title>
<link href="css/estilos.css" rel="stylesheet" type="text/css">
</head>

<body oncontextmenu="return false">
<div id="formulario">
<div id="encabezado">Activacion de Lineas CDMA y GSM</div>

<form action="<?php echo $editFormAction; ?>" method="POST" name="form" target="link">

<input type="hidden" name="usuario" value="<?php echo $_SESSION['MM_Username']; ?>">
<input type="hidden" name="operacion" value="Activacion de Linea">
<input type="hidden" name="precio" value="4000">

<label id="label_name">Nombre y Apellido:</label>
<input type="text" name="name" placeholder="Nombre y Apellido">

<label id="label_cedula">Cedula de Identidad:</label>
<input type="text" name="cedula" placeholder="Cedula de Identidad">

<label id="label_fn">Fecha de Nacimiento:</label>
<input type="text" name="fn" placeholder="Fecha de Nacimiento">

<label id="label_serial">Serial o Sim Card a Conectar:</label>
<input type="text" name="serial" placeholder="Serial o Sim Card a Conectar">

<label id="label_plan">Seleccione Plan a Activar:</label>
<select name="plan">
  <option value="">Seleccione</option>
  <option value="PLAN CONECTADOS">PLAN CONECTADOS</option>
  <option value="INTELIPLAN 100">INTELIPLAN 100</option>
  <option value="INTELIPLAN 400">INTELIPLAN 400</option>
  <option value="INTELIPLAN 1.2">INTELIPLAN 1.2</option>
  <option value="INTELIPLAN 3.2">INTELIPLAN 3.2</option>
  <option value="BB ULTRA">BB ULTRA</option>
  
</select>

<input name="procesar" type="submit" id="procesar" value="Procesar">
<input  id="cancelar" type="button" value="Cancelar" onclick="location.href = 'listar.php'">


<div id="linea">
<br><font color="red">CONDICIONES:</font><br>
Costo del requerimiento 4000 Bs.<br>
Una vez Procesado el requerimiento<br>
Tiene un Lapso de 24 Horas Para Cancelarlo.<br>
</div>
<input type="hidden" name="MM_insert" value="form">

</form>

</div>
</body>
</html>
<?php
mysql_free_result($sagv);
?>
Espero Pueda Ayudarme.
Saludos
  #5 (permalink)  
Antiguo 25/05/2017, 20:09
 
Fecha de Ingreso: septiembre-2013
Mensajes: 10
Antigüedad: 10 años, 7 meses
Puntos: 0
Respuesta: Como restar valores de un formulario con php y mysql?

Buenas noches amigos del foro.

Podra alguien ayudarme con mi consulta?

Por favor.
  #6 (permalink)  
Antiguo 26/05/2017, 19:21
Avatar de xfxstudios  
Fecha de Ingreso: junio-2015
Ubicación: Valencia - Venezuela
Mensajes: 2.448
Antigüedad: 8 años, 10 meses
Puntos: 263
Respuesta: Como restar valores de un formulario con php y mysql?

Cita:
Iniciado por xagentex Ver Mensaje
Buenas noches amigos del foro.

Podra alguien ayudarme con mi consulta?

Por favor.
Código PHP:
Ver original
  1. $a = $this->con->query("UPDATE tabla SET campo = ('campo'-$valor) WHERE campo = $loquesea");

asi podrias ir realizando restas de saldo directamente en mysql, bueno es lo que hago en algunos casos que tengo, por otro lado, es válidar la informacion del saldo al momento de cargar la pagina, de esa manera bloqueas o no imprimes formularios directamente desde el server.

Otra opcion es validar el saldo con cada peticion y bloquear la misma si el saldo es insuficiente.

Valla hay unas cuantas maneras de hacer lo que buscas.

Saludos
__________________
[email protected]
HITCEL

Etiquetas: formulario, restar, tabla
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 04:13.