creating an array from database - php

I'm using a array to get a range between 1011-2371 but I'didnt need all digits. It's a long list thats why I import the CSV to the database.
I want to create a array from a database table.
But I can't get it.
Here's a rough mockup of the old php:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']?>">
<input type="text" placeholder="1234AB" name="postcode" />
<input type="submit" value="verstuur" />
</form>
<?php
if($_SERVER['REQUEST_METHOD'] == "POST") {
$postcode = range(1011,2371);
if(preg_match('/^[1-9][0-9]{3} ?[a-zA-Z]{2}$/', $_POST['postcode'])) {
if(in_array($_POST['postcode'],$postcode)) {
echo 'FreshFoods is beschikbaar bij jou in de buurt.';
} else {
echo 'FreshFoods is nog niet beschikbaar bij u in de buurt.';
}
} else {
echo 'Voer 4 cijfers en 2 letters in als postcode. Voorbeeld 1234AB';
}
}
?>
and this is what I try do get the array from the database:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']?>">
<input type="text" placeholder="1234AB" name="postcode" />
<input type="submit" value="verstuur" />
</form>
<?php
require_once 'db_config.php';
if($_SERVER['REQUEST_METHOD'] == "POST") {
$postcode = array();
$result = mysql_query("SELECT postcode FROM postcode_check");
if(preg_match('/^[1-9][0-9]{3} ?[a-zA-Z]{2}$/', $_POST['postcode'])) {
if(in_array($_POST['postcode'],$postcode)) {
echo 'FreshFoods is beschikbaar bij jou in de buurt.';
} else {
echo 'FreshFoods is nog niet beschikbaar bij u in de buurt.';
}
} else {
echo 'Voer 4 cijfers en 2 letters in als postcode. Voorbeeld 1234AB';
}
}
?>
the db_config.php file looks like:
<?php
$db = array (
'host' => 'localhost',
'user' => 'root',
'pass' => 'root',
'dbname' => 'testzip'
);
if(!mysql_connect($db['host'], $db['user'], $db['pass']))
{
trigger_error('Fout bij verbinden: '.mysql_error());
}
elseif(!mysql_select_db($db['dbname']))
{
trigger_error('Fout bij selecteren database: '.mysql_error());
}
else
{
$sql = "SET SESSION sql_mode = 'ANSI,ONLY_FULL_GROUP_BY'";
if(!mysql_query($sql))
{
trigger_error('MySQL in ANSI niet mogelijk');
}
}
?>

you have to use mysql_fetch_array or mysql_fetch_assoc to fetch the result from database.
<form method="post" action="<?php echo $_SERVER['PHP_SELF']?>">
<input type="text" placeholder="1234AB" name="postcode" />
<input type="submit" value="verstuur" />
</form>
<?php
require_once 'db_config.php';
if($_SERVER['REQUEST_METHOD'] == "POST") {
$postcode = array();
$result = mysql_query("SELECT postcode FROM postcode_check");
while ($row = mysql_fetch_array($result)) {
$postcode[] = $row['postcode'];
}
if(preg_match('/^[1-9][0-9]{3} ?[a-zA-Z]{2}$/', $_POST['postcode'])) {
if(in_array($_POST['postcode'],$postcode)) {
echo 'FreshFoods is beschikbaar bij jou in de buurt.';
} else {
echo 'FreshFoods is nog niet beschikbaar bij u in de buurt.';
}
} else {
echo 'Voer 4 cijfers en 2 letters in als postcode. Voorbeeld 1234AB';
}
}
?>
Try this code.

You need to fetch the result. Your regex will never match your sample data from the db though so you will always get the nog niet message. or voorbeeld. Never 'FreshFoods is beschikbaar bij jou in de buurt'
<form method="post" action="<?php echo $_SERVER['PHP_SELF']?>">
<input type="text" placeholder="1234AB" name="postcode" />
<input type="submit" value="verstuur" />
</form>
<?php
require_once 'db_config.php';
if($_SERVER['REQUEST_METHOD'] == "POST") {
$postcode = array();
$result = mysql_query("SELECT postcode FROM postcode_check");
while($row = mysql_fetch_assoc($result)){
$postcode[] = $row['postcode'];
}
if(preg_match('/^[1-9][0-9]{3} ?[a-zA-Z]{2}$/', $_POST['postcode'])) {
if(in_array($_POST['postcode'],$postcode)) {
echo 'FreshFoods is beschikbaar bij jou in de buurt.';
} else {
echo 'FreshFoods is nog niet beschikbaar bij u in de buurt.';
}
} else {
echo 'Voer 4 cijfers en 2 letters in als postcode. Voorbeeld 1234AB';
}
}
?>

Related

Restaurant menu sorted by type of meal

I'm trying to sort a restaurant menu by type of meal. So appetizers first, main dish second, desert last.
When adding it to the database I use "soort" which gives it a type of meal.
When I run this code it wil show me the main dish, desert, appetizer which is the wrong order.
I can't figure out how to sort it the way I want it.
<?php
// vul de variable in die gebruikt worden om een connectie te maken (inlog gegevens)
$servername = "localhost";
$username = "root";
$password = "";
$naam = $soort = $prijs = $bijzonderheden = "";
$foutmelding1 = $foutmelding2 = $foutmelding3 = $foutmelding4 = "";
try {
$pdo = new PDO("mysql:host=$servername;dbname=restaurant", $username, $password);
// set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
// connectie is mislukt
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
<html>
<head>
</head>
</body>
<table>
<tr>
<th> Gerecht </th> <th> Soort </th> <th> Prijs </th> <th> Bijzonderheden </th>
</tr>
<?php
$sth = $pdo->prepare('select * from gerechten ORDER BY Soort ');
$sth->execute();
while($row = $sth->fetch())
{
echo "<tr> ";
echo "<td>" . $row['Naam'] . "</td>";
echo "<td>" . $row['Soort'] . "</td>";
echo "<td> " . $row['Prijs'] . "</td>";
echo "<td> " . $row['Bijzonderheden'] . "</td>";
echo "</tr> ";
}
// de update knoppen doorverwijzen met een href --> en dan een form maken voor 1 rij <-----------
?>
</table>
<style type="text/css">
table {
border-collapse: ;
border: 1px solid black;
padding: 5px;
}
td {
/* border: 1px solid black;
width: 25px; */
text-align: center;
padding: 15px;
}
</style>
</html>
This is the code that inserts the data in the database
<?php
// vul de variable in die gebruikt worden om een connectie te maken (inlog gegevens)
$servername = "localhost";
$username = "root";
$password = "";
$naam = $soort = $prijs = $bijzonderheden = "";
$foutmelding1 = $foutmelding2 = $foutmelding3 = $foutmelding4 = "";
try {
$pdo = new PDO("mysql:host=$servername;dbname=restaurant", $username, $password);
// set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
// connectie is mislukt
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
// maakt een query
if(isset($_POST['submit']))
{
// begin waarde van de fout check variable
$fout = FALSE;
// POST bijzonderheden mag hier wel blijven, want dat veld is niet verplicht om in te vullen.
$bijzonderheden = $_POST['bijzonderheden'];
// checkt of het veld 'naam' gevult is, zo niet dan geeft hij de melding vul het veld naam in
if (!empty($_POST['naam'])) {
$naam = $_POST['naam'];
}
else { $foutmelding1 = "vul het veld naam in";
$fout = TRUE;
}
// checkt of het veld 'soort' gevult is, zo niet dan geeft hij de melding vul het veld naam in
if (!empty($_POST['soort'])) {
$soort = $_POST['soort'];
}
else { $foutmelding2 = "vul het veld soort in";
$fout = TRUE;
}
// checkt of het veld 'prijs' gevult is, zo niet dan geeft hij de melding vul het veld naam in
if (!empty($_POST['prijs'])) {
$prijs = $_POST['prijs'];
}
else { $foutmelding3 = "vul het veld prijs in";
$fout = TRUE;
}
// checkt of het veld 'bijzonderheden' gevult is, zo niet dan geeft hij de melding vul het veld naam in
// if (!empty($_POST['bijzonderheden'])) {
// $bijzonderheden = $_POST['bijzonderheden'];
// }
// else { $foutmelding4 = "vul het veld bijzonderheden in";
// $fout = TRUE;
// }
if ($fout == FALSE)
{
// array aanmaken voor de parameters.
// Een array wordt gebruikt om de gegevens beveiligd te houden.
$parameters = array(':naam'=>$naam,
':soort'=>$soort,
':prijs'=>$prijs,
':bijzonderheden'=>$bijzonderheden);
// maakt een query die iets in de database gaat zetten
$sth = $pdo->prepare('INSERT INTO gerechten ( Naam, Soort, Prijs, Bijzonderheden) VALUES (:naam, :soort, :prijs, :bijzonderheden)');
$sth->execute($parameters);
echo "toevoegen gelukt";
header("Refresh:3");
}
}
$sth = $pdo->prepare('select * from gerechten');
$sth->execute();
//while($row = $sth->fetch())
//{
// echo '<br />' . $row['Naam'].'<br />'.'<br />';
//}
?>
<html>
<body>
<h2>Gerecht toevoegen aan de database</h2>
<form action="" method="post">
Naam: <input type="text" name="naam" value="<?php echo $naam ?>"> <?php echo $foutmelding1; ?> <br>
Soort:
<select id="soort" name="soort">
<option value="voorgerecht" <?php if($soort == "voorgerecht") echo "selected" ?>>Voorgerecht</option>
<option value="hoofdgerecht" <?php if($soort == "hoofdgerecht") echo "selected" ?>>Hoofdgerecht</option>
<option value="nagerecht" <?php if($soort == "nagerecht") echo "selected" ?> >Nagerecht</option>
</select> <?php echo $foutmelding2; ?><br>
Prijs <input type="number" min="1" step="any" " name="prijs" value="<?php echo $prijs ?>"> <?php echo $foutmelding3; ?><br>
Bijzonderheden <input type="text" name="bijzonderheden" value="<?php echo $bijzonderheden ?>"><br>
<input type="submit" name="submit" value="verzenden"><br>
</form>
</body>
</html>
Needed to store the meal order in db first.
Table Meal
Meal(int id_autonumber PK, varchar mealType key, int mealOrder)
(1,appetiser,1)
(2,main dish,2)
... etc
Then you get ordered by invoke sql = select mealType from Meal order by mealOrder
insert into wp_meal(mealType,mealOrder) values ('appetizer',1);
insert into wp_meal(mealType,mealOrder) values ('desert',3);
insert into wp_meal(mealType,mealOrder) values ('main dish',2);
Look at differences
CREATE TABLE `wp_meal` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`mealType` varchar(128) COLLATE utf8mb4_unicode_520_ci NOT NULL,
`mealOrder` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci

Update mysqli database by filling in only one of many input fields

I am making a very simple movie database, with the possibility to update the movies that are in it. All you have to do is fill in the fields underneath the table. However, when you fill in the id and only one other field, like film_id, the description etc. are erased from the table. How do i make sure that it's possible to change only one thing?
The code for the page:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<?php
session_start(); //Start sessie.
function is_logged() {
if (isset($_SESSION['username'])) return true;
return false; //De gebruikersnaam wordt gecontroleerd
}
if(!is_logged()){
header("Location: sign-in.php"); //Als de gebruiker naar overzichtlogin.php
gaat, zonder dat hij of zij is ingelogd, worden ze doorgestuurd naar de
login pagina.
}
require_once('db_const.php'); //De gegevens voor het maken van de verbinding
met de database staan in dit bestand gedeclareerd.
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if (!$mysqli){
die("Connection failed: ".mysqli_connect_error()); //Als de verbinding niet
lukt zal deze niet werken.
}
?>
<?php $current = 'secured'; ?> <!-- Om aan te geven dat men zich op de
beveiligde overzichtspagina bevindt, wordt gebruik gemaakt van deze
variabele. Current krijgt nu de waarde 'secured', waardoor de button waar
'secured' staat een kleur krijgt. -->
<div class="header">
<?php
if(isset($_SESSION['username'])){
require_once("headersecured.php"); //Indien de gebruiker ingelogd is, wordt
'headersecured.php' gebruikt als header.
}else{
require_once("header.php"); //Indien de gebruiker niet is ingelogd, wordt
header.php gebruikt als header.
}
?>
</div>
<h1>Filmoverzicht</h1>
<?php
$sql = "SELECT film_id, title, description, release_year, rating FROM
films"; //De gewenste gegevens uit de database worden geselecteerd.
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
echo "<table style='border: solid 1px grey; margin-left: auto; margin-right:
auto; margin-top:50px;'><tr><th>ID</th> <th>Titel</th> <th>Beschrijving</th>
<th>Jaar</th> <th>Rating</th> <th> </th></tr>";
while($row = $result->fetch_assoc()) {
echo "<tr><td>" .$row["film_id"] . "<td>" .$row["title"] . "<td>" .
$row["description"] . "<td>" . $row["release_year"]. "<td> " .
$row["rating"]. "<td> " . '<td><a class="alert" href="deletemovie.php?
id='.$row['film_id'].'" >
</i>'?> VERWIJDER <?php '</a></td>';
} //De beschikbare gegevens worden weergegeven.
echo "</table>";
} else {
echo "0 results";
}
?>
<br><br>
<form method="post" action="<?php $_SERVER["PHP_SELF"]; ?>"> <!--De
bewerkfunctie wordt op dezelfde pagina uitgevoerd.-->
<h2>Films bewerken</h2>
<input name="film_id" required="required" placeholder="ID">
<input name="title" placeholder="Titel film">
<textarea id="textarea" name="description" cols="20" rows="5"
placeholder="Beschrijving"></textarea>
<input name="release_year" placeholder="Uitkomstjaar">
<input name="rating" placeholder="Beoordeling">
<input id="submit" name="submit" type="submit" value="Wijzigen"> <!-- In
deze
invulvelden kunnen nieuwe gegevens worden ingevoerd, zodat de films worden
aangepast. -->
<?php
if (isset($_POST['submit'])) {
$film = $_POST["film_id"]; //Slaat de gegevens voor het ingevoerde ID op in
een
variabele.
$title = $_POST["title"]; //Slaat de gegevens voor de ingevoerde titel op in
een
variabele.
$description = $_POST["description"]; //Slaat de gegevens voor de ingevoerde
beschrijving op in een variabele.
$year = $_POST["release_year"]; //Slaat de gegevens voor het ingevoerde jaar
op
in een variabele.
$rating = $_POST["rating"]; //Slaat de gegevens voor de ingevoerde rating op
in een variabele.
$sql = "UPDATE films SET film_id = '$film', title = '$title', description =
'$description', release_year = '$year', rating = '$rating' WHERE film_id =
$film"; //De tabel 'films' in MySQL wordt geselecteerd, de gegevens die in
de
variabelen zijn opgeslagen worden gewijzigd in de database.
if (mysqli_query($mysqli, $sql)) { // Voert de actie uit
echo "<br>"; // Wit ruimte
echo "<br>"; // Wit ruimte
echo "<br>"; // Wit ruimte
echo "Succesvol aangepast!"; // Geeft aan dat het aangepast is
echo "<br>"; // Wit ruimte
echo "<a href='overzichtspagina.php'>Terug naar de vorige pagina.</a>"; //
een link waar de gebruiker terug kan gaan naar de vorige pagina
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($mysqli); // geef fout
melding aan de gebruiker als het mis gaat
}
}
?>
</form>
<?php
$mysqli->close(); //Verbinding wordt verbroken.
?>
<div class="footer">
<?php include 'footer.php';?> <!-- De footer wordt opgehaald. -->
</div>
</body>
</html>
The problem is when the $_POST["description"] is not defined the value of $description is taken as NUll. In order to avoid this the Update query has to be constructed dynamicaly.
$sql = "UPDATE films SET film_id = '$film', title = '$title'";
if(isset($_POST["description"])) {
$description = $_POST["description"];
$sql .= ", description = $description"
}
$sql .= ", release_year = '$year', rating = '$rating' WHERE film_id = $film";
In this case when the $_POST["description"] is not set the query becomes "UPDATE films SET film_id = '$film', title = '$title', release_year = '$year', rating = '$rating' WHERE film_id = $film";
or else the query becomes "UPDATE films SET film_id = '$film', title = '$title', description = $description, release_year = '$year', rating = '$rating' WHERE film_id = $film";
You have to check on multiple values for validation, because you want that at least one field (other than film ID) is completed. If none provided, than notify the user. This validation should be made on client-side (with js, jquery, validation plugins, etc).
Then, you must dynamically build your sql statement. Use sprintf()
function for such "complex" constructs. It's very elegant. In it, the %s parts are placeholders for the variables.
Please notice the UPDATE statement: you don't want to update the
film_id field! You must use it ONLY to select the one record which
you want to update (e.g. just in WHERE clause). If you want to
change film_id, you must reinsert a record with the new id.
You are missing the <body> tag.
I was bringing last php code UNDER the </form> tag.
As a general rule: separate display logic from server processing.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>My films</title>
</head>
<body>
<?php
$mysqli = new mysqli('localhost', 'root', 'root', 'tests');
if (!$mysqli) {
die("Connection failed: " . mysqli_connect_error());
}
?>
<!-- ... -->
<form method="post" action="<?php $_SERVER["PHP_SELF"]; ?>">
<h2>Films bewerken</h2>
<input name="film_id" required="required" placeholder="ID">
<input name="title" placeholder="Titel film">
<textarea id="textarea" name="description" cols="20" rows="5" placeholder="Beschrijving"></textarea>
<input name="release_year" placeholder="Uitkomstjaar">
<input name="rating" placeholder="Beoordeling">
<input id="submit" name="submit" type="submit" value="Wijzigen">
</form>
<?php
if (isset($_POST['submit'])) {
$film = $_POST["film_id"];
$title = $_POST["title"];
$description = $_POST["description"];
$year = $_POST["release_year"];
$rating = $_POST["rating"];
$message = '<br/><br/><br/>';
if (!isset($film)) {
$message .= 'You must provide the film ID!';
} elseif (
(!isset($title) || empty($title)) &&
(!isset($description) || empty($description)) &&
(!isset($year) || empty($year)) &&
(!isset($rating) || empty($rating))
) {
$message .= 'You must provide at least one field for the selected film ID!';
} else {
$sql = sprintf(
"UPDATE films SET %s%s%s%s WHERE film_id = %s"
, isset($title) ? "title = '$title'" : ""
, isset($description) ? ", description = '$description'" : ""
, isset($year) ? ", release_year = '$year'" : ""
, isset($rating) ? ", rating = '$rating'" : ""
, $film
);
if (mysqli_query($mysqli, $sql)) {
$message .= "Succesvol aangepast!";
$message .= "<br>";
$message .= "<a href='overzichtspagina.php'>Terug naar de vorige pagina.</a>";
} else {
$message .= "Error: " . $sql . "<br>" . mysqli_error($mysqli);
}
}
echo $message;
}
$mysqli->close();
?>
</body>
</html>
EDIT 1:
I recommend you to use exception handling. Here is an example:
try {
// Connect to db.
$mysqli = new mysqli('localhost', 'root', 'root', 'tests');
if (!isset($mysqli) || !$mysqli) {
throw new Exception("Connection failed: " . mysqli_connect_error());
}
// Run query on db.
$query = mysqli_query($mysqli, $sql);
if (!$query) {
throw new Exception('The statement can not be executed!');
}
$mysqli->close();
} catch (Exception $exception) {
echo $exception->getMessage();
/*
* OR display the whole error information.
* But only in the development stage!
*/
// echo '<pre>' . print_r($exception, true) . '</pre>';
exit();
}
Don't forget to add a <title> tag to your page.

Fill in form in PHP

So I've had to make a simple phonebook in PHP, but right now it simply echos the text beneath the form, I however, want it to fill it in the form which says: Phonenumber (When you type in the exact name of someone you it echos their phonenumber)
Here's the Form:
<form action="" method="post">
Naam: <br><input type="text" name="name" /><br>
Telefoonnummer: <br><input type="text" name="phonenumber" disabled />
<input type="submit" value="submit" />
</form>
and here's the PHP (I'm Dutch btw so some of the text is in Dutch):
<?php
if(isset($_POST['name'])) {
$formNaam = $_POST['name'];
$naamPersoon = array ("Ilja Clabbers","Piet Paulusma","Gerrit Zalm");
$telefoonNummer = array ("038-4699776","0568-121212","010-2311512");
if(empty($formNaam)) {
echo 'Vul een veld in.';
} else if ($formNaam == $naamPersoon[0]){
echo "Het telefoonnummer van " . $naamPersoon[0] . " is " .$telefoonNummer[0];
} else if ($formNaam == $naamPersoon[1]){
echo "Het telefoonnummer van " . $naamPersoon[1] . " is " .$telefoonNummer[1];
} else if ($formNaam == $naamPersoon[2]){
echo "Het telefoonnummer van " . $naamPersoon[2] . " is " .$telefoonNummer[2];
} else {
echo "Deze naam staat niet in het archief";
}
}
?>
So basically what I'd like to know is; How do you get the phonenumber belonging to a persons name to be shown in the Form where it says 'Telefoonnummer:'?
A neater solution would be to make a single associative array with key => value pairs:
$naamPersoon = array (
"Ilja Clabbers" => "038-4699776",
"Piet Paulusma" => "0568-121212",
"Gerrit Zalm" => "010-2311512",
);
Then your code would be:
$phonenumber = '';
if (array_key_exists($formNaam, $naamPersoon)) {
echo "Het telefoonnummer van " . $formNaam . " is " . $naamPersoon[$formNaam];
$phonenumber = $naamPersoon[$formNaam];
} else {
echo "Deze naam staat niet in het archief";
}
Alternatively you could keep your two arrays as they are and use array_search to find the index of the name in the first array, then use it as the index you check in the second array
$phonenumber = '';
$index = array_search($formNaam, $naamPersoon);
if ($index === false) {
echo "Deze naam staat niet in het archief";
} else {
echo "Het telefoonnummer van " . $formNaam . " is " . $telefoonNummer[$index];
$phonenumber = $telefoonNummer[$index];
}
Either way you can then use the assigned variable $phonenumber to add the number to the form by echoing it out as the input's value. At which point you can take out the echos if you wish.
<form action="" method="post">
Naam: <br><input type="text" name="name" /><br>
Telefoonnummer: <br><input type="text" name="phonenumber" value="<?=htmlspecialchars($phonenumber)?>" disabled />
<input type="submit" value="submit" />
</form>

PHP Unexpected T_VARIABLE

I'm making a basic lotery script and i'm getting the same error the whole time: Unexpected T_Variable on line 5. Here is my script, I hope someone can help me:
<?php
$invulcijfer = '';
if (isset($_POST['sumbitBtn']))
{
$invulcijfer = $_POST['cijfer'];
$pinda = preg_replace("/[^0-9]/", "", $invulcijfer);
$lotnummer = "1234"; // Hier je 4 cijfers voor lotnummer
if($invulcijfer = '') {
echo "<font color='#FF000'>Je moet alles invullen</font>";
} else if($pinda !== $invulcijfer) {
echo "<font color='#FF000'>Dat zijn geen cijfers</font>";
} else {
if ($pinda == $lotnummer) {
     echo "<font color='green'>WAUW! Het is je gelukt!</font>";
} else {
echo "<font color='#FF000'>Sorry, het is niet gelukt..</font>";
// Maybe update query van dat ze - points hebben ofso? q wat jij wilt
}
}
}
}?>
<br><br>
<h3>Loterij Script</h3>
<font color="green">Typ 4 cijfers in en misschien win jij!</font><br><br>
<form action="" method="post">
<input type="text" id="naam" name="naam" maxlength="4"/><br>
<input type="text" id="cijfer" name="cijfer" maxlength="4"/><br>
<input type="submit" id="submitBtn" name="submitBtn" value="Check je lot"/>
</form>
EDIT
I spotted a few errors:
THIS:
if (isset($_POST['sumbitBtn']))
it needs to read as
if (isset($_POST['submitBtn']))
there was a spelling mistake.
Also if($invulcijfer = '') { needs to be if($invulcijfer == '') {
You have one closing brace too many.
Remove the one this one in }?> and your script will work.
This is the code that I ran, deleting the extra closing brace.
EDIT #2 (fixed conditions and spelling mistake for submit button.
<?php
$invulcijfer = '';
if (isset($_POST['submitBtn']))
{
$invulcijfer = $_POST['cijfer'];
$pinda = preg_replace("/[^0-9]/", "", $invulcijfer);
$lotnummer = "1234"; // Hier je 4 cijfers voor lotnummer
if($invulcijfer == '') {
echo "<font color='#FF000'>Je moet alles invullen</font>";
}
elseif ($pinda !== $invulcijfer){
echo "<font color='#FF000'>Dat zijn geen cijfers</font>";
} else {
if ($pinda == $lotnummer) {
echo "<font color='green'>WAUW! Het is je gelukt!</font>";
}
else {
echo "<font color='#FF000'>Sorry, het is niet gelukt..</font>";
// Maybe update query van dat ze - points hebben ofso? q wat jij wilt
}
}
}
?>
<br><br>
<h3>Loterij Script</h3>
<font color="green">Typ 4 cijfers in en misschien win jij!</font><br><br>
<form action="" method="post">
<input type="text" id="naam" name="naam" maxlength="4"/><br>
<input type="text" id="cijfer" name="cijfer" maxlength="4"/><br>
<input type="submit" id="submitBtn" name="submitBtn" value="Check je lot"/>
</form>

My edit page doesnt edit the rows [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I have 2 buttons on my table which delete and edit data from the table, (data from the database) the delete button works well but the edit isnt working.. It runs like it is working but when I list the data it is like I created in the PhpMyadmin..
here is the main edit code:
<?php
// Editar um registo de user
if (isset($_GET['editequip']) == False) {
// Caso seja chamado directamente na URL o ficheiro "editar.php",
// este é redireccionado para o ficheiro "lista.php"
header("location:javascript:history.go(-1);return false;;");
} else {
$editequip = trim($_GET['editequip']);
}
$connection = new mysqli('***', '****', '****', '****');
$obterequip = "SELECT * FROM fichas WHERE id_ficha LIKE '$editequip'";
$resultequip = $connection->query($obterequip);
// Se devolveu 0 ou mais do que um utilizador, termina script
if ($connection->affected_rows != 1) {
header("location:javascript:history.go(-1);return false;");
exit();
}
$objequip = $resultequip->fetch_object();
$id_ficha = $objequip->id_ficha;
$id_user = $objequip->id_user;
$avaria = $objequip->avaria;
$observacoes = $objequip->observacoes;
$observacoes_privadas = $objequip->observacoes_privadas;
$estado = $objequip->estado;
?> <!DOCTYPE HTML>
<html><head>
<link href="css/style.css" rel="stylesheet" type="text/css" />
<link href="favicon.ico" rel="shortcut icon">
<title>Edição de Equipamentos</title></head>
<body>
<div id="links">
Voltar ao site |
Ínicio |
Utilizadores |
Upload de Ficheiros |
Logout
</div>
<h1>Editar Estado</h1>
<div id="container"><div class="left">
<form action="updatequip.php" method="post" id="editar">
<input type="hidden" name="ificha" value="<?php echo $id_ficha ?>"/>
<label>ID da Ficha: </label> <?php echo $id_ficha ?> <br>
<label>ID do Cliente: </label><input type="text" name="iuser" value="<?php echo $id_user ?>"><br>
<label>Avaria: </label><input type="text" name="iavaria" value="<?php echo $avaria ?>"><br>
<label>Observações: </label><input type="text" name="iobservacoes"value="<?php echo $observacoes ?>"><br>
<label>Observações Privadas: </label><input type="text" name="iobservacoes_privadas" value="<?php echo $observacoes_privadas?>"><br>
<label>Estado</label><input type="text" name="iestado" value="<?php echo $estado ?>"><br>
<input type="submit" value="Alterar"/>
<input type="button" value="Cancelar"onclick="javascript:history.go(-1);return false;"/>
</form>
</div>
</div>
<div class="footer">
<p>Copyright © 2013 - Todos os direitos reservados - Númica</p>
</div>
</body>
</html>
and the action page:
<?php
// Inserir o registo na BD
include_once ('config1.php');
// Estabelecer a ligação à BD
$connection = new mysqli('*****', '*****', '*******', '***');
//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['ificha']) == FALSE) {
echo ("Erro de submissão no ida da ficha");
exit();
} else {
$id_ficha = trim($_POST['ificha']);
}
if (isset($_POST['iuser']) == FALSE) {
echo ("Erro de submissão do id do user");
exit();
} else {
$id_user = trim($_POST['iuser']);
}
if (isset($_POST['iavaria']) == FALSE) {
echo ("Erro de submissão da avaria");
exit();
} else {
$avaria = trim($_POST['iavaria']);
}
if (isset($_POST['iobservacoes']) == FALSE) {
echo ("Erro de submissão nas observacoes");
exit();
} else {
$observacoes = trim($_POST['iobservacoes']);
}
if (isset($_POST['iobservacoes_privadas']) == FALSE) {
echo ("Erro de submissão nas observacoesprivadas");
exit();
} else {
$observacoes_privadas = trim($_POST['iobservacoes_privadas']);
}
if (isset($_POST['iestado']) == FALSE) {
echo ("Erro de submissão no estado");
exit();
} else {
$estado = trim($_POST['iestado']);
}
// 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='verificarequipamentos.php'>Listar</a>";
exit();
}
$sql = "UPDATE fichas SET
id_user = '$id_user';
avaria = '$avaria';
observacoes = '$observacoes';
observacoes_privadas = '$observacoes_privadas';
estado = '$estado';
WHERE
id_ficha = '$id_ficha'";
$connection->query($sql);
// Lista users depois de actualizar
header("location:verificarequipamentos.php");
?>
Change the semicolons to comas on the update query Or concat the variables with dots, You shoud also use a framework for this kind of things, it could be much easier.

Categories