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.
Related
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
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
I am creating a login script for my survey website, but can't seem to get it work.
log.php
<?php
// skapar en session
ob_start();
// Definererar mysql databas detaljer för att kunna göra en anslutning
$server = "127.0.0.1";
// vilken server
$user = "root";
// vad användaren heter
$password = "Redacted";
// Vad lösenordet är
$db = "LOL";
// vad databasen är
$conn = mysqli_query($server,$user,$password,$db) or die(mysqli_error($conn));
// Skapar en variable $conn och använder funktionen mysqli_query för att definera vad queryin ska använda för detaljer till databasen
// aka skapar en anslutning till databasen
// Post requests, som är parameterna fråm formerna som jag har skapat på log.php
$anv = $_POST['anv'];
$lose = $_POST['lose'];
// skyddar mot sql injection och lite xss, med hjälp av stripslahes som blockerar "arbiterary input"
$anv = stripslashes($anv);
$lose = stripslashes($lose);
/* använder mig själv av mysqli_real_escape_String, kan användas också av mysql_real_escape_string men har blivit depricerad.
Detta sanitisera queryn jag skickar till databasen */
$anv = mysql_real_escape_string($anv);
$lose = mysql_real_escape_string($lose);
/* Specifierar min query, använder en wilcard * för att söka igenom alla rows från tabellen users och kollar sedan om $anv
och $lose stämmer med det jag har skrivit in på mina parametrar. */
$query = "SELECT * FROM users WHERE anv = $anv and pass = $lose";
/* skickar nu min query med mysqli_query($conn, $query) som specifierar, först använder du databas detaljerna,
sedan använder du queryin som ska skickas. or die(mysqli_error($conn)); om det blir ett mysql fel så stänger den av anslutningen.
*/
$skicka = mysqli_query($conn, $query) or die(mysqli_error($conn));
// "skriker" eller som sagt "ekar" ;), variabeln $skicka.
// räknar sedan raderna, på variabeln $skicka och kollar om det finns någon record som stämmer in med min query.
$rakna = mysqli_fetch_array($skicka);
// Specifierar om mysql_num_rows hittar det jag har skrivit in i min query, med att använda en if och else, som kollar om $rakna
// hittar en rad med matchande.
if ($rakna == 1) {
// Kunde inte använda session_register() för att den är deprekerad, som använda mig av $_SESSION för att registrera sessionen
$_SESSION["username"] == $anv;
$_SESSION["lose"] == $lose;
// använder en redirect till enkat.php , har funderar på att göra en members area. Men vi får se.
header("location:enkat.php");
}
else {
// uHM, är ju självklart din kodapa.
print "fel lösenord eller användarnamn";
}
ob_end_flush();
?>
as user name and password are characters, you have to add quotes to the query. Change your query to
$query = "SELECT * FROM users WHERE anv = '".$anv."' and pass = '".$lose."'";
Hello! I'm having some trouble making a login for normal users, I have to tables, one is for admin users and the other for employees. The thing is that I want to use the same login and in the PHP first check if the username exists in the table admintable and if not check if it exits in empTable.
Here is my code:
It is working and recognizing only admin users but then when I try to log in with employee users it doesn't log in.
THANKS!!
<?php
include 'cod/php/utils.php';
if(isset($_POST['txtuser']) )
{
//get data from POST
$txtuser = $_POST['txtuser'];
$txtpass = $_POST['txtpass'];
//verificar que exista el usuario en la tabla de admins
if(exists('admintable', 'Username', $txtuser))
{
//obtener el password del usuario
if(get_value('admintable', 'Password', 'Username', $txtuser) == $txtpass)
{
//iniciar sesion
session_start();
//almacenar el usuario en esta sesion
$_SESSION['usuario'] = $txtuser;
header('Location: web/admin.php');
}
}
//verificar que exista el usuario en la tabla de admins
else if(exists('empTable', 'empUsername', $txtuser))
{
//obtener el password del usuario
if(get_value('empTable', 'empPassword', 'empUsername', $txtuser) == $txtpass)
{
//iniciar sesion
session_start();
//almacenar el usuario en esta sesion
$_SESSION['usuario'] = $txtuser;
header('Location: web/usr.php');
}
}
else
{
print_login(true);
}
}
else
{
print_login(true);
}
else
{
print_login(false);
}
}
function print_login($showerror)
{}
?>
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.