Send variable php for method post - php

I get a var called $cobro in this module php, and i need this variable for calculate a subtraction of a number insert in a input called $vuelto. When i send the form the var $cobro is eliminated and i cant execute the subtraction.
Help, and thx !
<?php
// Disponible desde PHP 4.1.0
date_default_timezone_set("America/Santiago");
if(isset($_POST['fecha'])){
$fecha = date("Y-m-d G:i:s",strtotime($_POST['fecha']));
}
$date1 = strtotime($fecha);
$date2 = time();
$subTime = $date2-$date1;
$y = ($subTime/(60*60*24*365));
$d = ($subTime/(60*60*24))%365;
$h = ($subTime/(60*60))%24;
$m = ($subTime/60)%60;
echo "Diferencia entre ".$fecha." y ".date('Y-m-d H:i:s',$date2)." es:<br/>";
//echo $y." annos<br/>";
echo $d." dias<br/>";
echo $h." horas<br/>";
echo $m." minutos<br/>";
$cobro =0;
$fecha_em= date('Y-m-d H:i:s',$date2);
$h = $h + $m/60 +$d*24;
$cobro = $h*600;
if($cobro<0)
$cobro = $cobro*-1;
if($h < 1)
echo "Debe pagar el minimo: $600";
else
echo "Debe pagar: $".$cobro;
$conexion = mysql_connect("localhost","grupo2","face2014");
mysql_select_db("sisace",$conexion);
/*if ($conexion==0)
echo "Lo sentimos, no se ha podido conectar con la MySQL";
else {
echo "Se logró conectar con MySQL";
echo "<br>";}
*/
$sql="INSERT INTO boleta(fecha_emision,fecha_ingreso,num_boleta,valor_total) ".
"VALUES('$fecha_em','$fecha','1','$cobro')";
mysql_query($sql);
if(isset($_POST['submit'])) {
$vuelto = $_POST['vuelto'];
$vuelto = $vuelto -$cobro;
echo "Su vuelto es el siguiente:";
echo $vuelto;
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="number" name="vuelto"><br>
<input type="submit" name="submit" value="Submit Form"><br>
</form>

You didn't put it in Form use input hidden to post it
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="number" name="vuelto"><br>
<input type="hidden" name="cobro" value="<?php echo $cobro; ?>">
<input type="submit" name="submit" value="Submit Form"><br>
</form>
That's how you can pass cobro variable value which will be available in $_POST['cobro']

Related

Calendar in php and html

I'm developing a calendar with reservations in HTML and PHP (I do not know how to do otherwise). Only I have a problem with formats and data.
First of all I have problems regarding the date, I had to set it as "integer" on Postgresql and consequently on the form html as text (and this is the first thing I would like to change).
Same thing regarding the timetable.
form.php
<?php
if (isset($_POST['submit']) && $_POST['submit']=="invia")
{
$titolo = addslashes($_POST['titolo']);
$testo = addslashes($_POST['testo']);
$str_data = strtotime($_POST['data']);
include 'config.php';
$sql = "INSERT INTO appuntamenti (titolo,testo,str_data ) VALUES ('$titolo', '$testo', '$str_data')";
if($result = pg_query($sql))
{
echo "Inserimento avvenuto con successo.<br>
Vai al Calendario";
}
}else{
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Titolo:<br>
<input name="titolo" type="text"><br>
Testo:<br>
<textarea name="testo" cols="30" rows="8"></textarea><br>
Data:<br>
<input name="data" type="text" value="gg-mm-aaaa"><br>
Orario:<br>
<input name="hour" type="time" ><br> -->
<input name="submit" type="submit" value="invia">
</form>
<?php
}
?>
appuntamenti.php
<?php
if(isset($_GET['day']) && is_numeric($_GET['day']))
{
$day = $_GET['day'];
include 'config.php';
$sql = "SELECT * FROM appuntamenti WHERE str_data=$day";
$result = pg_query($sql);
if(pg_num_rows($result) > 0)
{
while($fetch = pg_fetch_array($result))
{
$id = stripslashes($fetch['id']);
$titolo = stripslashes($fetch['titolo']);
$testo = stripslashes($fetch['testo']);
$data = date("d-m-Y", $fetch['str_data']);
$hour = date("hh-mm", $fetch['hour']);
echo "Appuntamenti del <b>$data</b> delle <b>$hour</b><br>" . $titolo . "<br>" . $testo . "<br>
Cancella |
Modifica
<hr>";
}
}
}
?>
In this case i receive the date in the correct way ( but the user inserts this like text, and i don't want to do this. ) and the hours likes 0101-0101.
How can i solve?
Thanks you all

Modify DB row after query PHP

I'm trying to modify my DB after a query. My goal is this: query the values, echo them with a little modify form that, if I hit "modify", the values will be modified in the DB. I don't know if I'm being clear enough, so here's my code, maybe it'll help me explain.
<h3>¿Quieres editar tu receta?</h3>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<h3>Introduce tu email: </h3><input type="text" name="email" placeholder="email"/><br/>
<input type="submit" name="editar" value="Buscar mi receta" class="send-btn">
</form>
<?php
date_default_timezone_set('Europe/Madrid');
$link = mysqli_connect("localhost", "root", "root", "db_csw");
if(!$link){
die("Conexion fallida: ". mysqli_error());
}
if(isset($_POST['editar'])){
$email = $_POST["email"];
$query = "SELECT * FROM datosformulario WHERE email LIKE '%".$email."%'";
$res = mysqli_query($link, $query);
if($res !== false && mysqli_num_rows($res) > 0){
while ($aux = mysqli_fetch_array($res)){
$accion = $_SERVER['PHP_SELF'];
$id = $aux['id'];
echo "Nombre de la receta: ".$aux['nombrereceta']."<br>";
echo "Pasos de la receta: ".$aux['pasosreceta']."<br>";
echo "<br><br>";
echo "¿Quieres editar esta receta?<br/>";
echo "<form method='POST' action='".$accion."'>";
echo "<input type='text' name='nombreRecetaEditada' placeholder='Nombre de la receta'/><br/>";
echo "<textarea cols='42' rows='10' name='pasosRecetaEditada' placeholder='Pasos de la receta'></textarea><br/>";
echo "<input type='submit' name='editarReceta' value='Editar' class='send-btn'><br/>";
echo "</form>";
if(isset($_POST["editarReceta"])){
$nombreRecetaEditada = $_POST["nombreRecetaEditada"];
$pasosRecetaEditada = $_POST["pasosRecetaEditada"];
$actualizaReceta = "UPDATE datosformulario SET nombrereceta='$nombreRecetaEditada',pasosreceta='$pasosRecetaEditada' WHERE id=$id";
$exito = mysqli_query($link, $actualizaReceta);
if($exito !== false){
echo "Receta modificada";
} else {
echo "No se pudo modificar la receta";
}
}
}
} else {
echo "El email introducido no se ha usado para enviar ninguna receta. Por favor, prueba de nuevo";
}
}
mysqli_close($link);
?>
Thanks in advance.
The problem is, the control will never reach to this if(isset($_POST["editarReceta"])){ ... block even though you've click on the submit button the update the values in the table. And that's because it has to cross this if(isset($_POST['editar'])){ ... block to reach the former mentioned if block.
The solution is, take this entire if(isset($_POST["editarReceta"])){ ... } outside of the if(isset($_POST['editar'])){ ... } block, like this:
// your code
if(isset($_POST["editarReceta"])){
...
}
if(isset($_POST['editar'])){
...
}
// your code
Also, to get the $id value in the UPDATE query, you have to change the form's action attribute in the following way,
echo "<form method='POST' action='".$accion."?id='".$id.">";
So that you could catch the appropriate $id in the following way,
$id = (int)$_GET['id'];
Here's the complete code,
<h3>¿Quieres editar tu receta?</h3>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<h3>Introduce tu email: </h3><input type="text" name="email" placeholder="email"/><br/>
<input type="submit" name="editar" value="Buscar mi receta" class="send-btn">
</form>
<?php
date_default_timezone_set('Europe/Madrid');
$link = mysqli_connect("localhost", "root", "root", "db_csw");
if(!$link){
die("Conexion fallida: ". mysqli_error());
}
if(isset($_POST["editarReceta"])){
$id = (int)$_GET['id'];
$nombreRecetaEditada = $_POST["nombreRecetaEditada"];
$pasosRecetaEditada = $_POST["pasosRecetaEditada"];
$actualizaReceta = "UPDATE datosformulario SET nombrereceta='$nombreRecetaEditada',pasosreceta='$pasosRecetaEditada' WHERE id=$id";
$exito = mysqli_query($link, $actualizaReceta);
if($exito !== false){
echo "Receta modificada";
} else {
echo "No se pudo modificar la receta";
}
}
if(isset($_POST['editar'])){
$email = $_POST["email"];
$query = "SELECT * FROM datosformulario WHERE email LIKE '%".$email."%'";
$res = mysqli_query($link, $query);
if($res !== false && mysqli_num_rows($res) > 0){
while ($aux = mysqli_fetch_array($res)){
$accion = $_SERVER['PHP_SELF'];
$id = $aux['id'];
echo "Nombre de la receta: ".$aux['nombrereceta']."<br>";
echo "Pasos de la receta: ".$aux['pasosreceta']."<br>";
echo "<br><br>";
echo "¿Quieres editar esta receta?<br/>";
echo "<form method='POST' action='".$accion."?id='".$id.">";
echo "<input type='text' name='nombreRecetaEditada' placeholder='Nombre de la receta'/><br/>";
echo "<textarea cols='42' rows='10' name='pasosRecetaEditada' placeholder='Pasos de la receta'></textarea><br/>";
echo "<input type='submit' name='editarReceta' value='Editar' class='send-btn'><br/>";
echo "</form>";
}
} else {
echo "El email introducido no se ha usado para enviar ninguna receta. Por favor, prueba de nuevo";
}
}
mysqli_close($link);
?>
Sidenote: Learn about prepared statement because right now your queries are susceptible to SQL injection. Also see how you can prevent SQL injection in PHP.

Var not affected on mysql

Good morning all !
I have a problem with a var in my code :
<?Php
error_reporting(E_ALL);
//Si IP correspond pas au PC autorisé, on retourne au debut.
include "./_protection.php";
$data='';
$rep='';
$requete='';
$val = '';
$Reference= '';
echo '<h2><u>Commander des pièces</u></h2><br>';
/*****************************************************************************************************
* AJOUT DE PIECE DANS LA BASE DE DONNEES
*****************************************************************************************************/
if(#$_POST['action'] == "ajouter")
{
if(!empty($_POST['choix'])){
foreach($_POST['choix'] as $val){
$Reference.="$val,";
}
//Injection dans la base SQL
include "./../connexion.inc";
mysql_query("INSERT INTO `tbl_commandes` ( `id`, `Eleve`, `Reference`, `Quantite`, `Date`, `Statut` )
VALUES ( '', '".$_POST['Eleve']."', '".$_POST['Reference']."', '".$_POST['Quantite']."', '".$_POST['Date']."', '".$_POST['Statut']."' )");
mysql_close();
}
}
/*****************************************************************************************************
* FORMULAIRE POUR L'AJOUT DE PIECE
*****************************************************************************************************/
echo '
<fieldset>
<legend>Commander des Pièces</legend>
<FORM action="./?page=commande_piece_full_php" method="POST">
<p align="left">
<H2>Pièces :</h2>
<br>';
echo $Reference;
include "./../connexion.inc";
$rep = mysql_query("SELECT id_categorie_piece, categorie_piece FROM tbl_categorie_piece ORDER BY categorie_piece");
mysql_close();
include "./../connexion.inc";
while($data = mysql_fetch_array($rep))
{
echo $data['categorie_piece'];
echo '<br>';
$requete = $data['id_categorie_piece'];
$reponse = mysql_query("SELECT id_piece, piece FROM tbl_piece WHERE idr_categorie_piece='$requete' ORDER BY piece");
while($donnees = mysql_fetch_array($reponse)){
?> <input type="checkbox" name="choix[]" value="<? echo $donnees['id_piece'] ?>"><? echo $donnees['piece'] ?><br> <?
}
echo '<br>';
}
mysql_close();
echo '
Elève :
<select name="Eleve">';
include "./../connexion.inc";
$reponse2 = mysql_query("SELECT id_client, client FROM tbl_client ORDER BY client");
while($donnees2 = mysql_fetch_array($reponse2))
{
?> <option value="<? echo $donnees2['client'] ?>"><? echo $donnees2['client'] ?></option> <?
}
mysql_close();
echo '
</select>
<br>
Date souhaitée : <input type="textbox" name="Date">
<br>
Quantité : <input type="textbox" name="Quantite">
<br>
<input type="submit" value="ajouter">
<input type="hidden" name="action" value="ajouter">
</form>
</fieldset>';
?>
my var $reference is Ok, i can echo $reference; and get the content rightly
BUT when i wanna send $reference to my mysql table .. that doesn't send it
When i submit, i get this notice from the parser : Notice:
Undefined index: Reference in /home/bddstock/www/admin/commande_piece_full_php.php on line 27
but when it is submited i get the right content in my echo line under PIECES
so i really don't understand ..
can someone help me ?
Change your insert statement to
mysql_query("INSERT INTO `tbl_commandes` ( `id`, `Eleve`, `Reference`,
`Quantite`, `Date`, `Statut` )
VALUES ( '', '".$_POST['Eleve']."', '".$Reference."', '".$_POST['Quantite']."', '".$_POST['Date']."', '".$_POST['Statut']."' )");
i.e change $_POST['Reference'] to $Reference as you have not posted this field and it seems you derive it from looping $_POST['choix'].
Note : use mysqli instead of mysql and refer How can I prevent SQL injection in PHP?

Can 2 $_POST conflict with eachother?

So I am trying to use the intel I got on the first $_POST on the second $_POST but when the second occurs the intel from the first is lost, what can I do to overcome this?
<?php
if(isset($_POST['entrar'])) {
$nr_processo = $_POST['nr_processo'];
echo "$nr_processo";
$aluno = mysql_query("SELECT * FROM alunos WHERE nr_processo = '$nr_processo'");
$row = mysql_fetch_array($aluno) or die ("Este numero de processo não está registado " . mysql_error()) ;
$aluno_nome = $row['nome'];
$aluno_ano = $row['ano'];
$aluno_turma = $row['turma'];
$aluno_ciclo = $row['ciclo'];
echo $aluno_nome, $aluno_ano, $aluno_turma, $aluno_ciclo;
}
?>
<form method="post" action="">
<label> A que se deve a tua visita ah biblitoeca?</label><br>
<label> Estudo/pesquisa</label>
<input name="estudo" value="1" type="checkbox">
<br>
<label> Leitura Periódica</label>
<input name="leitura" value="1" type="checkbox">
<br>
<label>Internet</label>
<input name="net" value="1" type="checkbox">
<br>
<label> Audiovisuais</label>
<input name="audiovisuais" value="1" type="checkbox"> <br>
<input name="enviar" value="Enviar" type="submit">
</form>
<?php
if(isset($_POST['enviar'])) {
$estudo = $_POST['estudo'];
$leitura = $_POST['leitura'];
$internet = $_POST['net'];
$audiovisuais = $_POST['audiovisuais'];
echo $aluno_nome;
$data = date('Y-m-d ');
$hora = date('H:i:s');
echo $data, $hora;
mysql_query("INSERT INTO entradas VALUES('', '$nr_processo', '$aluno_ano', '$aluno_turma', '$estudo', '$leitura', '$internet', '$audiovisuais', '$data', '$hora' )") ;
?>
<!-- <META http-equiv="refresh" content="0;URL=http://localhost/registosbib/agradecimento.php"> -->
<?php
}
?>
You post entrar and enviar in the same request or 2 different requests ?
Edit:
The 2 $_POST doesn't conflict
Fix:
Use $_SESSION instead
session_start();
$_SESSION['row'] = $row;
Then in the second $_POST use $_SESSION['row']['nome'] instead of $aluno_nome and other $aluno_* variables

can´t update my database

So, I'm getting an id_cliente from another php and I get it correctly from that id. I want to update my database but I can't find a way to do it. I've tried UPDATE, a friend of mine checked the code for syntax error, but I still want to see if any of use were wrong.
Here's my body:
<body>
<div class="maindiv">
<div class="form_div">
<div class="title">
<h2>Insertando datos a la tabla de Cliente.</h2>
</div>
<?php
$id_cliente = $_POST['id_cliente'];
?>
<form action="actualizar.php" method="post">
<?php
$query= "SELECT * FROM cliente WHERE $id_cliente = id_cliente";
include "../conexion/conexion.php";
$sql = mysqli_query($conn, $query);
if(empty($sql)) echo "No se encontró ningún personal que coincida con la búsqueda";
else{
while($row = mysqli_fetch_object($sql)){ ?>
<h2>Llena todos los campos.</h2>
<label>Clave:</label>
<input class="input" name="clave" type="number" value="<?php echo $row->CLAVE ?>">
<label>Nombre:</label>
<input class="input" name="nombre" type="text" value="<?php echo $row->NOMBRE ?>">
<label>Apellido Paterno:</label>
<input class="input" name="apellido_p" type="text" value="<?php echo $row->APELLIDO_P ?>">
<label>Apellido Materno:</label>
<input class="input" name="apellido_m" type="text" value="<?php echo $row->APELLIDO_M ?>">
<label>Direccion:</label>
<textarea cols="25" name="direccion" rows="5"><?php echo $row->DIRECCION ?></textarea><br>
<label>Telefono:</label>
<input class="input" name="telefono" type="text" value="<?php echo $row->TELEFONO ?>">
<label>Correo:</label>
<input class="input" name="correo" type="text" value="<?php echo $row->CORREO ?>">
<label>Fecha de Nacimiento (AA/MM/DD):</label>
<input class="input" name="fecha" type="date" value="<?php echo $row->NACIMIENTO ?>">
<label>Saldo:</label>
<input class="input" name="saldo" type="number" value="<?php echo $row->SALDO ?>">
<?php } $conn->close(); } ?>
<?php
$connection = mysqli_connect("localhost", "root", "");
$db = mysqli_select_db($connection,"cajadeahorros");
error_reporting(0);
if(isset($_POST['submit']))
{
if($_POST['id_cliente'] == "") $_POST['id_cliente'] = "NULL";
$clave = $_POST['clave'];
$nombre = $_POST['nombre'];
$apellido_p = $_POST['apellido_p'];
$apellido_m = $_POST['apellido_m'];
$direccion = $_POST['direccion'];
$telefono = $_POST['telefono'];
$correo = $_POST['correo'];
$fecha = $_POST['fecha'];
$saldo = $_POST['saldo'];
$q="select count(1) from cliente where clave='$clave'";
$r=mysqli_query($connection,$q);
$row=mysqli_fetch_row($r);
if($row[0]>=1)
{
$x = 1;
}
else
{
$x = 0;
}
if($clave !=''&&$nombre !=''&&$apellido_p !=''&&$apellido_m !=''&&$direccion !=''&&$telefono !=''&&$correo !=''&&$fecha !=''&&$saldo !=''&&$x==0)
{
$query = mysqli_query($connection, "update cliente set clave = 'a', nombre = 'a', apellido_p='a', apellido_m='a', direccion ='a', correo='a', nacimiento='a', saldo='a' where id_cliente = '$id_cliente'");
echo "<br/><br/><span>Datos ingresados correctamente.</span>";
}
else
{
echo "<p>No se pudo insertar. <br/> Algunos campos estan vacios o la clave ya existe.</p>";
}
}
mysqli_close($connection);
?>
<input class="submit" name="submit" type="submit" value="Insertar">
</form>
</div>
</div>
</body>
Please change the top select query which you have given like
$query= "SELECT * FROM cliente WHERE $id_cliente = id_cliente";
to
$query= "SELECT * FROM cliente WHERE id_cliente = $id_cliente";

Categories