getting form inputs values and passing to php variables - php

I'm configurating a tpv implemented in php.
This is the file which tpv commerce gave to me:
form.php
<?PHP
// If form is submitted with all required data then show the form
// else show error page
empty($Formulario) ?
ShowForm($Ds_Merchant_Amount,$Ds_Merchant_Currency,$prod) :
ShowError();
exit;
?>
<?PHP
function ShowError () {
echo "<table width=100% height=50%><tr><td><p><h2><center>Compruebe que todos los datos del formulario son correctos!!</center></h2></p></td></tr></table>\n";
} # End of function ShowError
function ShowForm ($amount,$currency,$producto) {
// Posted data
global $_POST;
// Valores constantes del comercio
$url_tpvv='xxxxxxxxxxxx';
$clave='xxxxxxxxxx';
$name='Panel piedra';
$code='xxxxxxxxxxxxxxx';
$terminal='1';
$order=date('ymdHis');
$amount = '50'; //importe
$currency='978';
$transactionType='0';
$urlMerchant=''; //ruta a fichero que notifica por email
$producto = 'Zapatos';
//$producto = '<script>'$('#requiredinput1').val()'</script>'; //nºfactura y producto
// Now, print the HTML script
echo "
<script language=JavaScript>
function calc() {
$('#Ds_Merchant_Amount').val( $('#requiredinput2').val() );
$('#Ds_Merchant_Producto').val( $('#requiredinput1').val() );
if($('#requiredinput1').val()==''){
alert('Es necesario introducir nºfactura y concepto');
return;
}
else if($('#requiredinput2').val()==''){
alert('Es necesario introducir el importe de la factura');
return;
}
else if($('#requiredinput3').val()==''){
alert('Es necesario introducir el email');
return;
}
vent=window.open('','tpv','width=725,height=600,scrollbars=no,resizable=yes,status=yes,menubar=no,location=no');
document.forms[0].submit();}
</script>
<body bgcolor=white>
<form name=compra action=$url_tpvv method=post target=tpv>
<pre>
<table>
<tr><td>";
echo "</td>
</tr><tr><td>
<input type='text' name='requiredinput1' id='requiredinput1' placeholder='Introduzca nºfactura y concepto' style='width: 250px;height: 30px;'/><br>
<input type='text' name='requiredinput2' id='requiredinput2' placeholder='Introduzca el importe de la factura' style='width: 250px;height: 30px;margin-top: 1em;'/> <br>
<input type='text' name='requiredinput3' id='requiredinput3' placeholder='Introduzca email' style='width: 250px;height: 30px;margin-top: 1em;margin-bottom: 1em;'/> <br>
<input type='hidden' name='Ds_Merchant_Amount' value='$amount' />
</td></tr><tr><td>
<input type=hidden name=Ds_Merchant_Currency value='$currency'>
</td></tr><tr><td>
<input type=hidden name=Ds_Merchant_Producto value='$producto'>
</td></tr><tr><td>
<input type=hidden name=Ds_Merchant_Order value='$order'>
</td></tr><tr><td>
<input type=hidden name=Ds_Merchant_MerchantCode value='$code'>
</td></tr><tr><td>
<input type=hidden name=Ds_Merchant_Terminal value='$terminal'>
</td></tr><tr><td>
<input type=hidden name=Ds_Merchant_TransactionType value='$transactionType'>
</td></tr><tr><td>
<input type=hidden name=Ds_Merchant_MerchantURL value='$urlMerchant'>
</td></tr><tr><td>";
// Compute hash to sign form data
// $signature=sha1_hex($amount,$order,$code,$currency,$clave);
$message = $amount.$order.$code.$currency.$transactionType.$urlMerchant.$clave;
$signature = strtoupper(sha1($message));
echo "<input type=hidden name=Ds_Merchant_MerchantSignature value='$signature'>
</td></tr>
</table>
<center><a href='javascript:calc()' class='realizarpago'>Realizar pago</a></center>
</pre>
</form>
";
} # End of function ShowForm
?>
Observe, for example, the amount. It's a variable, with a constant value, but I need to assign it the value introduced by the user.
Could you help me, please?
Thanks, Daniel

You have access to the submitted form values via the $_POST superglobal.
For example, if your form field is named amount, you can access the value using $_POST['amount']. That's the value you can assign to the $amount variable in your script.
You don't need the global $_POST; line.
Reference: http://php.net/manual/en/reserved.variables.post.php
EDIT: When you deal with form input, do not forget to sanitize it.

I finally solved it.
I had to move input visible fields (which the user has to populate) to another firstly form.
firstform.php
<form action="tpv.php" method="POST">
<input type='text' name='requiredinput1' id='requiredinput1' placeholder='Introduzca nºfactura y concepto' style='width: 250px;height: 30px;'/><br>
<input type='text' name='requiredinput2' id='requiredinput2' placeholder='Introduzca el importe de la factura' style='width: 250px;height: 30px;margin-top: 1em;'/> <br>
<input type='text' name='requiredinput3' id='requiredinput3' placeholder='Introduzca email' style='width: 250px;height: 30px;margin-top: 1em;margin-bottom: 1em;'/> <br>
<input type="submit" value="Realizar pago" />
</form>
This is the first, in which I populate three data (description , amount, email) , and send them to tpv.php . So, in tpv.php , I pick up them by using $_POST
tpv.php
<?PHP
// If form is submitted with all required data then show the form
// else show error page
empty($Formulario) ?
ShowForm($Ds_Merchant_Amount,$Ds_Merchant_Currency,$prod) :
ShowError();
exit;
?>
<?PHP
function ShowError () {
echo "<table width=100% height=50%><tr><td><p><h2><center>Compruebe que todos los datos del formulario son correctos!!</center></h2></p></td></tr></table>\n";
} # End of function ShowError
function ShowForm ($amount,$currency,$producto) {
// Posted data
global $_POST;
// Valores constantes del comercio
$url_tpvv='xxxx';
$clave='xxxx';
$name='Panel piedra';
$code='xxxx';
$terminal='1';
$order=date('ymdHis');
$amount = $_POST['requiredinput2']; //importe
$currency='978';
$transactionType='0';
$urlMerchant=''; //ruta a fichero que notifica por email
$producto = $_POST['requiredinput1'];
// Now, print the HTML script
echo "
<body bgcolor=white>
<form name=compra action=$url_tpvv method=post target=tpv>
<pre>
<table>
<tr><td>";
echo "</td>
</tr><tr><td>
<input type='hidden' name='Ds_Merchant_Amount' value='$amount' />
</td></tr><tr><td>
<input type=hidden name=Ds_Merchant_Currency value='$currency'>
</td></tr><tr><td>
<input type=hidden name=Ds_Merchant_Producto value='$producto'>
</td></tr><tr><td>
<input type=hidden name=Ds_Merchant_Order value='$order'>
</td></tr><tr><td>
<input type=hidden name=Ds_Merchant_MerchantCode value='$code'>
</td></tr><tr><td>
<input type=hidden name=Ds_Merchant_Terminal value='$terminal'>
</td></tr><tr><td>
<input type=hidden name=Ds_Merchant_TransactionType value='$transactionType'>
</td></tr><tr><td>
<input type=hidden name=Ds_Merchant_MerchantURL value='$urlMerchant'>
</td></tr><tr><td>";
// Compute hash to sign form data
// $signature=sha1_hex($amount,$order,$code,$currency,$clave);
$message = $amount.$order.$code.$currency.$transactionType.$urlMerchant.$clave;
$signature = strtoupper(sha1($message));
echo "<input type=hidden name=Ds_Merchant_MerchantSignature value='$signature'>
</td></tr>
</table>
</pre>
</form>
<script language=JavaScript>
vent=window.open('','tpv','width=725,height=600,scrollbars=no,resizable=yes,status=yes,menubar=no,location=no');
document.forms[0].submit();
</script>
";
} # End of function ShowForm
?>
I hope that this answer helps others users.
Regards.

Related

How delete a row with php in mysql?

I have this code and i'm doing a dropdown to people choose what notice they want to delete, but i don't know what is wrong in my code......i'm new..so sorry for my ignorance
PHP code:
<?php
include('configdb.php')
if(isset($_POST['delete']))
{
$query_delete = "DELETE from artigos where idartigos >0";
$resultado_delete = mysqli_query($mysqli,$query_delete) or
die(mysqli_error($mysqli));
if($resultado_delete)
{
echo "
<script language='JavaScript'>
window.alert('Notícia eliminada com sucesso. Clique para voltar à página inicial.')
window.location.href='index.php';
</script>";
}
else
{
echo "
<script language='JavaScript'>
window.alert('Não foi possível apagar a sua notícia. Tente novamente, sff. Clique para voltar à página inicial.')
window.location.href='index.php';
</script>";
}
}
?>
HTML CODE:
<h1>Apagar notícia</h1>
<a>Notícias disponíveis</a><br><br>
<select name="delete" style="width:332px">
<?php echo $artigos; ?>
</select><br><br>
<p>eliminar
<input type="submit" name="submit" id="submit" action= "delete.php" value="delete" />
</p>
This is how it looks:
<form action="delete.php">
<select name="delete">
<option value=" ">blank</option>
<option value=" <?php echo $artigos; ?> "> <?php echo $artigos; ?> </option>
</select>
<input type="submit" value="Submit">
</form>

Update Mysql with form

I would like to update a sql table with a html form. I would like to select the element with a drop-down list and later update the values with the form.
Here is my code, the drop-down list and the form works, but I didn't know how to make that the php code get the element that I select.
HTML form:
<?php
require("conectarBD.php");
$select = "SELECT id_serie, nombre FROM series";
$result = $conectar->query($select);
?>
Selecciona la serie que quieres modificar:
<br>
<select>
<?php
while ( $row = $result->fetch_array() )
{
?>
<option value=" <?php echo $row['id_serie'] ?> " >
<?php echo $row['nombre']; ?>
</option>
<?php
}
?>
</select>
<form action="modificar_serie.php" method="post">
<p>
Introduce los cambios a realizar:
</p>
<p>
<label for="textfield">Nombre</label>
<input type="text" name="nom" id="nom" />
<label for="textarea"></label>
</p>
<p>
<label for="textfield">Temporadas</label>
<input type="number" name="temp" id="temp" />
<label for="textarea"></label>
</p>
<p>
<label for="textfield"> Año de estreno</label>
<input type="text" name="est" id="est" />
<label for="textarea"></label>
</p>
<input type="Submit" value="Actualizar">
</form>
PHP:
<?php
require("conectarBD.php");
$nombre = $_POST["nombre"];
$temp = $_POST["temp"];
$est = $_POST["est"];
$query="UPDATE series SET nombre = '.$nombre.', temporadas = '.$temp.', estreno= '.$est.' WHERE nombre='$nombre'";
mysqli_query($conectar,$query);
if(mysqli_affected_rows()>=0){
echo "<p>($nombre) Datos Actualizados<p>";
}else{
echo "<p>($nombre) No se ha podido actualizar en estos momentos<p>";
}
header("Location: ../index.php");
?>
Your select element must be inside form and have a name. Then you will be able to get a value of it from $_POST.

Send variable php for method post

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']

echo on html just prints one word of a sentence

We are getting the values from the select and then trying to print them on a textbox so we can edit it. But when test it, the echo on the value just returns the first word of the sentence that is inside the column. For example our row[2] is the column "Nombre" with the value "estadio nacional", when we print it, the echo only return "estadio".
<!DOCTYPE html>
<html>
<head>
<title>Editar Estadio</title>
</head>
<body>
<h1>Editar Estadios</h1>
<?php
// Conectando y seleccionado la base de datos
$dbconn = pg_connect("host=localhost dbname=tarea3 user=postgres password=12345")
or die('No se ha podido conectar: ' . pg_last_error());
$id_1 = $_GET["id"];
$result=pg_query("SELECT * FROM estadio where id_estadio='".$id_1."'");
$row=pg_fetch_row($result, 0, PGSQL_NUM);
echo $row[2];
$nombre = $row[2];
?>
<form method ='post' action='checkaddestadio.php'>
<pre>
Nombre: <input type='text' name='Nombre' value=<?php echo $nombre ?>>
Capacidad: <input type='text' name='Capacidad' value=<?php echo $row[3] ?>>
Ciudad: <input type='text' name='Ciudad' value=<?php echo $row[4] ?>>
Direccion: <input type='text' name='Direccion' value=<?php echo $row[5] ?>>
Descripcion: <input type='text' name='Descripcion' value=<?php echo $row[6] ?>>
Fotografia: <input type='text' name='Fotografia' value=<?php echo $row[1] ?>>
</pre>
<br><input type='submit' value='Ingresar'></br>
</form>
<?php
// Cerrando la conexión
pg_close($dbconn);
?>
</body>
</html>
You need to use quotes around your HTML element attributes. As it stand, the HTML generated from your code would look like this
<input type='text' name='Nombre' value=estadio nacional>
See the problem?
You should also use htmlspecialchars() to avoid any XSS vulnerabilities or general HTML incorrect-ness, eg
<input type="text" name="Nombre" value="<?= htmlspecialchars($nombre) ?>">
Also, why the <pre> tags?

Delete button to delete database table row

I want to give the users of my website the ability to add, edit and remove questions of a FAQ that's stored on a database. They select the title from a form and then they can press 'select' (to edit the q&a) or 'delete'. Deleting doesn't work.
The first problem is: when they click delete, it leads them to the 'edit' form instead of deleting the database table row.
The second problem: when I make them click the button, I ask to confirm the delete. Whether they press 'Ok' or 'Cancel' doesn't matter, they are always lead to the 'edit' form.
The code in the admin panel (index.php):
if(isset($_POST['actie']) && $_POST['actie'] != "")
{
$actie = $_POST['actie'];
if($actie == "csd_faq") { verwerk_csd_faq($DB); }
if($actie == "csd_faq_edit") { verwerk_edit_csd_faq($DB); }
}
if($GLOBALS['logged_in'] && isset($_GET['actie']) && $_GET['actie'] != "")
{
$actie = $_GET['actie'];
if($actie == "csd_faq") { toon_csd_faq($DB); }
if($actie == "csd_faq_edit") { edit_csd_faq($DB); }
}
The code for the functions:
//ADD FAQ
function toon_csd_faq($DB)
{?>
<h2>Een FAQ toevoegen:</h2>
Gebruik het formulier hieronder om een FAQ toe te voegen.
<br /><br />
<form action='index.php?actie=csd_faq' method='post'>
<input type='hidden' name='actie' value='csd_faq' />
<input type='hidden' name='naam' value='<? echo $GLOBALS['nickname']; ?>' />
Vraag (Q): <br />
<input type='text' name='q' size='80' /><br /><br />
Antwoord (A): <br />
<textarea name='a' cols='80' rows='10'></textarea><br /><br />
<input type='submit' value='Toevoegen' />
</form>
<?}
function verwerk_csd_faq($DB)
{
$naam = $_POST['naam'];
$q = clean($_POST['q']);
$a = clean($_POST['a']);
$DB->q("INSERT INTO `csd_faq` (`datum`, `naam`, `q`, `a`) VALUES (NOW(), '$naam', '$q', '$a')");
echo "<b class='roze'>FAQ succesvol toegevoegd!</b>"
."<br /><br />";
}
// EDIT FAQ
function edit_csd_faq($DB)
{
echo "<h2>Een FAQ bewerken:</h2>";
if(isset($_GET['faq_id'])) //bewerken
{
$faq_id = $_GET['faq_id'];
$faq = $DB->q1("SELECT * FROM `csd_faq` WHERE `faq_id` = '$faq_id'");
?>
Gebruik het formulier hieronder om de FAQ te bewerken
<br /><br />
<form action='index.php?actie=csd_faq_edit' method='post'>
<input type='hidden' name='actie' value='csd_faq_edit' />
<input type='hidden' name='faq_id' value='<? echo $faq_id; ?>' />
<input type='hidden' name='naam' value='<? echo $GLOBALS['nickname']; ?>' />
Vraag (Q): <br />
<input type='text' name='q' size='80' value='<? echo $faq[3]; ?>' /><br /><br />
Antwoord (A): <br />
<textarea name='a' cols='80' rows='10'><? echo $faq[4]; ?></textarea><br /><br />
<input type='submit' name='update' value='Update' />
</form>
<br />
« <a href='javascript:history.go(-1)'>Kies een andere FAQ</a>
<?}
else { //selectie box tonen ?>
Selecteer de te bewerken FAQ.
<br /><br />
<form action='index.php' method='get'>
<input type='hidden' name='actie' value='csd_faq_edit' />
Titel: <br />
<select name='faq_id' size='10' style='width:500px;'>
<?
$result = $DB->q("SELECT * FROM `csd_faq` ORDER BY `datum` DESC");
$lijst = "";
while($faq = $DB->fa($result))
{
$lijst .= "<option value='".$faq[0]."'>".$faq[3]."</option>";
}
echo $lijst;
?>
</select>
<br /><br />
<input type='submit' name='selecteer' value='Selecteer' />
<input type='submit' name='delete' value='Verwijder' onClick='confirm("Zeker dat je deze FAQ wilt verwijderen?")' />
</form>
<?}
}
function verwerk_edit_csd_faq($DB)
{
if(isset($_POST['update'])) {
$faq_id = $_POST['faq_id'];
$naam = $_POST['naam'];
$q = clean($_POST['q']);
$a = clean($_POST['a']);
$DB->q("UPDATE `csd_faq` SET `datum` = NOW(), `naam` = '$naam', `q` = '$q', `a` = '$a' WHERE `faq_id` = '$faq_id'");
echo "<b class='roze'>FAQ succesvol bewerkt!</b>"
."<br /><br />";
}
else if(isset($_GET['delete'])) {
$faq_id = $_GET['faq_id'];
$DB->q("DELETE FROM `csd_faq` WHERE `faq_id` = '$faq_id'");
echo "<b class='roze'>FAQ succesvol verwijderd!</b>"
."<br /><br />";
}
}
You probably want to check for $_POST['delete'] and $_POST['faq_id'], not $_GET['delete'] and $_GET['faq_id'] as the method of the form is POST.

Categories