I have a problem with PHP and, although I spent a whole hour trying to find what's wrong, I can't find anything in the code.
I'm working with a MySQL database and an input form. The form should be used to add entries to a specific table in the database. However, it gives a "Parse error: syntax error, unexpected '}'" whenever I hit the "Submit" button.
I tried everything but nothing worked.
This is the code:
<?php
include 'config.php';
session_start();
if (!isset($_SESSION['login'])){
header("Location: index.html");
}
if(isset($_POST['submit']) && ($_POST['submit']=="Invia")){
if(isset($_POST['section'])){
$section = addslashes(filter_var($_POST['section'], FILTER_SANITIZE_STRING));
} else {
echo "Devi selezionare una sezione";
}
if(isset($_POST['offer'])){
$offer = addslashes(filter_var($_POST['offer'], FILTER_SANITIZE_STRING));
}
if(isset($_POST['title'])){
$title = addslashes(filter_var($_POST['title'], FILTER_SANITIZE_STRING));
} else {
echo "Devi impostare il nome del viaggio";
}
if(isset($_POST['datestart'])){
$datestart = date('Ymd', strtotime($_POST['datestart']));
} else {
echo "Devi selezionare una data di inizio";
}
if(isset($_POST['dateend'])){
$dateend = date('Ymd', strtotime($_POST['dateend']));
} else {
echo "Devi selezionare una data di fine";
}
if(isset($_POST['itinerary'])){
$itinerary = addslashes(filter_var($_POST['itinerary'], FILTER_SANITIZE_STRING));
} else {
echo "Devi inserire un itinerario";
}
if(isset($_POST['price'])){
$price = addslashes(filter_var($_POST['price'], FILTER_SANITIZE_STRING));
} else {
echo "Devi inserire un prezzo";
}
if(isset($_POST['includes'])){
$includes = addslashes(filter_var($_POST['includes'], FILTER_SANITIZE_STRING));
} else {
echo "Devi inserire La quota comprende!";
}
if(isset($_POST['pdfname'])){
$pdfname = addslashes(filter_var($_POST['pdfname'], FILTER_SANITIZE_STRING));
} else {
echo "Devi inserire un nome per il pdf";
}
if(isset($_POST['section']) && isset($_POST['title']) && isset($_POST['datestart']) && isset($_POST['dateend']) && isset($_POST['itinerary']) && isset($_POST['price']) && isset($_POST['includes']) && isset($_POST['pdfname'])){
$data = new MysqlClass();
$data->connetti();
$query = "INSERT INTO " . $section . " (
`id` ,
`title` ,
`offer` ,
`datestart` ,
`dateend` ,
`itinerary` ,
`price` ,
`includes` ,
`pdfname`)
VALUES (
NULL,
'".$title."',
'".$offer."',
'".$datestart."',
'".$dateend."',
'".$itinerary."',
'".$price."',
'".$includes."',
'".$pdfname."');";
$data->query($query);
echo "Viaggio inserito con successo.";
$data->disconnetti();
}
} else {
header("Location: index.html");
}
?>
EDIT: I'm using Wamp as a local server. I'm starting to think that's the problem, although it seems unlikely.
EDIT 2: I tried switching to EasyPHP, but I still have the same problem: Parse error: syntax error, unexpected '}' in C:\Program Files (x86)\EasyPHP-DevServer-13.1VC11\data\localweb\input.php on line 50
if(isset($_POST['price'])){
else { //<<---- missing } before else
echo "Devi inserire un prezzo";
}
There is also an "extra" closing bracket at the end of the script
when you use if statement you should do like this
if(){
}else{
}
and as he told you above
if(isset($_POST['price'])){
else {
echo "Devi inserire un prezzo";
}
Thank You .
Related
I have an input in my code that update a value in MySQL, but is not working, if i set the value manually in PHPMyAdmin, the value display in HTML, but when i try update, return to 0.
I have the same code to do a similar function, and have copied, and it still isn't working.
Controller:
function ordemmobile(){
$ordemmobile = $this->input->post('ordemmobile');
$id = $this->input->post('id');
if($id > 0){
$data['ordemmobile'] = $ordemmobile;
$data['id'] = $id;
if( $this->categorias_model->alterar($data)){
$ret = "success";
$msg = "Ordem alterada com sucesso!";
}else{
$ret = "danger";
$msg = "Erro ao alterar a ordem :(";
}
}else{
$ret = "danger";
$msg = "Erro ao alterar a ordem :(";
}
echo json_encode(array('status' => $ret , 'msg' => $msg));
}
View:
echo "<td><input type=\"number\" name=\"ordemmobile\" value=\"".$registro->ordemmobile."\" style=\"width:80px; margin:0\" class=\"ordemmobile\" data-id=\"".$registro->id."\" data-url=\"".base_url('adm/'.$this->router->fetch_class().'/ordemmobile')."\" /><span style=\"display:none\">".$registro->ordemmobile."</span></td>";
Model (alterar):
function alterar($data){
$this->db->where('id',$data['id']);
return $this->db->update('ga845_categorias',$data);
}
Looks like it should work if the inputs are getting posted. Checking both inputs would be a good idea.
Consider this
function ordemmobile()
{
$ordemmobile = $this->input->post('ordemmobile');
$id = $this->input->post('id');
if(empty($id) || empty($ordemmobile))
{
$ret = "danger";
$msg = "Erro ao alterar a ordem :(";
}
else
{
$data['ordemmobile'] = $ordemmobile;
$data['id'] = $id;
if($this->categorias_model->alterar($data))
{
$ret = "success";
$msg = "Ordem alterada com sucesso!";
}
else
{
$ret = "danger";
$msg = "Erro ao alterar a ordem :(";
}
}
echo json_encode(array('status' => $ret, 'msg' => $msg));
}
You should also take a good look at what your browser's Web Developer Tools tell you about the request to and response from the server.
So I have to make contact form multilingual, but im stuck for 7 hours already.
SO i have to make ajax ok/error messages without duplicating code.
$language = $_GET["language"] OR $language == "en";
$language = $_GET["language"] OR $language == "es";
$language = $_GET["language"] OR $language == "pl";
if ($language == "en") {
$okMessage = 'Thank you, we will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';
}
if ($language == "pl") {
$okMessage = 'Dziękujemy, skontaktujemy się niedługo';
$errorMessage = 'W wiadomości pojawił się błąd, prosimy spróbować później';
}
if ($language == "es") {
$okMessage = 'Gracias, nos pondremos en contacto con usted pronto!';
$errorMessage = 'Hubo un error al enviar la solicitud. Por favor intente de nuevo.';
}
So what i want my code to do is that when im on poland contact form page. like www.website.com/pl-contact-page.php?language=pl - it gives me error/success messages in poland
After reading this thread I decided to give my little help, I changed a bit your code to get it more easy and secure... what that you need is Query String and Parse String... the rest is simple... I tested on my localtest and works fine...
<?php
#ini_set('default_charset', 'UTF-8');
$gurl = $_SERVER['QUERY_STRING'];
$ourl = array();
parse_str($gurl, $ourl);
if (isset($ourl['language']) || (!empty($ourl['language']))) {
$language = htmlspecialchars($ourl['language'], ENT_NOQUOTES, 'UTF-8');
if ($language == "en") {
$okMessage = 'Thank you, we will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';
} elseif ($language == "pl") {
$okMessage = 'Dziekujemy, skontaktujemy sie niedlugo';
$errorMessage = 'W wiadomosci pojawil sie blad, prosimy spróbowac pózniej';
} elseif ($language == "es") {
$okMessage = 'Gracias, nos pondremos en contacto con usted pronto!';
$errorMessage = 'Hubo un error al enviar la solicitud. Por favor intente de nuevo';
}
// echo $okMessage; #Debug purpose
// echo $errorMessage; #Debug purpose
} else {
echo ("No language available!");
}
?>
Version with my function get_messages() that detect the correct string code (UTF-8 or ANSI):
<?php
#ini_set('default_charset', 'UTF-8');
$gurl = $_SERVER['QUERY_STRING'];
$ourl = array();
parse_str($gurl, $ourl);
if (isset($ourl['language']) || (!empty($ourl['language']))) {
$language = htmlspecialchars($ourl['language'], ENT_NOQUOTES, 'UTF-8');
function get_messages($string) {
return mb_convert_encoding($string, 'UTF-8', mb_detect_encoding($string, 'UTF-8, ISO-8859-1', true));
}
if ($language == "en") {
$okMessage = get_messages('Thank you, we will get back to you soon!');
$errorMessage = get_messages('There was an error while submitting the form. Please try again later');
} elseif ($language == "pl") {
$okMessage = get_messages('Dziekujemy, skontaktujemy sie niedlugo');
$errorMessage = get_messages('W wiadomosci pojawil sie blad, prosimy spróbowac pózniej');
} elseif ($language == "es") {
$okMessage = get_messages('Gracias, nos pondremos en contacto con usted pronto!');
$errorMessage = get_messages('Hubo un error al enviar la solicitud. Por favor intente de nuevo');
}
// echo $okMessage; #Debug purpose
// echo $errorMessage; #Debug purpose
} else {
echo ("No language available!");
}
?>
http://localhost-test/contact-page.php?language=pl
http://localhost-test/contact-page.php?language=en
http://localhost-test/contact-page.php?language=es
http://localhost-test/contact-page.php
Notes: you have to echo somewhere your messages otherwise the code appears not working well...
I hope this helps.
When I submit the form of register new user or new client, this message error appears.
I'm using PHP 7.1.5 with IIS Server in a Windows 10 OS. The same code was working correctly and stop work from nothing.
Somebody can help me?
Here is the code:
enter code here
<?php
if (!isset($_SESSION)) {
session_start();
}
// Verifica se não há a variável da sessão que identifica o usuário
if (!isset($_SESSION['UsuarioID'])) {
// Destrói a sessão por segurança
session_destroy();
// Redireciona o visitante de volta pro login
header("Location: login.php"); exit;
}
if(isset($_POST['submit'])) {
$nome = $_POST['txt_nome'];
$email = $_POST['txt_email'];
$password = $_POST['txt_password'];
$cpassword = $_POST['txt_cpassword'];
$nivel = $_POST['txt_nivel'];
$pass=strcmp($password,$cpassword);
if($pass == 0){
$senha = md5($password);
}else{
echo 'As Senhas Não Conferem. Verifique!';
}
if ($nivel == '1 - Diretoria') {
$nivel = 1;
}else if ($nivel == '2 - Gerência'){
$nivel = 2;
}else if ($nivel == '3 - Usuários'){
$nivel = 3;
}
$cad_usur = "INSERT INTO C_USUR
(C_USUR_USUR,C_USUR_STUS,C_USUR_NOME,C_USUR_LGIN,C_USUR_PSWD,C_USUR_NIVL)
VALUES ((SELECT S_CONT_CONT FROM
SP_PROX_NRMO('0001','C_USUR')),'1','$nome','$email','$senha','$nivel')";
$insert_usur = ibase_query($cad_usur);
if($cad_usur == true){
echo 'Cadastro Realizado Com Sucesso';
}else{
echo 'Não foi possível cadastrar o usuário. Verifique!';
}
}
?>
I have the following code:
session_start();
$error_fname = $_SESSION['error_fname'];
$error_lname = $_SESSION['error_lname'];
$error_email = $_SESSION['error_email'];
$error_email_invalid = $_SESSION['error_email_invalid'];
$error = array(
'fname' => $error_fname,
'lname' => $error_lname,
'email' => $error_email,
'email_invalid' => $error_email_invalid);
This is on top of the page, and down at my contact form, the following code is placed:
<?php echo $error; ?>
For some reason, when I trigger an error, the page refreshes, and prints out the following:
How can I make it so one variable ($error) displays all of the possible errors?
The _SESSION variables are defined in the following file:
/assets/redir/contact.php
<?php
session_start();
$_SESSION['error_fname'] = " ";
$_SESSION['error_lname'] = " ";
$_SESSION['error_email'] = " ";
$_SESSION['error_email_invalid'] = " ";
if($_POST['fname']){
if($_POST['lname']){
if($_POST['email']){
if (strstr($_POST['email'], '#') && strstr($_POST['email'], '.')) {
mail('', 'Nieuw bericht van je website!', strip_tags($_POST['message']));
header('Location: ../../index.php');
}else
$_SESSION['error_email_invalid'] = "<div class='mssg mssg_error'>Het ingevoerde e-mail adres is niet correct.</div>";header('Location: ../../index.php');
}else
$_SESSION['error_email'] = "<div class='mssg mssg_error'>Je e-mail adres is verplicht</div>";header('Location: ../../index.php');
}else
$_SESSION['error_lname'] = "<div class='mssg mssg_error'>Je achternaam is verplicht</div>";header('Location: ../../index.php');
}else
$_SESSION['error_fname'] = "<div class='mssg mssg_error'>Je voornaam is verplicht</div>";header('Location: ../../index.php');
?>
When using var_dump($error); I get the following:
Thanks in advance!
$error is array so you need to iterate by this and display each element separately:
foreach ($error as $er) {
if (!empty($er)) {
echo $er;
break; //to leave for first error
}
}
The problem is that I can't update the database using this code. It seems that the UPDATE query don't recognize $id variable. I try to put it in the if cycle but still don't recognize it.
Here I put the code for update the database and to retrieve data from it to show in the form fields. The script is executed but it doesn't update the database.
<?php
session_start();
require_once("../config.php");
require_once("../database.php");
//inserisci dati in tabella utenti
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$id=isset($_GET['id']) ? intval($_GET['id']) : "";
if ($_SERVER["REQUEST_METHOD"] == "POST" ) {
$error_message = "";
//primo controllo campi inseriti con funzione test_input
if(isset($_POST['nome'])) {
$nome = test_input($_POST['nome']);
} else {
$error_message = "Devi inserire il tuo nome.<br/>";
}
if(isset($_POST['cognome'])) {
$cognome = test_input($_POST['cognome']);
} else {
$error_message = "Devi inserire il tuo cognome.</br>";
}
if(isset($_POST['paese'])) {
$paese = test_input($_POST['paese']);
} else {
$error_message = "Devi inserire il paese di residenza.</br>";
}
if(isset($_POST['provincia'])) {
$provincia = test_input($_POST['provincia']);
} else {
$error_message = "<p>Devi inserire la provincia di residenza.</br>";
}
if(isset($_POST['citta'])) {
$citta = test_input($_POST['citta']);
} else {
$error_message = "Devi inserire la città di residenza.</br>";
}
if(isset($_POST['telefono'])) {
$telefono = intval(test_input($_POST['telefono']));
} else {
$error_message = "Devi inserire un recapito telefonico.</br>";
}
if(isset($_POST['indirizzo'])) {
$indirizzo = test_input($_POST['indirizzo']);
} else {
$error_message = "Devi inserire il tuo indirizzo di residenza.</br>";
}
if(isset($_POST['cap'])) {
$cap = intval(test_input($_POST['cap']));
} else {
$error_message = "Devi inserire il tuo cap.</br>";
}
if(isset($_POST['cf'])) {
$cf = test_input($_POST['cf']);
} else {
$error_message = "Devi inserire il tuo codice fiscale.</br>";
}
//if(!isset($error_message)) {
$results1 = $db->prepare("UPDATE utenti SET
nome = :nome,
cognome = :cognome,
cf = :cf,
paese = :paese,
provincia = :provincia,
citta = :citta,
indirizzo = :indirizzo,
cap = :cap,
telefono = :telefono
WHERE id = " . $id);
$results1->bindParam(':nome',$nome);
$results1->bindParam(':cognome',$cognome);
$results1->bindParam(':cf',$cf);
$results1->bindParam(':paese',$paese);
$results1->bindParam(':provincia',$provincia);
$results1->bindParam(':citta',$citta);
$results1->bindParam(':indirizzo',$indirizzo);
$results1->bindParam(':cap',$cap);
$results1->bindParam(':telefono',$telefono);
$results1->bindParam(':id',$id);
if($results1->execute()) {
header("Location:aggiorna.php?aggiorna=ok");
exit;
} else {
$error_message = "Problema nell'inserimento nel database: ";
header("Location:aggiorna.php?");
}
//}
}
$results = $db->prepare("SELECT * FROM utenti WHERE id= ?");
$results->bindParam(1,$id);
$results->execute();
$dati = $results->fetch(PDO::FETCH_ASSOC);
Change from
WHERE id = " . $id);
To
WHERE id = :id ");