How to put if in an variable in HTML/PHP - php

I just starded with PHP and dont have a lot of knowledge. But i want to generate a Mail by pressing ona button. That works so far. But now i have for example the Row Anrede: ".$row["anrede"]."%0D%0A. This is a ENUM with Herr, Frau and Other. But i also got that in other languages (FR, IT) and i want to output Monsineur for Herr, Madamme for Frau and autres for Other.
I tried it with
"if ($row['anrede'] == 'Herr' ){
echo "Monsieur";
}
if ($row['anrede'] == 'Frau') {
echo "Madame";
}
if ($row['anrede'] == 'other') {
echo "autres";
}"
Here the full code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<?php
$host = "";
$username = "";
$password = "";
$dbname = "";
$port = "";
$socket = "";
// initiate new mysqli object
$mysqli = new mysqli($host, $username, $password, $dbname, $port, $socket);
if(mysqli_connect_errno())
{
printf("Verbindungsfehler: %s\n". mysqli_connect_error());
exit();
}
$queryString = "SELECT anrede, vorname, nachname, strasse , plz, ort , strasser, plzr, ortr, firma, funktion, email, sektion, anfahrt, uebernachtung, status, ksprache, usprache, aktiv FROM tab_teilnehmer WHERE aktiv = 1";
$queryResult = $mysqli->query($queryString);
while ($row = mysqli_fetch_assoc($queryResult)) {
echo "<tr>";
echo "<td><a href='mailto:" . $row["email"] . "?subject=Test&body=
------------------DE------------------
%0D%0AVielen Dank für Ihre Anmeldung Frau/Herr " . $row["nachname"] ."
%0D%0AHier Ihre Anmeldedaten:%0D%0A%0D%0A
Anrede:: ".$row["anrede"]."%0D%0A
Vorname: ".$row["vorname"]."%0D%0A
Nachname: ".$row["nachname"]."%0D%0A
Strasse: ".$row["strasse"]."%0D%0A
PLZ/Ort: ".$row["plz"].", ".$row["ort"]."%0D%0A
Strasse(Rechn.): ".$row["strasser"]."%0D%0A
PLZ/Ort(Rechn.): ".$row["plzr"].", ".$row["ortr"]."%0D%0A
Firma: ".$row["firma"]."%0D%0A
Funktion: ".$row["funktion"]."%0D%0A
E-Mail: ".$row["email"]."%0D%0A
Anfahrt: ".$row["anfahrt"]."%0D%0A
Übernachtungsart: ".$row["uebernachtung"]."%0D%0A
Sektion: ".$row["sektion"]."%0D%0A
Status: ".$row["status"]."%0D%0A
Korrespondenz-/Übersetzungssprache: ".$row["ksprache"].", ".$row["usprache"]."%0D%0A%0D%0A
------------------FR------------------
%0D%0AMerci beaucoup pour votre inscription madame/monsineur " . $row["nachname"] ."
%0D%0AVoici vos identifiants de connexion:%0D%0A%0D%0A
Anrede: ".$row["anrede"]."%0D%0A
Vorname: ".$row["vorname"]."%0D%0A
Nachname: ".$row["nachname"]."%0D%0A
Strasse: ".$row["strasse"]."%0D%0A
PLZ/Ort: ".$row["plz"].", ".$row["ort"]."%0D%0A
Strasse(Rechn.): ".$row["strasser"]."%0D%0A
PLZ/Ort(Rechn.): ".$row["plzr"].", ".$row["ortr"]."%0D%0A
Firma: ".$row["firma"]."%0D%0A
Funktion: ".$row["funktion"]."%0D%0A
E-Mail: ".$row["email"]."%0D%0A
Anfahrt: ".$row["anfahrt"]."%0D%0A
Übernachtungsart: ".$row["uebernachtung"]."%0D%0A
Sektion: ".$row["sektion"]."%0D%0A
Status: ".$row["status"]."%0D%0A
Korrespondenz-/Übersetzungssprache: ".$row["ksprache"].", ".$row["usprache"]."%0D%0A%0D%0A
------------------IT------------------
%0D%0AGrazie mille per la vostra registrazione signora/signore " . $row["nachname"] ."
%0D%0AEcco i tuoi dati di accesso:%0D%0A%0D%0A
Anrede: ".$row["anrede"]."%0D%0A
Vorname: ".$row["vorname"]."%0D%0A
Nachname: ".$row["nachname"]."%0D%0A
Strasse: ".$row["strasse"]."%0D%0A
PLZ/Ort: ".$row["plz"].", ".$row["ort"]."%0D%0A
Strasse(Rechn.): ".$row["strasser"]."%0D%0A
PLZ/Ort(Rechn.): ".$row["plzr"].", ".$row["ortr"]."%0D%0A
Firma: ".$row["firma"]."%0D%0A
Funktion: ".$row["funktion"]."%0D%0A
E-Mail: ".$row["email"]."%0D%0A
Anfahrt: ".$row["anfahrt"]."%0D%0A
Übernachtungsart: ".$row["uebernachtung"]."%0D%0A
Sektion: ".$row["sektion"]."%0D%0A
Status: ".$row["status"]."%0D%0A
Korrespondenz-/Übersetzungssprache: ".$row["ksprache"].", ".$row["usprache"]."
'>Mail</a></td>";
echo "</tr>";
}
?>
</body>
</html>

Maybe something like this
Add this inside looping (your while)
if ($row['anrede'] == 'Herr' ){
$temp = "Monsieur";
}
if ($row['anrede'] == 'Frau') {
$temp = "Madame";
}
if ($row['anrede'] == 'other') {
$temp = "autres";
}
You need set the value into the variables, based on anrede value.
if anrede value is Frau, set $temp value with Madame. And call $temp where you want.

You have to stop the printing, then add the if condition, then continue printing. Or you could consider a ternary, but I would stick with the way your thinking for better readability.
Like so:
echo "<td><a href='mailto:" . $row["email"] . "?subject=Test&body=
------------------DE------------------
%0D%0AVielen Dank für Ihre Anmeldung Frau/Herr " . $row["nachname"] ."
%0D%0AHier Ihre Anmeldedaten:%0D%0A%0D%0A
Anrede:: ";
if ($row['anrede'] == 'Herr' ){
echo "Monsieur";
} else if ($row['anrede'] == 'Frau') {
echo "Madame";
} else if ($row['anrede'] == 'other') {
echo "autres";
}
echo "%0D%0A
Vorname: ".$row["vorname"]."%0D%0A
......";
// continue echo

I would propose this switch snippet, it protects against notice, when $row['anrede'] would not be set and also with echo-ing instead of using $temp variable.
$anrede = isset($row['anrede']) ? $row['anrede'] : null;
switch($anrede) {
case 'Herr':
echo 'Monsieur';
break;
case 'Frau':
echo 'Madame';
break;
default:
echo 'autres';
}

Related

Some troubles with date visualization

I have some troubles with visualization of the date in a query with php. Here is the code:
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$dbname = "alternanza";
// connessione al server sql
$conn = mysqli_connect($hostname, $username, $password, $dbname);
if (!$conn) {
die("errore nella connessione");
} else {
echo "connessione avvenuta correttamente <Br/>";
}
// recupero dati passati dal form
$nome = $_POST["nome"];
$cognome = $_POST["cognome"];
$dal = $_POST["dal"];
$al = $_POST["al"];
$query = "select NomeS, CognomeS, Specializzazione, Denominazione
from studente, azienda, attivitàformativa
where CodFiscaleS=KCodFiscaleS and CodAzienda=KodAzienda and Data_inizio='$dal'
and Data_fine='$al' and CognomeS='$cognome' and NomeS='$nome'";
$risultato = mysqli_query($conn, $query);
if (!$risultato) {
echo " errore di comando <br/>";
exit();
}
while ($riga = mysqli_fetch_array($risultato))
if ($riga) {
echo "nome: " . $riga['NomeS'] . " <br/>";
echo "cognome: " . $riga['CognomeS'] . " <br/>";
echo "periodo stage dal: " . $riga['Data_inizio'] . " <br/>";
echo "al: " . $riga['Data_fine'] . " <br/>";
echo "presso azienda: " . $riga['Denominazione'] . " <br/>";
echo "con specializzazione: " . $riga['Specializzazione'] . " <br/>";
}
mysqli_close($conn);
echo " connessione chiusa";
?>
The errors I viewed are:
Notice: Undefined index: Data_inizio(date) in
C:\xampp\htdocs\scuola18\attestato.php on line 38 periodo stage dal:
Notice: Undefined index: Data_fine in
C:\xampp\htdocs\scuola18\attestato.php on line 39 al:
Do you know something about?
You have missed Data_fine and Data_inizio in your select query. Your select query should look like this
select NomeS, Data_fine, Data_inizio, CognomeS, Specializzazione, Denominazione
from studente, azienda, attivitàformativa
where CodFiscaleS=KCodFiscaleS and CodAzienda=KodAzienda and Data_inizio='$dal'
and Data_fine='$al' and CognomeS='$cognome' and NomeS='$nome'
However, I suggest you to use parepared statements to prevent from sql injections

PHP code does not start when the page is loaded

I made the code below to show the files that were inserted by the user, however it only shows the files after having attached a file, however I wanted it to show when loading the page, for the user to see what files he has already uploaded. Here is the code I used to upload the file:
<center><p class="text-success" style="font-size: 20px; padding-bottom: 100px;">
<?php
session_start();
require_once('conecta.php');
$email = $_SESSION['email'];
if (isset($_POST['enviar'])) {
$arq = $_FILES['arquivo']['name'];
$dataup = date('Y-m-d H:i:s');
echo $dataup;
$arq = str_replace(" ", "_", $arq);
$arq = str_replace("ç", "c", $arq);
if (file_exists("uploads/".$arq)) {
$a = 1;
while (file_exists("uploads/[".$a."]".$arq)) {
$a++;
}
$arq = "[".$a."]".$arq;
}
if (move_uploaded_file($_FILES['arquivo']['tmp_name'], 'uploads/'.$arq)) {
$objDb = new db();
$link = $objDb->conecta_mysql();
$sql = "insert into arquivos (email_vol, nomearq) values ('". $email."', '".$arq."')";
if (mysqli_query($link, $sql)){
echo 'Plano de aula 1 enviado com sucesso!';
} else {
echo (mysqli_error($link));
echo 'Erro ao enviar o plano de aula!';
}
} else {
echo "Nenhum arquivo selecionado!";
}
}
?>
</p></center>
Here is the code to show the file on the page:
<?php
session_start();
require_once('conecta.php');
$pasta = "uploads/";
$consulta = mysqli_query($link, "SELECT * FROM arquivos WHERE email_vol = '$email'");
while ($resultado = mysqli_fetch_array($consulta)) {
echo "" . $resultado["nomearq"] . "<br />";
}
?>
Can someone give me a hand? Thank you very much in advance.

How can I limit the backup files of my database I created via cronjob?

I am using a script, to backup my database into an ftp-folder. My problem is, that I am executing the script every day via cronjob and I am afraid that too many backups are created. So I want to keep always only three backups.
db_backup.phpx:
<?php
######## einstellungen #############################################
$db_name = "IhreDatenBank";
$db_passwd = "IhrDatenBankPasswort";
$downloadlink_erstellen = "ja";
$bestaetigungsmail_senden = "ja";
$bestaetigungsmail_adresse = "IhreMailAdresse";
$bestaetigungsmail_betreff = "[BACKUP] Ihr Backupscript";
$sql_file = "dump_" . $db_name . "_" . date('Ymd_Hi') . ".sql";
####################################################################
### daten überprüfen
if ( $db_name == "IhreDatenBank" or $db_passwd == "IhrDatenBankPasswort" )
{
die("FEHLER: Sie müssen zunächst Ihre Datenbankdaten im Script eingeben!");
}
if ( file_exists($sql_file) or file_exists($sql_file . ".gz") )
{
die("FEHLER: Das zu erstellende Dump existiert bereits!");
}
## dump erstellen
exec("mysqldump -u $db_name -p'$db_passwd' --quick --allow-keywords --add-drop-table --complete-insert --quote-names $db_name >$sql_file");
exec("gzip $sql_file");
### größe ermitteln
$datei = $sql_file . ".gz";
$size = filesize($datei);
$i = 0;
while ( $size > 1024 )
{
$i++;
$size = $size / 1024;
}
$fileSizeNames = array(" Bytes", " KiloBytes", " MegaBytes", " GigaBytes", " TerraBytes");
$size = round($size,2);
$size = str_replace(".", ",", $size);
$groesse = "$size $fileSizeNames[$i]";
### nachricht erstellen
$message = "Ihr Backup der Datenbank <b>" . $db_name . "</b> wurde durchgeführt.<br>";
$message .= "Die Größe des erstellten Dumps beträgt <b>" . $groesse . "</b>.<br>";
if ($downloadlink_erstellen == "yes" or $downloadlink_erstellen == "ja" or $downloadlink_erstellen == "1")
{
$link = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
$link = str_replace(basename(__FILE__),$datei,$link);
$message .= "Downloadlink: " . $datei . "";
}
## nachricht ausgeben
echo $message;
### mail versenden
if ($bestaetigungsmail_senden == "yes" or $bestaetigungsmail_senden == "ja" or $bestaetigungsmail_senden == "1")
{
if(!preg_match( '/^([a-zA-Z0-9])+([.a-zA-Z0-9_-])*#([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-]+)+/' , $bestaetigungsmail_adresse))
{
echo "<br>FEHLER: Mail konnte nicht versendet werden, da die Adresse ungültig ist!";
}
else
{
mail($bestaetigungsmail_adresse, $bestaetigungsmail_betreff,
$message,"From: backupscript#{$_SERVER['SERVER_NAME']}\r\n" . "Reply-To: backupscript#{$_SERVER['SERVER_NAME']}\r\n" . "Content-Type: text/html\r\n")
or die("FEHLER: Mail konnte wegen eines unbekannten Fehlers nicht versendet werden");
echo "<br>Bestätigungsmail wurde erfolgreich versandt!";
}
}
?>
I found a solution:
I change this line..
$sql_file = "dump_" . $db_name . "_" . date('Ymd_Hi') . ".sql";
..into this line:
$sql_file = "dump_" . $db_name . "_" . date('D') . ".sql";
So I keep only seven backups. Because after one week the old one is overwritten.

MySQL/PHP - Checkbox array to delete multiple rows from database

i'm having some trouble passing Form checkbox array as mysql_query in order to delete multiple rows from table.
The structure is as follows:
HTML
<form action="usunogrod.php" method="POST" enctype="multipart/form-data">
<?php
$ogrodysql = "SELECT id_ogrodu, nazwa FROM ogrody";
$result = mysqli_query($con, $ogrodysql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "• " . $row["id_ogrodu"]. " " . $row["nazwa"]. "<input type='checkbox' name='removegarden[]' value=" .$row["id_ogrodu"]." <br><br>";
}
}
else {
echo "0 results";
}
?>
<br><br>
<input type="submit" value="Usuń zaznaczony ogród."/>
</form>
PHP for processing form in usunogrod.php
<?php
$db_host = 'xxxxx';
$db_user = 'xxxxx';
$db_pwd = 'xxxxx';
$con = mysqli_connect($db_host, $db_user, $db_pwd);
$database = 'xxxxx';
if (!mysqli_connect($db_host, $db_user, $db_pwd))
die("Brak połączenia z bazą danych.");
if (!mysqli_select_db($con, $database))
die("Nie można wybrać bazy danych.");
function sql_safe($s)
{
if (get_magic_quotes_gpc())
$s = stripslashes($s);
global $con;
return mysqli_real_escape_string($con, $s);
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$ogrod_id = trim(sql_safe($_POST['removegarden[]']));
if (isset($_POST['removegarden[]'])) {
mysqli_query($con, "DELETE FROM ogrody WHERE id_ogrodu='$ogrod_id'");
$msg = 'Ogród został usunięty.';
}
elseif (isset($_GET['removegarden[]']))
$msg = 'Nie udało się usunąć ogrodu.';
};
?>
MySQL table
ogrody
# id_ogrodu nazwa
1 garden1
How may i process an array from checkboxes form so that i will be able to pass a query to delete all checked elements?
EDIT:
I have been able to make it work to a moment where it only deleted one of the checked positions, or the other time just got an error saying i can't pass and array to mysqli_query.
I think this should help you:
Change this line:
echo "• " . $row["id_ogrodu"]. " " . $row["nazwa"]. "<input type='checkbox' name='removegarden[]' value=" .$row["id_ogrodu"]." <br><br>";
For this one:
echo '• ' . $row["id_ogrodu"]. ' ' . $row["nazwa"]. '<input type="checkbox" name="removegarden['.$row["id_ogrodu"].']" value="'.$row["id_ogrodu"].'" /> <br/><br/>';
Then this one:
if (isset($_POST['removegarden[]'])) {
To
if (isset($_POST['removegarden'])) {
And finally your query:
$gardens = implode(',',$_POST['removegarden']);
mysqli_query($con, "DELETE FROM ogrody WHERE id_ogrodu IN($gardens)");
You can get your data in $_POST['removegarden']. no need [] at last.
Then convert this array to ',' seperated string which can be then used in query
if (isset($_POST['removegarden'])) {
$ids_to_delete = implode(",",$_POST['removegarden']);
mysqli_query($con, "DELETE FROM ogrody WHERE id_ogrodu IN ($ids_to_delete)");
$msg = 'Ogród został usunięty.';
}

combobox php mysql delete value

require 'open.php';
$query4 = "SELECT * FROM posto_emissao,cliente, conta WHERE idCliente = '".$_SESSION['usuarioClienteID']."' AND
conta.Cliente_idCliente = cliente.idCliente AND cliente.idCliente =
posto_emissao.Cliente_idCliente";
$resultado = #mysql_query($query4,$dbConnect);
$resultado2 = #mysql_query($query4,$dbConnect);
This conn things are working fine! My problem comes here:
I want to select a ID from a populated combobox and delete them from DB
Here's my form: (part of it)
echo '<form name ="apagar" method="post" action="apagape.php" id="peform">';
echo '<fieldset>';
echo' <li class="category">';
echo '<label>Posto de emissão:</label>';
echo '<select name="eliminar_PE">';
echo '<option value="0" selected="selected">Seleccione um posto</option>';
if ($resultado2 === FALSE)
echo "<p>Não foi possivel resolver a query.</p>" . "<p> Erro: " . mysql_errno($dbConnect) . ": " . mysql_error($dbConnect) . "</p>";
else
{
while($row2 = mysql_fetch_array($resultado2))
{
echo'<option value="'.$row2['idPosto_Emissao'].'">'.$row2['idPosto_Emissao'].'</option>';
}
echo''; echo ''; echo '';
echo '';
echo ''; echo '';
echo ''; mysql_close($dbConnect);
Here's my apagape.php: (part of it)
require 'open.php'; $query5 = "DELETE FROM posto_emissao WHERE
idPosto_Emissao = '".$_POST['IdPosto_Emissao']."'";
$result5=#mysql_query($query5,$dbConnect); if ($result5 ===
FALSE) { echo "Não foi possivel resolver a query." . "
Erro: " . mysql_errno($dbConnect) . ": " . mysql_error($dbConnect) .
""; } else { header("Location: index.php"); }
mysql_close($dbConnect);
PROBLEM: Nothing happens, delete fails :|
What i need to do?
Create a delete variable. I delete database entries like this by creating a dynamic url
click
I would then pull down an array on my delete.php page and have it look for that url variable, and match the record and delete it. returning back to the original page.

Categories