What I'm trying to do is to echo something at the top of the page while it catches something ad the bottom.
This is my script:
<html>
<head>
<title>Westpop</title>
<link rel="stylesheet" href="opmaak.css">
</head>
<body>
<div id="header"></div>
<?php
$host = "localhost";
$gebruikersnaam = "root";
$wachtwoord = "";
mysql_connect($host, $gebruikersnaam, $wachtwoord);
$demooistedatabase = "c5g4westpopintranet";
mysql_select_db($demooistedatabase);
$achternaam = $_POST["achternaam"];
$voornaam = $_POST["voornaam"];
$gbdatum = $_POST["geboortedatum"];
$email = $_POST["email"];
$geslacht = $_POST["geslacht"];
$wachtwoord = $_POST["wachtwoord"];
$woonplaats = $_POST["woonplaats"];
$adres = $_POST["adres"];
$telefoonnummer = $_POST["telefoonnummer"];
$functie = $_POST["functie"];
$achternaam = stripslashes($achternaam);
$voornaam = stripslashes($voornaam);
$gbdatum = stripslashes($gbdatum);
$email = stripslashes($email);
$geslacht = stripslashes($geslacht);
$wachtwoord = stripslashes($wachtwoord);
$woonplaats = stripslashes($woonplaats);
$adres = stripslashes($adres);
$telefoonnummer = stripslashes($telefoonnummer);
$functie = stripslashes($functie);
$query ="INSERT INTO vrijwilliger (voornaam, achternaam, gbdatum, geslacht, wachtwoord, woonplaats, adres, telefoonnummer, functie, activiteitID, groepID, email)
VALUES('$voornaam','$achternaam','$gbdatum','$geslacht','$wachtwoord','$woonplaats','$adres','$telefoonnummer','$functie',null,null,'$email')";
?>
<div id="registreer">
<center>
<br><br>
<?php
$foutloos=true;
if(preg_match("/^.*(?=.{8,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/", $wachtwoord) === 0)
{
echo '<fblack>Wachtwoord moet minstens 8 tekens lang zijn, een kleine letter, grote letter én cijfer bevatten.<br><fblack>';
$foutloos = false;
}
if(preg_match("/^[0-9]{10}+$/", $telefoonnummer) === 0)
{
echo '<fblack>Het telefoonnummer moet 10 cijfers bevatten.<br><fblack>';
$foutloos = false;
}
if(preg_match("/^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}$/", $gbdatum) === 0)
{
echo '<fblack>Geboorte datum moet op dit formaat ingevoerd worden: JJJJ-MM-DD<br><fblack>';
$foutloos = false;
}
if(preg_match("/^[a-z0-9]+([_\\.-][a-z0-9]+)*#([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i", $email) === 0)
{
echo '<fblack>Email moet hier op lijken: email#provider.com<br><fblack>';
$foutloos = false;
}
if(preg_match("/^[A-Z][a-zA-Z -]+$/", $voornaam) === 0)
{
echo '<fblack>Voornaam is niet geldig ingevoerd, heeft u een hoofdletter gebruikt?<br><fblack>';
$foutloos = false;
}
if(preg_match("/^[A-Z][a-zA-Z -]+$/", $achternaam) === 0)
{
echo '<fblack>Achternaam is niet geldig ingevoerd, heeft u een hoofdletter gebruikt?<br><fblack>';
$foutloos = false;
}
if ($geslacht == '')
{
echo '<fblack>U heeft uw geslacht niet aangegeven.<br><fblack>';
$foutloos = false;
}
if(preg_match("/^[a-zA-Z]+\ +[0-9]+$/", $adres) === 0)
{
echo '<fblack>Het adres is verkeerd ingevoerd.<br><fblack>';
$foutloos = false;
}
if(preg_match("/^[a-zA-Z\s]+$/", $woonplaats) === 0)
{
echo '<fblack>De woonplaats is verkeerd ingevoerd.<br><fblack>';
$foutloos = false;
}
if ($foutloos == true)
{
mysql_query($query)
or die('<fblack>U staat al in ons systeem<br><br>Klik hier om terug te gaan<fblack>');
echo "<fblack>Uw registratie is succesvol verwerkt!<br>Log <a href='login.php' MEDIA=screen>hier</a> in<fblack>";
}
else
{
echo '<fblack><br>Klik hier om terug te gaan<fblack>';
}
?>
</center>
</div>
<?php
include ("html_end.php");
?>
Now on top of the page I want to show an error message.
So how do I echo something on the top, while it catches it in the IF?
if ($foutloos == true)
{
mysql_query($query)
or die('<fblack>U staat al in ons systeem<br><br>Klik hier om terug te gaan<fblack>');
echo "<fblack>Uw registratie is succesvol verwerkt!<br>Log <a href='login.php' MEDIA=screen>hier</a> in<fblack>";
}
else
{
ECHO SOMETHING THAT HAS TO GO ABOVE THE PAGE
echo '<fblack><br>Klik hier om terug te gaan<fblack>';
}
Thanks in advance!
You want to seperate your logic from your view. So put your PHP on top, then the HTML at the bottom, for example:
//This goes at the top, only PHP here!
$host = "localhost";
$gebruikersnaam = "root";
$wachtwoord = "";
mysql_connect($host, $gebruikersnaam, $wachtwoord);
//etc
$query ="INSERT INTO vrijwilliger (voornaam, achternaam, gbdatum, geslacht, wachtwoord, woonplaats, adres, telefoonnummer, functie, activiteitID, groepID, email) VALUES('$voornaam','$achternaam','$gbdatum','$geslacht','$wachtwoord','$woonplaats','$adres','$telefoonnummer','$functie',null,null,'$email')";
$foutmelding = false; //Start without error obviously, we check later if this value has been changed at all.
if(preg_match("/^[0-9]{10}+$/", $telefoonnummer) === 0) //Something is not right
{
$foutmelding = "Je telefoon nummer klopt niet!"; //By setting this to a string it will evaluate to `true` later on, thus showing the error message.
}
//More error checking etc...
Then all the way down in your view, e.g. HTML;
<?php if($foutmelding) { ?>
Er is een fout opgetreden; <?php echo $foutmelding; ?>
<?php } else { ?>
Alles is goed gegaan, dankjewel!
<?php } ?>
Use the PHP buffers. Don't send the content of the buffer until you reach the end of the php file.
http://php.net/manual/en/book.outcontrol.php
<?php
// Open buffer #1
ob_start();
print "Line 1\n";
// Open buffer #2
ob_start();
print "Line 2\n";
// Grab the contents of buffer #2
$buf2 = ob_get_contents();
// Close buffer #2
ob_end_clean();
print "Line 3\n";
// Grab the contents of buffer #1
$buf1 = ob_get_contents();
// Close buffer #1
ob_end_clean();
// Output the buffer contents
print $buf1;
print $buf2;
?>
You have at least 2 ways of doing this:
server side - start using some template engines like smarty and separate your presentation layer from the business layer as F. Calderan suggested
client side - add some javascript code to the HTML generated by your php script. Make this execute at the end of the page and modify the DOM of the HTML.
if you don't want to rewrite your project to mvc, here is just a quick solution..: use ob_start
Related
I'm trying to make a poll where the user is voting through a PHP page sending data to a database where I store the values of the poll results.
I'm also trying to make it not possible to vote with the same account more than once. In this area, I've hit a roadblock. When I take the ID which in the code is $userid which is collected from a query and then passed to the vote.php in a $_SESSION it says that
Truncated incorrect DOUBLE value: 3.
It's calling my variable DOUBLE value?
Code of Login.php :
$sqlID = "SELECT ID FROM Users WHERE Konto = '$user'";
$checkID = $connection->query($sqlID);
while ($row = $checkID->fetch_assoc()) {
$setID = $row['ID']."<br>";
}
$_SESSION['sess_id'] = $setID;
$_SESSION['inloggning'] = TRUE; // Ger inloggning en boolean som används senare.
Code of Vote.php :
$userid = $_SESSION['sess_id'];
$voteValidate = "SELECT has_voted FROM Users WHERE ID = '$userid'";
$voteValidationResult = $connection->query($voteValidate);
while ($row = $voteValidationResult->fetch_assoc()) {
$checkVoted = $row['has_voted']."<br>";
}
if ($_SESSION['inloggning'] != TRUE || $checkVoted != 0) { // Tar variabler från login.php och kontrollerar dem, om de inte är sanna så skickas man tillbaka.
echo "<script type='text/javascript'>alert('Du är antingen inte inloggad eller så har du redan röstat.');</script>";
// header("Location: skyddad_sida.php"); // Skickar tillbaka en användare om de har kommit till skyddad_sida.php utan att gå igenom login.php.
exit;
}
if (isset($_POST["voteOriginal"])) {
$voteQuery = "UPDATE polls_choices SET poll_vote_amount = poll_vote_amount + 1 WHERE poll_choice_name = 'Original'";
$voteExecute = $connection->query($voteQuery); // Utför förfrågan i databas.
$preventVote = "UPDATE users SET has_voted = 1 WHERE ID = '$userid'";
if ($connection->query($preventVote) === TRUE) { // Queryar databasen och kontrollerar att det fungerade.
echo "<strong><font color ='green'>Bra.</font></strong>";
} else { // Annars blir det en error.
echo "Error: " . $preventVote . "<br>" . $connection->error . "$userid";
}
I have created a filtering system, which can create the desired SQL code, when a button is clicked. Only problem is the array I used for the checkbox SQL code continues the OR statement, but I don't want the empty variables to be used in my array.
Here is the code (Some text is Dutch, but it's about skin, hair and eye colour):
if(isset($_POST["Filter"]))
{
$OogC = count($_POST['ogen']);
$HuidC = count($_POST['huidskleur']);
$HaarC = count($_POST['haarkleur']);
$StatusC = count($_POST['status']);
//Als checkbox is aangevinkt gaat dit verder
if(!empty($_POST['ogen'])) {
//Als er meer dan 1 checkbox is ingevuld dan wordt diit stukje SQL gebruikt
if($OogC > 1){
$Oog = implode("' OR `Kleur_ogen`='", $_POST['ogen']);
$OogSQL = "`Kleur_ogen`='".$Oog."'";
}
//En anders dit
else{
foreach($_POST['ogen'] as $Oog1)
$OogSQL1 = "`Kleur_ogen`='".$Oog1."'";
}}
else{
$OogSQL="";
$OogSQL1 ="";
}
echo"<br>";
//Als checkbox is aangevinkt gaat dit verder
if(!empty($_POST['huidskleur'])) {
//Als er meer dan 1 checkbox is ingevuld dan wordt diit stukje SQL gebruikt
if($HuidC > 1){
$Huid = implode("' OR `Huidskleur`='", $_POST['huidskleur']);
$HuidSQL = "`Huidskleur`='".$Huid."'";
}
//En anders dit
else{
foreach($_POST['huidskleur'] as $Huid1)
$HuidSQL1 = "`Huidskleur`='".$Huid1."'";
}}
else{
$HuidSQL ="";
$HuidSQL1 ="";
}
echo"<br>";
//Als checkbox is aangevinkt gaat dit verder
if(!empty($_POST['haarkleur'])) {
//Als er meer dan 1 checkbox is ingevuld dan wordt diit stukje SQL gebruikt
if($HaarC > 1){
$Haar = implode("' OR `Kleur_haar`='", $_POST['haarkleur']);
$HaarSQL = "`Kleur_haar`='".$Haar."'";
}
//En anders dit
else{
foreach($_POST['haarkleur'] as $Haar1)
$HaarSQL1 = "`Haarkleur`='".$Haar1."'";
}}
else{
$HaarSQL ="";
$HaarSQL1 ="";
}
echo"<br>";
//Als checkbox is aangevinkt gaat dit verder
if(!empty($_POST['status'])) {
//Als er meer dan 1 checkbox is ingevuld dan wordt diit stukje SQL gebruikt
if($StatusC > 1){
$Status = implode("' OR `Status`='", $_POST['status']);
$StatusSQL = "`Status`='".$Status."'";
}
//En anders dit
else{
foreach($_POST['status'] as $Status1)
$StatusSQL1 = "`Status`='".$Status1."'";
}}
else{
$StatusSQL ="";
$StatusSQL1 ="";
}
$Array = array($OogSQL,$OogSQL1,$HuidSQL,$HuidSQL1,$HaarSQL,$HaarSQL1,$StatusSQL,$StatusSQL1); $Array = array_diff($Array, [""]);
$SQL = implode($Array,"OR"); $Filtered = mysqli_query($mysql,"SELECT * FROM Producten WHERE '$SQL'");
echo $SQL; //Is to check how the array is printed out
echo mysqli_fetch_assoc($Filtered);
}
Now I wonder how I can get an array to only use the variables which have a line of SQL code, but my knowledge of arrays is limited. If anything is unclear I'd like to edit it for you.
By adding $Array = array_diff($Array, [""]); under the Array($Array) it filters out nulled variables and then does not continue to generate any more AND's.
This solution has been verified
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 an webpage on which i want to display 2 separate tables with content from the same database. How do i run separate functions on a webpage and display 2 different results?
The code i have so far:
the second query that i want to run is in it as query2, but this doesn`t work....
<?php
$server = "localhost";
$user = "776";
$wachtwoord = "776";
$database = "kse001_h5mh";
$query = "SELECT beschrijving FROM supermarkt WHERE soort = 'komkommertest'"; //de SQL-query
$resultaat = ""; // hierin wordt het resultaat van de query opgeslagen
if (!$db = mysql_connect($server, $user, $wachtwoord)){ // probeert de verbinding te maken
$melding = "<h2>Verbinding maken met databaseserver is mislukt!</h2>";
}
else{
$melding = "<h2>Verbinding maken met databaseserver is tot stand gebracht!</h2>";
if(!mysql_select_db($database)){ // open de gewenste database
$melding .= "...maar de database \"$database\" kon niet worden gevonden!";
} else {
$melding .= "en de database \"$database\" is geselecteerd!";
if(!$resultaat = mysql_query($query, $db)){
$melding .= "<br />...maar de query \"$query\" kon niet worden uitgevoerd!";
} else {
$melding .="<br />De query \"$query\" is met succes uitgevoerd!";
}
}
$query2 = "SELECT beschrijving FROM supermarkt WHERE soort = 'hamburger'"; //de SQL-query
$resultaat2 = ""; // hierin wordt het resultaat van de query opgeslagen
if (!$db = mysql_connect($server, $user, $wachtwoord)){ // probeert de verbinding te maken
$melding = "<h2>Verbinding maken met databaseserver is mislukt!</h2>";
} else {
$melding = "<h2>Verbinding maken met databaseserver is tot stand gebracht!</h2>";
if(!mysql_select_db($database)){ // open de gewenste database
$melding .= "...maar de database \"$database\" kon niet worden gevonden!";
} else {
$melding .= "en de database \"$database\" is geselecteerd!";
if(!$resultaat2 = mysql_query($query, $db)){
$melding .= "<br />...maar de query \"$query\" kon niet worden uitgevoerd!";
} else {
$melding .="<br />De query \"$query\" is met succes uitgevoerd!";
}
}
mysql_close($db); //database afsluiten
?>
</head>
<body>
<?php echo $melding; ?>
<hr />
<?php
while(list($bescrijving) = mysql_fetch_row($resultaat))
{
echo "$bescrijving is geboren op <br />";
}
?>
<?php
while(list($bescrijving) = mysql_fetch_row($resultaat2))
{
echo "$bescrijving is geboren op <br />";
}
?>
</body>
First problem, stop using mysql_ functions family... this kind of function was deprecated and will stop work soon or just don't run appropriately.
You should change to PDO family functions try this:
$dbh = new PDO('mysql:host=localhost;dbname=kse001_h5mh', '776', '776');
$query1 = $dbh->query("SELECT beschrijving FROM supermarkt WHERE soort = 'komkommertest'");
$query1->fetchAll(); // bring the result
$query2 = $dbh->query("SELECT beschrijving FROM supermarkt WHERE soort = 'hamburger'");
$query2->fetchAll(); // bring the result
This should work.
You can run 2 process of your script using the pcntl-fork function.
You can also try to use ob_flush function to send the output buffer between your 2 database requests.
In your case, I think it's a better option to load data in AJAX if it's possible.
I'm building an admin panel in PHP. I'm new to PHP and I can't get my edit page to work as I need it to. I can edit the name, but 2 values which represent "Active User" and "Access Level" are set to 0 and I can't change it from 0 on my edit page, only from PhpmyAdmin..
<?php
// Inserir o registo na BD
include_once ('config1.php');
// Estabelecer a ligação à BD
$connection = new mysqli('localhost', 'root', '123456', 'admin1');
//Verificar se a ligação foi estabelecida com sucesso
if (mysqli_connect_errno() ) {
echo "</h2>Erro no acesso a BD</h2>" . mysqli_connect_error();
exit();
}
// Validar se os campos do formulário foram preenchidos pelo utilizador
// Verificar se "username" foi enviado
if (isset($_POST['iusername']) == FALSE) {
echo ("Erro de submissão");
exit();
} else {
$username = trim($_POST['iusername']);
}
if (isset($_POST['inome']) == FALSE) {
echo ("Erro de submissão");
exit();
} else {
$nome = trim($_POST['inome']);
}
if (isset($_POST['inivel']) == FALSE) {
echo ("Erro de submissão");
exit();
} else {
$apelido = trim($_POST['inivel']);
}
if (isset($_POST['iativo']) == FALSE) {
echo ("Erro de submissão");
exit();
} else {
$telefone = trim($_POST['iativo']);
}
if (isset($_POST['iemail']) == FALSE) {
echo ("Erro de submissão");
exit();
} else {
$email = trim($_POST['iemail']);
}
if (isset($_POST['ipass']) == FALSE) {
echo ("Erro de submissão");
exit();
} else {
$pass = trim($_POST['ipass']);
}
if (isset($_POST['irpass']) == FALSE) {
echo ("Erro de submissão");
exit();
} else {
$repass = trim($_POST['irpass']);
}
// Função de validação do email (chamada mais abaixo no código)
function isValidEmail($email){
return #eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z] {2,3})", $email);
// Validar se o nº de caracteres do "username" está entre 4 e 12
if (strlen($username) < 4 || strlen($username) > 12) {
$erro = true;
$msgerro .= "<p>erro: \"username\" deve conter entre 4 e 12 caracteres</p>";
}
// Validar se o nome tem entre 3 e 40 caracteres
if (strlen($nome) < 3 || strlen($nome) > 40) {
//echo (strlen($nome));
$erro = true;
$msgerro .= "<p>erro: \"nome\" deve conter entre 3 a 40 caracteres</p>";
}
// Validação das passwords
$mudapass = false;
if (strlen($password) == 0 && strlen($rpassword) == 0) {
$mudapass = false;
} else {
$mudapass = true;
}
// 2.2. Validar o tamanho da password
if (strlen($password) < 4 || strlen($password)> 16) {
$erro = true;
$msgerro .= "<p>erro: \"password\" deve conter entre 4 a 16 caracteres</p>";
}
}
// 3. Validar se as duas passwords correspondem
if ($password != $rpassword) {
$erro = true;
$msgerro .= "<p>\"passwords\" não correspondem</p>";
}
// validação de email
// Chama a nova função "isValidEmail"
if (isValidEmail($email) == false) {
$erro = true;
$msgerro .= "<p>email inválido</p>";
}
// Final das validações (avisa caso algum erro seja detectado)
if ($erro) {
echo "<p>Formulário submetido com erros</p>";
echo $msgerro;
echo "<br>";
// Desenha 2 botões "Corrigir" e "Listar"
echo "<a class='ains' href='javascript:history.go(-1)' title='Volta à página anterior'>Corrigir </a>";
echo "<br/>";
echo "<a class='ains' href='lista.php'>Listar</a>";
exit();
}
if($password != $rpassword){
echo "ERRO: PASSWORDS SAO DIFERENTES";
}
$sql= "UPDATE usuarios SET
nome = '$nome';
email = '$email';
nivel = '$nivel';
ativo = '$ativo';
WHERE
usuario = '$username'";
if ($mudapass == TRUE) {
$sql = "UPDATE usuarios SET nome = '$nome',
password = '$password',
email = '$email',
nivel = '$nivel',
ativo = '$ativo', WHERE usuario = '$username'";
}
if ($mudapass == FALSE) {
$sql = "UPDATE usuarios SET
nome = '$nome',
email = '$email',
nivel = '$nivel',
ativo = '$ativo'
WHERE
usuario = '$username'";
}
$connection->query($sql);
// Lista users depois de actualizar
header("location:lista.php");
?>
It looks like a naming problem. Two of your variables don't seem to follow the same convention as the rest of them, and unless I'm missing some extra processing before the query, then you should change these two lines:
$apelido = trim($_POST['inivel']);
// ...several lines later
$telefone = trim($_POST['iativo']);
to this:
$nivel = trim($_POST['inivel']);
// ...several lines later
$ativo = trim($_POST['iativo']);