Filter system array - php

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

Related

My php code loops and doesn't explore my database [duplicate]

This question already has answers here:
The 3 different equals
(5 answers)
Closed 1 year ago.
Hello I'm currently trying to create a page based on a database under mysql that would update itself for a client. However what I'm trying to do loops and returns the first value of the database each time and indefinetely when I want it to go on to another object in the database. Here is the code, I'm a beginner so the error might be flagrant, thanks for the help.
<?php
try
{
$db = new PDO('mysql:host=localhost;dbname=labase', 'root' ,'');
$db->exec(" SET CHARACTER SET utf8 ");
$db->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(Exception $e){
echo'une erreur est survenue';
die();
}
for ($i = 1; $i < 10; $i++) {
if ($i=1){
$select = $db->prepare("Select profession from contact where affiliation='nord' group by profession"); // je récupère les professions de la bdd
$select->execute();
}
$data = $select->fetch(PDO::FETCH_OBJ);
$profess=$data->profession; // je prends la prochaine profession
$selectionner = $db->prepare("Select nomcontact, count(*) as nbrcontact from contact where affiliation='nord' and profession='$profess'"); // je prends les contacts qui ont cette profession ainsi que leur nombre
$selectionner->execute();
$prendre = $selectionner->fetch(PDO::FETCH_OBJ);
$nbrcontact=$prendre->nbrcontact;// je récupère leur nombre
echo $profess;
echo $nbrcontact;
}
?>
I am not a PHP expert and never use PDO, but in Msqli, there is a fetch_array() to get multiple result (instead of fetch for single result), maybe in PDO you have a fetch_array too. Then, you can loop on the result array
Something like that (using msqli)
$sql = "SELECT... FROM ..";
$result = $link->query($sql);
while($row =mysqli_fetch_array($result))
{
}
if ($i=1) { // here is should be == or ===
You're causing an infinite loop by declaring $i=1
<?php
try
{
$db = new PDO('mysql:host=localhost;dbname=labase', 'root' ,'');
$db->exec(" SET CHARACTER SET utf8 ");
$db->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(Exception $e){
echo'une erreur est survenue';
die();
}
for ($i = 1; $i < 10; $i++) {
if ($i == 1){ // added code
$select = $db->prepare("Select profession from contact where affiliation='nord' group by profession"); // je récupère les professions de la bdd
$select->execute();
}
$data = $select->fetch(PDO::FETCH_OBJ);
$profess=$data->profession; // je prends la prochaine profession
$selectionner = $db->prepare("Select nomcontact, count(*) as nbrcontact from contact where affiliation='nord' and profession='$profess'"); // je prends les contacts qui ont cette profession ainsi que leur nombre
$selectionner->execute();
$prendre = $selectionner->fetch(PDO::FETCH_OBJ);
$nbrcontact=$prendre->nbrcontact;// je récupère leur nombre
echo $profess;
echo $nbrcontact;
}
?>
Use == for comparison

Truncated incorrect DOUBLE value: | Error when trying to update data in database

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";
}

Check if foreign key exists in a database using PHP

I want to make an check for my application to see if my table in MySQL contains a foreign key. If so, I want to remove the option to delete the table containing the foreign key. Here is my code:
<html>
<head>
<link href="css/stylesheet.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<?php
require_once 'autoloader.php';
// cursusManager is verantwoordelijk voor alle person handeling op
// de database.
$cursusManager = new cursusmanager();
// Aanname dat delete de enige action is op dit scherm
if(isset($_GET["action"]) && $_GET["action"] == "delete") {
// Aanname dat het id netjes word meegenomen!
$id = $_GET["id"];
$cursusManager->delete($id);
}
// Haal alle cursussen uit de database om deze verderop te laten zien.
$cursussen = $cursusManager->getAll();
?>
<img src="images/logo.png" id="logo" />
<h2>Cursussen</h2>
<!-- simpel gridje, 123 hatsaflats -->
<div class="grid">
<div class="gridheader">Naam</div>
<div class="gridheader">Aantal jaar</div>
<div class="gridheader">Niveau</div>
<div class="gridheader gridaction"></div>
<?php
// loop door alle personen heen
// (in code bovenaan uit database gehaald)
foreach($cursussen as $cursus) {
echo "<div class='gridcontent'>$cursus->naam</div>";
echo "<div class='gridcontent'>$cursus->aantaljaar</div>";
echo "<div class='gridcontent'>$cursus->niveau</div>";
echo "<div class='gridcontent gridaction'><a href='index.php?action=delete&id=$cursus->id'>delete</a></div>";
}
?>
</div>
</body>
This is the code of my php manager:
<?php
/* cursusmanager inherits van mastermanager. Op dit moment bevat de mastermanager
* alleen nog een database verbinding.
*/
class cursusmanager extends mastermanager {
public function getById($aId) {
$statement = $this->connection->prepare("SELECT * FROM cursus WHERE id = ?");
$statement->bindValue(1, $aId);
$statement->execute();
/* fetchobject haalt het eerste record op uit het statement. PHP
* maakt hier zelf een object van, dus het model person.php wordt
* hier nu niet gebruikt. fetchobject geeft null als er geen records
* zijn
*/
return $statement->fetchObject();
}
public function getAll() {
$statement = $this->connection->prepare("SELECT * FROM cursus");
$statement->execute();
/* fetchAll(PDO::FETCH_OBJ) haalt ALLE records op uit het statement. PHP
* maakt hier zelf objecten van, fetchAll(PDO::FETCH_OBJ) geeft een lege array als
* er geen records zijn
*/
return $statement->fetchAll(PDO::FETCH_OBJ);
}
public function delete($aId) {
throw new Exception("DIT IS DUS NOG NIET GEMAAKT!");
}
}
?>
You need to connect to the Information scheme and you can find all the information about the primary key and foreign keys in this table
SELECT * FROM information_schema.TABLE_CONSTRAINTS T;
you need to be a ROOT user to access the information_schema.
USING this table you can find the table, db and whether it has foreign key.

runnun multiple functions on webpage

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.

PHP echo on top of page

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

Categories