Edit/update row with php doesn't work / Undefined variable - php

There is something wrong with my code :
On the edit page, I want to show the user the previous value in the input box.
But one error I keep getting about the value is the following :
Notice: Undefined variable: gebruikers_naam in C:\xampp\htdocs\website_herkansing\edit_gebruiker.php on line 72
I think there is something wrong with the isset/submit part but I just
can not figure it out..
Here is the code I'm working with
<?php
session_start();
define('DB_NAME', 'ochtendgloren');
$servername = "localhost";
$username = "root";
$password = "";
$db = "ochtendgloren";
$tbl = "members";
// Create connection
$conn = new mysqli($servername, $username, $password, $db);
//Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['submit']))
{
$gebruikers_naam = mysqli_real_escape_string($db, $_POST['gebruikers_naam']);
htmlentities($gebruikers_naam);
$id = $_GET['id'];
$query = "UPDATE members
SET gebruikers_naam = '$gebruikers_naam'
WHERE id = '$id' " ;
$result = $conn->query($query);
if($result){
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('edit succesvol!')
window.location.href='admin_members.php';
</SCRIPT>");
}
}
?>
<html>
<head>
<link rel="stylesheet" href="boekingsform.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Abel">
</head>
<div class="boeken">
<h1>Wijzig hier de gebruiker</h1>
<form action="editrij.php?id=<?= $id ?>" method="post" >
<div class="row">
<div class="col-25">
<label for="gebruikers_naam"> vul hier de nieuwe gebruikers naam in: </label>
</div></div>
<br>
<div class="row">
<div class="col-75">
<input type="text" name="voornaam" required="required" value="<?= $gebruikers_naam['gebruikers_naam'] ?>"/>
</div>
</div>
<br>
<input type="submit" value="submit" name="submit" />
</form>
</div>
</html>

I think the problem is related with your variable usage and name of input box it must be gebruikers_naam
On line :
<input type="text" name="voornaam" required="required" value="<?= $gebruikers_naam['gebruikers_naam'] ?>"/>
You may use $gebruikers_naam only to print the name.
Also you must assign a global variable before before using it in if clause.
Just assign null like $gebruikers_naam = ""; after variables declarations.

You aren't sending the variable gebruikers_naam, but voornaam. This line of code
<input type="text" name="voornaam" required="required" value="<?= $gebruikers_naam['gebruikers_naam'] ?>"/>
Should be
<input type="text" name="gebruikers_naam" required="required" value="<?= $gebruikers_naam['gebruikers_naam'] ?>"/>
Also, because you are using the variables $id and $gebruikers_naam in the form, you should assign them a value before the if clause.

Still not completely sure the 'flow' of your code makes a lot of sense, but following should help a bit:
<?php
session_start();
//define('DB_NAME', 'ochtendgloren'); // not used in your code, commented out
$servername = "localhost";
$username = "root";
$password = "";
$db = "ochtendgloren";
$tbl = "members";
// Create connection
$conn = new mysqli($servername, $username, $password, $db);
//Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['submit']))
{
if(isset($_POST['gebruikers_naam']) && !empty($_POST['gebruikers_naam'])) { // added condition: we need a 'gebruikers_naam'
$gebruikers_naam = mysqli_real_escape_string($conn, $_POST['gebruikers_naam']); // changed $db to $conn
// the return value (encoded string) of htmlentities is not used in your code
// so commented it out
//htmlentities($gebruikers_naam);
$id = $_GET['id'];
$query = "UPDATE members
SET gebruikers_naam = '$gebruikers_naam'
WHERE id = '$id' " ;
$result = $conn->query($query);
}
if($result){
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('edit succesvol!')
window.location.href='admin_members.php';
</SCRIPT>");
} else { // added else {} statement
echo "<script> alert('Error: could not update the database'); </script>"; // added: error message
}
}
?>
<html>
<head>
<link rel="stylesheet" href="boekingsform.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Abel">
</head>
<div class="boeken">
<h1>Wijzig hier de gebruiker</h1>
<form action="editrij.php?id=<?php echo $id; ?>" method="post" > <!-- you need to echo $id and close with ';' - changed: echo $id; -->
<div class="row">
<div class="col-25">
<label for="gebruikers_naam"> vul hier de nieuwe gebruikers naam in: </label>
</div></div>
<br>
<div class="row">
<div class="col-75">
<?php $gebruikers_naam = (isset($gebruikers_naam)) ? $gebruikers_naam : 'N/A'; ?> <!-- added a test to see if $gebruikers_naam is available -->
<input type="text" name="voornaam" required="required" value="<?php echo $gebruikers_naam; ?>"/> <!-- variable is $gebruikers_naam, changed (echo and ';') -->
</div>
</div>
<br>
<input type="submit" value="submit" name="submit" />
</form>
</div>
</html>

Related

Insert And Retrieve Data in MySQL with $.post Noob Question

Trying to insert data into MySQL database with PHP. I don't want to refresh the page. The data isn't inserted when I press the Send Message button, but the data is displayed. Please help a noob out. Here's the HTML:
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML Contact Form</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<div class="form">
<form method="POST" action="form.php" id="foo" name="foo">
<h1>Contact Form</h1>
<table>
<tr>
<td>
<label for="fname">Full Name:</label><br>
<input type="text" name="fname" placeholder="John Doe" id="">
</td>
</tr>
<tr>
<td>
<label for="email">Your Email:</label><br>
<input type="email" name="email" placeholder="example#gmail.com" id="">
</td>
</tr>
<tr>
<td>
<label for="msg">Your Message:</label><br>
<textarea name="msg" placeholder="Type your message..." id="" cols="30" rows="10"></textarea>
</td>
</tr>
<tr>
<td>
<input type="submit" name="submit" value="Send Message">
</td>
</tr>
</table>
</form>
</div>
<p id="target">
</p>
<script>
$(function() {
$("#foo").submit(function(event){
// Stop form from submitting normally
event.preventDefault();
/* Serialize the submitted form control values to be sent to the web server with the request */
var formValues = $(this).serialize();
// Send the form data using post
$.post("form.php", formValues, function(response){
$('#target').load('show.php');
});
});
});
</script>
</body>
</html>
Here's form.php which is supposed to insert data into the database:
<?php
error_reporting(E_ALL);
log_errors(1);
display_errors(1);
if(isset($_POST['submit']))
{
$name = $_POST['fname'];
$email = $_POST['email'];
$message = $_POST['msg'];
//database details. You have created these details in the third step. Use your own.
$host = "localhost";
$username = "user";
$password = "GoTn_1290";
$dbname = "form_entriesdb";
//create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$con = mysqli_connect($host, $username, $password, $dbname);
//check connection if it is working or not
if (!$con)
{
die("Connection failed!" . mysqli_connect_error());
}
//This below line is a code to Send form entries to database
$sql = $con->prepare("INSERT INTO contactform_entries (name_fld, email_fld, msg_fld) VALUES (?, ?, ?)");
$sql->bind_param("sss", $name, $email, $message);
$sql->execute();
//connection closed.
$sql->close();
$con->close();
}
?>
And here's what displays my data, show.php:
<?php
$servername = "localhost";
$username = "user";
$password = "secret";
$dbname = "form_entriesdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql2 = "SELECT id, name_fld, email_fld, msg_fld FROM contactform_entries";
$result = $conn->query($sql2);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name_fld"]. " " . $row["email_fld"]. " " . $row["msg_fld"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
I ended up using .ajax instead of .post. I also changed my filename to index.php. I can't find the website where I got my code from, but here it is:
<!DOCTYPE html>
<html>
<head>
<title>Insert data in MySQL database using Ajax</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div style="margin: auto;width: 60%;">
<div class="alert alert-success alert-dismissible" id="success" style="display:none;">
×
</div>
<form id="fupForm" name="form1" method="post">
<div class="form-group">
<label for="email">Name:</label>
<input type="text" class="form-control" id="name" placeholder="Name" name="name">
</div>
<div class="form-group">
<label for="pwd">Email:</label>
<input type="email" class="form-control" id="email" placeholder="Email" name="email">
</div>
<div class="form-group">
<label for="pwd">Phone:</label>
<input type="text" class="form-control" id="phone" placeholder="Phone" name="phone">
</div>
<div class="form-group" >
<label for="pwd">City:</label>
<select name="city" id="city" class="form-control">
<option value="">Select</option>
<option value="Delhi">Delhi</option>
<option value="Mumbai">Mumbai</option>
<option value="Pune">Pune</option>
</select>
</div>
<input type="button" name="save" class="btn btn-primary" value="Save to database" id="butsave">
</form>
</div>
<p id="target">
</p>
<script>
$(document).ready(function() {
$('#butsave').on('click', function() {
var name = $('#name').val();
var email = $('#email').val();
var phone = $('#phone').val();
var city = $('#city').val();
if(name!="" && email!="" && phone!="" && city!=""){
$.ajax({
url: "save.php",
type: "POST",
data: {
name: name,
email: email,
phone: phone,
city: city
},
cache: false,
success: function(dataResult){
var dataResult = JSON.parse(dataResult);
if(dataResult.statusCode==200){
$("#butsave").removeAttr("disabled");
$('#fupForm').find('input:text').val('');
$("#success").show();
$('#success').html('Data added successfully !');
$('#target').load('show.php');
}
else if(dataResult.statusCode==201){
alert("Error occured !");
}
}
});
}
else{
alert('Please fill all the fields !');
}
});
});
</script>
</body>
</html>
Here's save.php. It's the code that inserts data into the database:
<?php
include 'database.php';
$name=$_POST['name'];
$email=$_POST['email'];
$phone=$_POST['phone'];
$city=$_POST['city'];
$sql = $con->prepare("INSERT INTO `crud`( `name`, `email`, `phone`, `city`) VALUES (?,?,?,?)");
$sql->bind_param("ssss", $name, $email, $phone, $city);
$rc = $sql->execute();
if (true===$rc) {
echo json_encode(array("statusCode"=>200));
}
else {
echo json_encode(array("statusCode"=>201));
}
//connection closed.
$sql->close();
$con->close();
?>
Here is show.php:
<?php
include 'database.php';
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
$query = "SELECT name, email, phone, city FROM crud";
$result = $con->query($query);
if ($result->num_rows > 0) {
// output data of each row
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
echo $row["name"]. " " . $row["email"]. " " . $row["phone"]. " " . $row["city"]."<br>";
}
} else {
echo "0 results";
}
$result -> free_result();
$con->close();
?>
And here are the database connection details, database.php:
<?php
$servername = "localhost";
$username = "user";
$password = "secret";
$db="school";
$con = mysqli_connect($servername, $username, $password,$db);
?>
The code posted is entirely functional.

Have a Insert and a Edit button in the same form using PHP and SQL

I've been going at this for a couple of hours now (searching here and google) but nothing I find helped me to get this to work.
I'm trying to make one form and have a Insert INTO and UPDATE $table SET function in the same form, using buttons.
But whatever I try the Update doesn't copy the data from the form. INSERT INTO works. But when I try to edit the form, no data is copied.
HTML:
<form id="contact-form" method="post" action="cms_data.php" role="form">
<div class="col-sm-12">
<h2>id</h2>
<input name="id" type="text" placeholder="<?php echo $id;?>" value="1">
</div>
<div class="col-sm-12">
<h2>Omschrijving</h2>
<textarea name="omschrijving" type="text" style="height:220px;width:100%;resize:none;"><?php echo $omschrijving;?></textarea>
</div>
<div class="col-sm-12">
<h2>Datum</h2>
<input name="datum" type="text" value="<?php echo $datum;?>">
</div>
<div class="col-sm-12">
<h2>Tijd</h2>
<input name="tijd" type="text" value="<?php echo $tijd;?>">
</div>
<div class="col-sm-12">
<h2>Locatie</h2>
<input name="locatie" type="text" value="<?php echo $locatie;?>">
</div>
<div class="col-sm-12">
<h2>Dresscode</h2>
<input name="dresscode" type="text" value="<?php echo $dresscode;?>">
</div>
<div class="col-sm-12 text-right">
<input type="submit" class="btn btn-success btn-send" value="Versturen" id="sent" <?php // echo $_SESSION['disabled']; ?>>
Update
</div>
</form>
CMS_DATA.php
<?php session_start();?>
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
//echo '<div style="width:100%;background:green;color:#FFF;font-size:2rem;text-align:center;">Connected to '. $dbname. '</div>';
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$id = $_POST['id'];
$omschrijving = $_POST["omschrijving"];
$datum = $_POST["datum"];
$item = $_POST["tijd"];
$locatie = $_POST["locatie"];
$dresscode = $_POST["dresscode"];
$quote = iconv("UTF-8", "WINDOWS-1252//TRANSLIT");
$date = date('Y-m-d');
date_default_timezone_set("Europe/Amsterdam");
$time = date("h:i:sa");
$sql = "INSERT INTO $table (ID, Omschrijving, Datum, Tijd, Locatie, Dresscode )
VALUES ('" .$id."','" .$omschrijving."','".$datum."',' ".$item."','".$locatie."','".$dresscode."')";
if ($conn->query($sql) === TRUE) {
echo "";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
UPDATE-CMS.php
<?php session_start();?>
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
//echo '<div style="width:100%;background:green;color:#FFF;font-size:2rem;text-align:center;">Connected to '. $dbname. '</div>';
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$id = $_POST['id'];
$omschrijving = $_POST["omschrijving"];
$datum = $_POST["datum"];
$item = $_POST["tijd"];
$locatie = $_POST["locatie"];
$dresscode = $_POST["dresscode"];
$quote = iconv("UTF-8", "WINDOWS-1252//TRANSLIT");
$date = date('Y-m-d');
date_default_timezone_set("Europe/Amsterdam");
$time = date("h:i:sa");
$sql = "UPDATE $table SET
Omschrijving = '$omschrijving', Datum = '$datum', Tijd = '$item', Locatie = '$locatie', Dresscode = '$dresscode' WHERE ID = '1'";
if ($conn->query($sql) === TRUE) {
echo "Done";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Like I said, the INSERT INTO works fine. But no data (values) are copied when using the update. I just overrides ID 1 with empty rows... I hope someone can help me... thanks in advance.
You have defined action on your form action="cms_data.php", so your button that is responsible for submitting that form works correctly, but on the other hand you've defined another button (anchor tag), that only has href (hence points to another page), so if you click on it, you won't pass any arguments with it.
My suggestion here is, as I mentioned in comment below your question, to use two buttons, both with submit property, but then handle clicking on them via JavaScript.
When you capture submitment, you can dinamically change action on your form, so your data will be passed to desired script.
Handling multiple buttons in a form:
Process a Form Submit with Multiple Submit Buttons in Javascript
Manipulating form's action property:
How to use JavaScript to change the form action
Another suggestion would be that you use prepared statements in your query, so you wouldn't be vulnerable to SQL injections (from the comments section, I see you'll only be using this locally, but this is a good practice).
Using Mysqli prepared statements:
https://stackoverflow.com/a/24989090/5018750
Echo only prints value on the screen in your respective textbox and does not assign that value to your actual field.
Instead what you can do is start the session in the start of your contact form and store those fields in session variable.
When user selects UPDATE option he will get redirected to UPDATE-CMS.php page. In UPDATE-CMS.php you can retrieve your stored session variables and assign them to your actual variables. In this way you can carry forward your old as well as new values.
anchor just links the page it will not pass data
you are trying to have submit and update button in one form
solution:
in html5 button has formaction attribute .formaction specifies page data to be transferred .so that different button can have different action page
<form id="contact-form" method="post" action="cms_data.php" role="form">
<div class="col-sm-12">
<h2>id</h2>
<input name="id" type="text" placeholder="<?php echo $id;?>" value="1">
</div>
<div class="col-sm-12">
<h2>Omschrijving</h2>
<textarea name="omschrijving" type="text" style="height:220px;width:100%;resize:none;"><?php echo $omschrijving;?></textarea>
</div>
<div class="col-sm-12">
<h2>Datum</h2>
<input name="datum" type="text" value="<?php echo $datum;?>">
</div>
<div class="col-sm-12">
<h2>Tijd</h2>
<input name="tijd" type="text" value="<?php echo $tijd;?>">
</div>
<div class="col-sm-12">
<h2>Locatie</h2>
<input name="locatie" type="text" value="<?php echo $locatie;?>">
</div>
<div class="col-sm-12">
<h2>Dresscode</h2>
<input name="dresscode" type="text" value="<?php echo $dresscode;?>">
</div>
<div class="col-sm-12 text-right">
<buttin formaction="CMS-DATA.php" type="submit" class="btn btn-success btn-send" value="Versturen" id="sent" <?php // echo $_SESSION['disabled']; ?>>
<button formaction="UPDATE-CMS.php" >Update </button>
</div>
</form>

How do i send HTML input fields to my MySQLi database using PHP?

I am trying to send the data put into the input fields to my database and I cant seem to make it work out properly..
The ultimate goal is to put in the input fields into the database and show the inserted data in another window.
Here's my code
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
// create a variable
$naam=$_POST['namen'];
$plaats=$_POST['plaatsen'];
$land=$_POST['landen'];
//Execute the query
mysqli_query($conn,"INSERT INTO phptoets(Namen,Plaatsen,Landen)
VALUES('$naam','$plaats','$land')");
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="main.css">
<title>PHP Toets</title>
</head>
<body>
<div class="import_intel">
</div>
<form method="POST">
<div class="invulform">
<h2>Vul hier de gegevens in die naar de database moeten</h2>
<input type="text" name="naam" class="input_name" placeholder="Naam"><br>
<input type="text" name="plaats" class="input_plaats" placeholder="Plaats"><br>
<input type="text" name="land" class="input_land" placeholder="Land"><br>
<input type="submit" name="submit" class="submit_button" value="Verstuur">
</div>
</form>
<div class="overzichtform">
<h3>Data</h3>
</div>
</body>
</html>
Try this. It will help you. I've done few changes in your code.
- Add form to post the data on server
- Add database name in connection
- Add provincie field in form (because you are trying to get that in php)
- Use the same variable in query as declared at the time of connection
<?php
if (isset($_POST['submit'])) {
$servername = "localhost";
$username = "root";
$password = "";
$database = "DATABASE";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// create a variable
$namen=$_POST['naam'];
$plaatsen=$_POST['plaats'];
$landen=$_POST['land'];
$provincie=$_POST['provincie'];
//Execute the query
mysqli_query($conn, "INSERT INTO employees1(naam,plaats,land,provincie) VALUES('$namen','$plaatsen','$landen','$provincie')");
}
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="main.css">
<title>PHP Toets</title>
</head>
<body>
<div class="import_intel">
</div>
<form method="POST" action="">
<div class="invulform">
<h2>Vul hier de gegevens in die naar de database moeten</h2>
<input type="text" name="naam" class="input_name" placeholder="Naam"><br>
<input type="text" name="plaats" class="input_plaats" placeholder="Plaats"><br>
<input type="text" name="land" class="input_land" placeholder="Land"><br>
<input type="text" name="provience" class="input_provience" placeholder="Provience"><br>
<input type="button" name="submit" class="submit_button" value="Verstuur">
</div>
</form>
<div class="overzichtform">
<h3>Data</h3>
</div>
</body>
</html>
This is my solution:
You forgot to set database name and the names of your input fields where not equal to your $_POST names.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$database = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
// create a variable
$naam=$_POST['naam'];
$plaats=$_POST['plaats'];
$land=$_POST['land'];
//Execute the query
mysqli_query($conn,"INSERT INTO phptoets(namen,plaatsen,landen)
VALUES('$naam','$plaats','$land')");
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="main.css">
<title>PHP Toets</title>
</head>
<body>
<div class="import_intel">
</div>
<form method="post">
<div class="invulform">
<h2>Vul hier de gegevens in die naar de database moeten</h2>
<input type="text" name="naam" class="input_name" placeholder="Naam"><br>
<input type="text" name="plaats" class="input_plaats" placeholder="Plaats"><br>
<input type="text" name="land" class="input_land" placeholder="Land"><br>
<input type="submit" name="submit" class="submit_button" value="Verstuur">
</div>
</form>
<div class="overzichtform">
<h3>Data</h3>
</div>
</body>
</html>
<?php
// TESTS
$servername = "localhost";
$username = "root";
$password = "";
$db_name = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $db_name);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully <br>";
if(isset($_POST['submit']))
{
// create a variable
$a = (string)filter_input(INPUT_POST,'naam');
$b = (string)filter_input(INPUT_POST,'plaats');
$c = (string)filter_input(INPUT_POST,'land');
$d = (string)filter_input(INPUT_POST,'provincie');
echo("executing query <br>");
//Execute the query
if($a != null && $b != null && $c != null && $c != null)
{
$sql="INSERT INTO employees1 (naam,plaats,land,provincie) VALUES (?,?,?,?)";
echo("sql ".$sql. "<br>");
if($stmt = $conn->prepare($sql))
{
$stmt->bind_param("ssss",$a,$b,$c,$d);
$stmt->execute();
$stmt->close();
}
}
$sql = "SELECT naam, plaats, land, provincie FROM employees1";
if ($stmt = $conn->prepare($sql))
{
$stmt->execute();
$stmt->bind_result($naam,$plaats,$land,$provincie);
while ($stmt->fetch())
{
printf("naam : %s, plaats: %s, land: %s, provincie: %s <br>",$naam,$plaats,$land,$provincie);
}
$stmt->close();
}
}
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="main.css">
<title>PHP Toets</title>
</head>
<body>
<div class="import_intel">
</div>
<div class="invulform">
<h2>Vul hier de gegevens in die naar de database moeten</h2>
<form class="my_form" target="_self" enctype="multipart/form-data" method="post">
<input type="text" name="naam" class="input_name" placeholder="Naam"><br>
<input type="text" name="plaats" class="input_plaats" placeholder="Plaats"><br>
<input type="text" name="land" class="input_land" placeholder="Land"><br>
<input type="text" name="provincie" class="input_land" placeholder="Provincie"><br>
<input type="submit" name="submit" class="submit_button" value="Verstuur">
</form>
</div>
<div class="overzichtform">
<h3>Data</h3>
</div>
</body>
</html>
I will just name few things that I changed in your code, not mentioning syntax errors
you dont specify db_name in your sql connection
you dont use prepared statements nor any kind of input filtering
(note : my input filtering is very basic, read more about how to
filter inputs)
to address html form you need to create one and have submit input
type inside

PHP connected to (MySQL) database - does not input data

I'm using Cloud9 to create a website. For whatever reason, the data taken from a HTML page will not get inserted into the Database.
I have tested to see if the Database is connected and it is. I would like to be able to get the data to be inserted into the Database.
The HTML code and PHP code is:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Record Form
</title>
</head>
<body>
<form action="../php/keithphp/address_submit.php" method="post">
<p>
<label for="address_street">Street</label>
<input type="text" name="address_street" id="address_street">
</p>
<p>
<label for="address_street2">Street 2</label>
<input type="text" name="address_street2" id="address_street2">
</p>
<p>
<label for="address_city">City</label>
<input type="text" name="address_city" id="address_city">
</p>
<p>
<label for="address_county">County</label>
<input type="text" name="address_county" id="address_county">
</p>
<p>
<label for="eircode">Eircode</label>
<input type="text" name="eircode" id="eircode">
</p>
<!-- <p>
<label for="address_geo_latitude">Latitude</label>
<input type="float" name="address_geo_latitude" id="address_geo_latitude">
</p>
<p>
<label for="address_geo_longtitude">Longitude</label>
<input type="float" name="address_geo_longtitude" id="address_geo_longtitude">
</p> -->
<input type="submit" value="Submit">
</form>
</body>
</html>
*****************
<?php
$servername = getenv('IP');
$username = getenv('C9_USER');
$password = "";
$database = "c9";
$dbport = 3306;
// Create connection
$db = new mysqli($servername, $username, $password, $database, $dbport);
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
/*$address_id = $_POST['address_id'];*/
$address_street = $_POST['address_street'];
$address_street2 = $_POST['address_street2'];
$address_city = $_POST['address_city'];
$address_county = $_POST['address_county'];
$address_eircode = $_POST['address_eircode'];
/*$address_geo_latitude = $_POST['address_geo_latitude'];
$address_geo_longtitude = $_POST['address_geo_longtitude'];*/
$sql = "INSERT INTO Address(address_id, address_street, address_street2, address_city, address_county, address_eircode, address_geo_latitude, address_geo_longtitude) VALUES ('$address_id', '$address_street', '$address_street2', '$address_city', '$address_county', '$address_eircode', '$address_geo_latitude', '$address_geo_longtitude')";
$success = $db->query($sql);
if (!$sucess){
die("Could not enter data: ".$db->error);
}
echo "Thank you. Address submitted!"
/*my$db->close();*/
?>
And the result after typing in test data is (no error message after text), I get;
Could not enter data:

PHP form, converting input field into a drop down list

The below code is a simple form that is sending the data that is inputted to my local database.
<html>
<head>
<title>!!!!!!!!!!!!!!</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="main">
<h1>Insert data into database using mysqli</h1>
<div id="login">
<h2>Student's Form</h2>
<hr/>
<form action="" method="post">
<label>Student Name :</label>
<input type="text" name="stu_name" id="name" required="required" placeholder="Please Enter Name"/><br /><br />
<label>Student Email :</label>
<input type="email" name="stu_email" id="email" required="required" placeholder="john123#gmail.com"/><br/><br />
<label>Student City :</label>
<input type="text" name="stu_city" id="school" required="required" placeholder="Please Enter Your City"/><br/><br />
<input type="submit" value=" Submit " name="submit"/><br />
</form>
</div>
<!-- Right side div -->
</div>
<?php
if(isset($_POST["submit"])){
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "Student";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO students (student_name, student_email, student_school)
VALUES ('".$_POST["stu_name"]."','".$_POST["stu_email"]."','".$_POST["stu_city"]."')";
if ($conn->query($sql) === TRUE) {
echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
} else {
echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" . $conn->error."');</script>";
}
$conn->close();
}
?>
</body>
</html>
The issue that I am finding is that I am trying to change the Student City input field into a drop down where the values is retrieve from the database and put into a drop down list for a new user to select.
Could someone advise on what needs to be done please.
i am trying to use the below code and send the below list to my database.
<option value="US">United States</option>
<option value="UK">United Kingdom</option>
<option value="France">France</option>
<option value="Mexico">Mexico</option>
but i am finding it hard to send the these values to the database with my above code as well as where to place this code.
As a rough example of how you could build the dropdown menu using data from your db this should give you the general idea perhaps.
/* store formatted menu options in temp array */
$html=array();
/* query db to find schools/cities */
$sql='select distinct `student_school` from `students` order by `student_school`';
$res=$mysqli_query( $conn, $sql );
/* process recordset and store options */
if( $res ){
while( $rs=mysqli_fetch_object( $res ) ){
$html[]="<option value='{$rs->student_school}'>{$rs->student_school}";
}
}
/* render menu */
echo "<select name='stu_city'>", implode( PHP_EOL, $html ), "</select>";
You need to refactor your code by moving the if (isset($_POST)) above the html:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "Student";
// Create connection
$conn = new mysqli ( $servername, $username, $password, $dbname );
// Check connection
if ($conn->connect_error) {
die ( "Connection failed: " . $conn->connect_error );
}
$sql = "SELECT city_name FROM cities" ;
if ($conn->query ( $sql ) === TRUE) {
$cities = ... // build the cities from the query result
} else {
$cities = '<option value="none">No cities found</option>' ;
}
if (isset ( $_POST ["submit"] )) {
$sql = "INSERT INTO students (student_name, student_email, student_school)
VALUES ('" . $_POST ["stu_name"] . "','" . $_POST ["stu_email"] . "','" . $_POST ["stu_city"] . "')";
if ($conn->query ( $sql ) === TRUE) {
echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
} else {
echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" . $conn->error . "');</script>";
}
$conn->close ();
}
?>
<html>
<head>
<title>!!!!!!!!!!!!!!</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="main">
<h1>Insert data into database using mysqli</h1>
<div id="login">
<h2>Student's Form</h2>
<hr />
<form action="" method="post">
<label>Student Name :</label> <input type="text" name="stu_name"
id="name" required="required" placeholder="Please Enter Name" /><br />
<br /> <label>Student Email :</label> <input type="email"
name="stu_email" id="email" required="required"
placeholder="john123#gmail.com" /><br />
<br /> <label>Student City :</label> <select name="stu_city" multiple><?php echo $cities; ?>
</select>><br />
<br /> <input type="submit" value=" Submit " name="submit" /><br />
</form>
</div>
<!-- Right side div -->
</div>
</body>
</html>
Use the Select tag: Lets say you hav a column in your database with Student City, like this, lets say the database field is called city
City 1
City 2
City 3
Step 1: Query the database and fetch all the Cities
$sql = "SELECT city FROM table_name";
$result = $conn->query($sql);
Then you come to your dropdown:
<select name="stu_city" id="..." required>
<?php
while($cities = $conn->fetch_array($result){
extract($cities);
echo "<option value='...'>$city</option>";
}
?>
</select>
You need to refactor your code by moving the if (isset($_POST)) above the html:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "Student";
// Create connection
$conn = new mysqli ( $servername, $username, $password, $dbname );
// Check connection
if ($conn->connect_error) {
die ( "Connection failed: " . $conn->connect_error );
}
$sql = "SELECT city_name FROM cities" ;
$result = $conn->query ( $sql );
if (isset ( $_POST ["submit"] )) {
$sql = "INSERT INTO students (student_name, student_email, student_school)
VALUES ('" . $_POST ["stu_name"] . "','" . $_POST ["stu_email"] . "','" . $_POST ["stu_city"] . "')";
if ($conn->query ( $sql ) === TRUE) {
echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
} else {
echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" . $conn->error . "');</script>";
}
$conn->close ();
}
?>
<html>
<head>
<title>!!!!!!!!!!!!!!</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="main">
<h1>Insert data into database using mysqli</h1>
<div id="login">
<h2>Student's Form</h2>
<hr />
<form action="" method="post">
<label>Student Name :</label> <input type="text" name="stu_name"
id="name" required="required" placeholder="Please Enter Name" /><br />
<br /> <label>Student Email :</label> <input type="email"
name="stu_email" id="email" required="required"
placeholder="john123#gmail.com" /><br />
<br /> <label>Student City :</label> <select name="stu_city" multiple>
<?php
if ($result == TRUE) {
while($cities = $conn->fetch_array($result)){
extract($cities);
echo "<option value=''>$city_name</option>";
}
}
else {
echo "<option value='none'>No cities found</option>";
}
?>
</select>><br />
<br /> <input type="submit" value=" Submit " name="submit" /><br />
</form>
</div>
<!-- Right side div -->
</div>
</body>
</html>

Categories