How to save to database MySQL/MariaDB using PHP-JQuery? - php

I want to create a simple website to show form input fields based on select values. Here is my codes:
index.php
<?php
include('conn.php');
?>
<!-- For server type field -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script>
// For physical type -------------------------------------
$(document).ready(function () {
toggleFieldsPhys(); // call this first so we start out with the correct visibility depending on the selected form values
// this will call our toggleFields function every time the selection value of our other field changes
$("#type").change(function () {
toggleFieldsPhys();
});
});
// this toggles the visibility of other server
function toggleFieldsPhys() {
if ($("#type").val() === "physical")
$("#physical").show();
else
$("#physical").hide();
}
// -------------------------------------------------------
// For cloud type ----------------------------------------
$(document).ready(function () {
toggleFieldsCloud(); // call this first so we start out with the correct visibility depending on the selected form values
// this will call our toggleFields function every time the selection value of our other field changes
$("#type").change(function () {
toggleFieldsCloud();
});
});
function toggleFieldsCloud() {
if ($("#type").val() === "vps")
$("#vps").show();
else
$("#vps").hide();
}
// -------------------------------------------------------
</script>
<body>
<center>
<h1>Add Server</h1>
<center>
<form method="POST" action="add_process.php" enctype="multipart/form-data" >
<section class="base">
<div>
<label>Server Type</label>
<td>
<select id="type" name="type" required>
<option value="">Choose Type</option>
<option value="physical">Physical</option>
<option value="vps">VPS Hosting</option>
</select>
</td>
</div>
<div class="input-group" id="physical">
<fieldset>
<p>Server Name:
<input type="text" name="servername" required />
</p>
<p>Manufactur:
<input type="text" name="brand" required />
</p>
<p>Type:
<input type="text" name="product" required />
</p>
<p>Serial Number:
<input type="text" name="sn" required />
</p>
</fieldset>
</div>
<br>
<div class="input-group" id="vps">
<fieldset>
<p>Hosting Name
<input type="text" name="hosting" required />
</p>
</fieldset>
</div>
<br>
<div>
<label>Processor</label>
<input type="text" name="processor" autofocus="" required="" />
</div>
<br>
<br>
<div>
<button type="submit">Save</button>
</div>
</section>
</form>
</body>
</html>
add_process.php
<?php
include 'conn.php';
$type = $_POST['type'];
$number = $_POST['number'];
$servername = $_POST['servername'];
$brand = $_POST['brand'];
$product = $_POST['product'];
$sn = $_POST['sn'];
$hosting = $_POST['hosting'];
$processor = $_POST['processor'];
$query = "INSERT INTO try (type, number, servername, brand, product, sn, hosting, processor ) VALUES ('$type', '$number', '$servername', '$brand', '$product', '$sn', '$hosting', '$processor')";
$result = mysqli_query($conn, $query);
if(!$result){
die ("Query Failed: ".mysqli_errno($conn).
" - ".mysqli_error($conn));
} else {
echo "<script>alert('Data Saved');window.location='index.php';</script>";
}
The problem is when I choose Physical type, the data is saved to the database. But when I choose VPS Hosting, I cannot Save to the database because the save button can't be clicked normally.
What should I do if I click VPS Hosting and I fill the form, the data save to the database?

Related

Trying to submit the checked data into database

****I'm trying to get submiitted value in database.After getting the value from a particular table i want to store the checked value into another table with the same columns.How to add the values that come from database while submitting after the checked valueHere's my code****
form.php
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<title></title>
</head>
<body>
<form action="insert.php" method="post">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" name="name" id="name">
</div>
<div class="form-group">
<label for="text">Sec</label>
<input type="text" class="form-control" name="sec" id="sec">
</div>
<button type="submit" name="submit" class="btn btn-default">Submit</button>
<button type="submit" name="getdata" class="btn btn-default">Get</button>
</form>
</body>
</html>
insert.php
<?php
$con=mysqli_connect("localhost", "root", "","input");
// inserting data
if(isset($_POST['submit'])){
$name=$_POST['name'];
$sec=$_POST['sec'];
if($name !=''||$sec !=''){
$query = mysqli_query($con,"insert input_form(Name,Sec) values ('$name', '$sec')");
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
}
else{
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
}
}
else if(isset($_POST['getdata'])){
$query1 = mysqli_query($con,"select * from input_form");
while ($row1 = mysqli_fetch_array($query1)) {
?>
<ul class="form-get">
<input type="checkbox" name="chk[]" ><li><?php echo $row1['Name'];?><?php echo $row1['Sec']; ?> </li>
</ul>
<?php
}
?>
<button name="present">Submit</button>
<?php
}
?>
<?php
if(isset($_POST['present'])){
$checkbox=$_POST['chk'];
for($i=0;$i<sizeof($checkbox);$i++){
$query2=mysqli_query($con,"insert into present(Name,Sec) values ('".$checkbox[i]."')");
}
}
?>
<?php
mysqli_close($con);
?>
you should set a status for checked value to "1" and "0" to unchecked to store into database.Make a condition that if the variable is checked and have status to "1" then it will be submitted to database otherwise not.
here you can make a condition.
First of all you have missing a tag for check box in the form
<label for="checkbox">check</label>
<input type="checkbox" class="form-control" name="chk" id="chk">
here you can post the checkbox status
$chk=$_POST['chk'];
////////////create a column for check box also to make it easy./////
if(isset($_POST['present'])){
$checkbox=$_POST['chk'];
for($i=0;$i<sizeof($checkbox);$i++){
if($checkbox===1){
$query2=mysqli_query($con,"insert into present(Name,Sec,checkbox) values
('".$checkbox[i]."')");
}
}
}
hope it may help you.

Keep the form open when sending data to the table

I have this code with multiple forms within the same page:
test1 page:
<select id="mudar_produto">
<option value="#produto_1">Novo Produto Higiene</option>
<option value="#produto_2">Entrada de Produtos Higiene</option>
<option value="#produto_3">Novo Produto Nutricia</option>
</select>
<section class="hide-section" id="produto_1">
<form id="form3" action="./teste2" method="POST" onsubmit="return form_validation()">
<fieldset>
<h1>
<legend>
<center>
<strong>Produtos de Higiene</strong>
</center>
</h1><br>
<fieldset class="grupo">
<div class="campo">
<strong><label for="Nome do Produto">Nome do Produto</label></strong>
<input type="text" id="DescricaoProd" name="DescricaoProd" required="" style="width:350px">
</div>
<div class="campo">
<strong><label for="Unidade">Unidade</label></strong>
<input type="text" id="DescricaoUnid" name="DescricaoUnid" style="width:160px" required="" size="120">
</div>
</fieldset>
<button type="submit" name="submit" class="botao submit">Registo</button>
</form>
</section>
<section class="hide-section" id="produto_2">
<form name="form4" action="./teste2" method="POST" onsubmit="return form_validation()">
<fieldset>
<h1>
<legend>
<center>
<strong>Entrada de Produtos de Higiene</strong>
</center>
</h1><br>
<fieldset class="grupo">
<div class="campo">
<strong><label for="Data Entrada">Data Entrada</label></strong>
<input id="DataEntrada" type="date" name="DataEntrada" required="" style="width:180px" value="<?php echo date("Y-m-d");?>">
</div>
</fieldset>
<fieldset class="grupo">
<div class="campo">
<strong><label for="Produto">Produto</label></strong>
<select id="first_dd" name="Produto" style="width:250px" required>
<option></option>
<?php
$sql = "SELECT * FROM centrodb.ProdHigieneteste WHERE Ativo = 1 ORDER BY DescricaoProd ASC";
$qr = mysqli_query($conn, $sql);
while($ln = mysqli_fetch_assoc($qr)){
echo '<option value="'.$ln['IDProd'].'"> '.$ln['DescricaoProd'].'</option>';
$valencia[$ln['IDProd']]=array('DescricaoUnid'=>$ln['DescricaoUnid'],'DescricaoUnid'=>$ln['DescricaoUnid']);
}
?>
</select>
</div>
<div class="campo">
<strong><label for="Unidade">Unidade</label></strong>
<select id="second_dd" name="Unid" style="width:150px" required>
<option></option>
<?php
foreach ($valencia as $key => $value) {
echo '<option data-id="'.$key.'" value="'.$value['DescricaoUnid'].'">'.$value['DescricaoUnid'].'</option>';
}
?>
</select><br>
</div>
</fieldset>
<fieldset class="grupo">
<div class="campo">
<strong><label for="Quantidade">Quantidade</label></strong>
<input type="text" id="Quantidade" name="Quantidade" style="width:80px" required="" size="40">
</div>
<div class="campo">
<strong><label for="Preço">Preço</label></strong>
<input type="text" id="Preco" name="Preco" style="width:100px" value="0.00">
</div>
</fieldset>
<button type="submit" name="submit1" class="botao submit">Registo</button>
</form>
</section>
<section class="hide-section" id="produto_3">
<form id="form3" name="form3" action="./teste2" method="POST" onsubmit="return form_validation()" >
<fieldset>
<h1>
<legend>
<center>
<strong>Produtos de Nutricia</strong>
</center>
</h1><br>
<fieldset class="grupo">
<div class="campo">
<strong><label for="Nome do Produto">Nome do Produto</label></strong>
<input type="text" id="ProdNutricia" name="ProdNutricia" style="width:350px" required="" size="120" />
</div>
</fieldset>
<button type="submit" name="submit2" class="botao submit">Registo</button>
</form>
</section>
In the page teste2 I make the insertion of the data in the table of the database:
<script language="javascript" type="text/javascript">
document.location = "teste1";
</script>
<?php
if(isset($_POST['submit'])){
$name = $_POST['DescricaoProd'];
$unid = $_POST['DescricaoUnid'];
$sql = "INSERT INTO ProdHigieneteste (DescricaoProd,DescricaoUnid)
VALUES ('$name','$unid')";
if ($conn->query($sql) === TRUE);
$sql1 = "INSERT INTO StockHigieneteste (DescricaoProd,DescricaoUnid)
VALUES ('$name','$unid')";
if ($conn->query($sql1) === TRUE);
//Count total number of rows
$rowCount = $query->num_rows;
header("Location: teste1");
$conn->close();
}
?>
<?php
if(isset($_POST['submit1'])){
$data = $_POST['DataEntrada'];
$produto = $_POST['Produto'];
$unidade = $_POST['Unid'];
$quantidade = $_POST['Quantidade'];
$preco = $_POST['Preco'];
$sql = "INSERT INTO regEntradahigieneteste (DataEntrada,Produto,Unid,Quantidade,Preco)
VALUES ('$data','$produto','$unidade','$quantidade','$preco')";
if ($conn->query($sql) === TRUE);
$sql1 = "UPDATE StockHigieneteste SET Quantidade = Quantidade +" . $quantidade . " WHERE StockHigieneteste.IDProd =" . $produto;
if ($conn->query($sql1) === TRUE);
//Count total number of rows
$rowCount = $query->num_rows;
header("Location: teste1");
$conn->close();
}
?>
<?php
if(isset($_POST['submit2'])){
$name = $_POST['ProdNutricia'];
$sql = "INSERT INTO ProdNutriciateste (ProdNutricia)
VALUES ('$name')";
if ($conn->query($sql) === TRUE);
$sql1 = "INSERT INTO StockNutriciateste (ProdNutricia)
VALUES ('$name')";
if ($conn->query($sql1) === TRUE);
//Count total number of rows
$rowCount = $query->num_rows;
header("Location: teste1");
$conn->close();
}
?>
Everything is working correctly with the insertion of data in the table, but when I do the insertion and does the header ("Location: teste1"); closes the form I was filling out and I want to keep it open, since I may have to insert several types of products on the same form.
Some explanation to start with:
I have cleaned up your HTML markup. You may have gotten the look you desired, but the markup is badly broken. A good editor will help you with making a well-formed document that validates.
I've used Bootstrap for styling. Foundation is another good choice.
JQuery is used as the basis for Javascript event monitoring and AJAX
This is not copy and paste code. It's untested; it's purpose is to point you in the right direction.
The code is commented to help you understand what it's doing.
Since this is how SO is showing the code, we start off with the javascript and the HTML:
// this delays execution until after the page has loaded
$( document ).ready(function() {
// this monitors the button, id=submit-form-1, for a click event
// and then runs the function, submitForm1()
$('#submit-form-1').on('click', function() {
submitForm('#form1');
});
// could be repeated for another form...
$('#submit-form-2').on('click', function() {
submitForm('#form2');
});
});
// this function does an AJAX call to "insert.php".
// it expects a reply in JSON.
function submitForm(whichForm) {
var datastring = $(whichForm).serialize();
// see what you're sending:
alert('You would be sending: ' + datastring);
$.ajax({
type: "POST",
url: "insert.php",
data: datastring,
dataType: "json",
success: function(data) {
if(data.status=='success') {
alert('successfully uploaded');
} else {
alert('failed to insert');
}
},
error: function() {
alert("This example can't actually connect to the PHP script, so this error appears.");
}
});
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="produto_1">
<!--
note that the form is identified with id="form1".
"id" has to be unique. Nothing else can have id="form1".
There are no action nor method attributes,
since AJAX is submitting the form contents.
-->
<form class="form-horizontal" id="form1">
<!--
field named "action" will be used in PHP script
-->
<input type="hidden" name="action" value="insert_form_1" />
<!-- use CSS for styling, not <center>, <strong>, etc. -->
<h1 class="text-center">Produtos de Higiene</h1>
<div class="form-group">
<label for="DescricaoProd" class="col-sm-2 control-label">Nome do Produto</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="DescricaoProd" name="DescricaoProd" required />
</div>
</div>
<div class="form-group">
<label for="DescricaoUnid" class="col-sm-2 control-label">Unidade</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="DescricaoUnid" name="DescricaoUnid" required />
</div>
</div>
<div class="form-group">
<div class="col-sm-2">
<!--
button type is button, not submit.
Otherwise the form will try to submit.
We want the javascript to submit, not the form.
-->
<button type="button" id="submit-form-1" class="btn btn-success">Registo</button>
</div>
</div>
</form>
</section>
<!-- set up another form in the same way... -->
<form id="form2">
<input type="hidden" name="action" value="insert_form_2" />
...
<button type="button" id="submit-form-2">submit form 2</button>
</form>
The above markup and javascript should make an AJAX POST request to insert.php, and listen for a reply.
insert.php
<?php
/**
* note: It is a good practice to NEVER have anything before the <?php tag.
*
* Always try to separate logic from presentation. This is why you should
* start with PHP on the top, and never do any output until you are done
* with processing. Better yet, have separate files for logic and presentation
*
*/
// if $_POST doesn't have ['action'] key, stop the script. Every request will have
// an action.
if(!array_key_exists('action', $_POST)) {
die("Sorry, I don't know what I'm supposed to do.");
}
// database initialization could (should) go on another page so it can be reused!
// set up PDO connection
// this section credit to https://phpdelusions.net/pdo
// use your credentials here...
$host = '127.0.0.1';
$db = 'your_db_name';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
// helpful initializations, such as default fetch is associative array
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
// instantiate database
$pdo = new PDO($dsn, $user, $pass, $opt);
// end database initialization
// whenever you have to do something over again, break it out into a function
// this function prevents warnings if the variable is not present in $_POST
function get_post($var_name) {
$out = '';
if(array_key_exists($var_name,$_POST)) {
$out = $_POST[$var_name];
}
return $out;
}
// assign variables
$action = get_post('action');
$name = get_post('DescricaoProd');
$unid = get_post('DescricaoUnid');
// All output of this script is JSON, so set the header to make it so.
// There can be NO output before this!
// Not even a blank line before the <?php start tag.
header('Content-Type: application/json');
// take action based on value of "action".
if($action=='insert_form_1') {
$error = false;
$output = array('message' => 'success');
// Use placeholders, never (NEVER NEVER NEVER) php variables!
$sql = "INSERT INTO ProdHigieneteste (DescricaoProd,DescricaoUnid) VALUES (?,?)";
$pdo->prepare($query);
$result = $pdo->execute([$name, $unid]); // don't miss the [] which is a shortcut for array()
if(!$result) { $error = true; }
$sql1 = "INSERT INTO StockHigieneteste (DescricaoProd,DescricaoUnid) VALUES (?,?)";
$pdo->prepare($query);
$result = $pdo->execute([$name, $unid]); // don't miss the [] which is a shortcut for array()
if(!$result) { $error = true; }
// note, I just repeated myself, so this probably should be refactored...
// send a message back to the calling AJAX:
if($error) {
$output = array('status' => 'failed');
} else {
$output = array('status' => 'success');
}
print json_encode($output);
die; // nothing more to do
}
// you could have additional actions to perform in the same script.
// or, you could use different files...
if($action=='insert_form_2') {
// do insert for form 2
}
// etc.

PHP - multiple forms, get values from both upon submit?

I am a little stuck at the moment and could use some help please.
I have a calendar which is being used by multiple departments to enter their schedule in. Each user is asked to complete 1x select and 2x input fields which are divided into FORM 1 and FORM 2
FORM 1:
department code (onclick submit event)
FORM 2:
name
date
submit button
After the user has selected his/her department code, the calendar will refresh and fetch the entries for this specific department only (meaning it will filter all records for the department code). After that, the user has to enter his username and select a date, followed by pressing the submit button (form 2).
Now, the problem is that in order for FORM 2 to submit correctly, I need to know the department code from Form 1. Additionally, I am having troubles preventing the calendar from refreshing (Form 1) when pressing the submit button for Form 2.
In short, how can I clearly distinguish the ($_POST) between form 1 and form 2, while accessing both form's data?
PHP
<?php
// SHOULD BE EXECUTED AFTER THE SUBMIT BUTTON WAS CLICKED
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['type']) && ($_POST['type']=='new_entry')) {
// include connection details
include '../../plugins/MySQL/connect_db.php';
// Open a new connection to the MySQL server
$con = new mysqli($dbhost,$dbuser,$dbpass,$dbname);
// Output any connection error
if ($con->connect_error) {
die('Error : ('. $con->connect_errno .') '. $con->connect_error);
}
// define variables
$table = 'calendar';
$type = mysqli_real_escape_string($con,$_POST['type']);
$holidex = mysqli_real_escape_string($con,$_POST['holidex']);
if($type == 'new_entry')
{
// define variables and query
$mod_property = mysqli_real_escape_string($con,$_POST['holidex']);
$mod_name = mysqli_real_escape_string($con,$_POST['mod_name']);
$mod_date = date('Y-m-d',strtotime($_POST['mod_date']));
$sql = "INSERT INTO calendar (`title`, `startdate`, `enddate`, `allDay`, `color`, `holidex`) VALUES ('$mod_name','$mod_date','$mod_date','true','','$mod_property')";
print($sql);
$result = $con->query($sql) or die('<p>Could not submit new MOD record into database: ' . MYSQLI_ERROR() . '</p>');
$result->free();
}
$con->close();
}
?>
<form name="form1" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<!-- <form name="mod_form" action="../../plugins/MySQL/ajax_action.php?type=new_entry" method="POST"> -->
<!-- Property -->
<div class="col-md-4">
<label>Property</label>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-server"></i></span>
<select name="holidex" id="holidex" class="form-control select2" style="width: 100%;" data-placeholder="Select your property" onchange="this.form.submit();" method="POST" <?php if($_SESSION['Access']=='User') { echo "disabled"; } ?>>
// get all my departments and their respective codes
<option value="1">Dept. 1</option>
<option value="2">Dept. 2</option>
<option value="3">Dept. 3</option>
</select>
</div>
<!-- /btn-group -->
</div>
<!-- /.property -->
</form>
<form name="form2" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<!-- MOD Name -->
<div class="col-md-4">
<label>MOD Name</label>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-user"></i></span>
<select name="mod_name" id="mod_name" class="form-control select2" style="width: 100%;" data-placeholder="Select a name">
<option value=""></option>
<option value="1">User1</option>
<option value="2">User2</option>
<option value="3">User3</option>
</select>
</div>
<!-- /.input-group -->
</div>
<!-- /.mod name -->
<!-- MOD Date -->
<div class="col-md-3">
<label>MOD Date</label>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-server"></i></span>
<input type="date" class="form-control" name="daterangepicker" id="daterangepicker" />
<!-- <input type="date" id="mod_date" name="mod_date" class="form-control" style="width: 100%;"> -->
</div>
</div>
<!-- /.mod date -->
// hidden input field to determine the type and help differentiate the $_POST submissions
<input type="hidden" class="form-control" name="type" id="type" value="new_entry"/>
<!-- Submit button -->
<div class="col-md-1 text-center">
<label> </label>
<button type="submit" name="btnSubmit" class="btn btn-primary btn-block" onclick="this.disabled=true; this.value = 'Wait...'; this.form.submit(); return true;">Submit</button>
</div>
<!-- /.submit button -->
</form>
<!-- /.form 2 -->
Following SiteThief's suggestion, I am skipping the <form> approach altogether and am submitting the results via AJAX to my php handler file. Works like a charm without the pesky form submission problems.
JS
<script>
// SAVE NEW DEPARTMENT RECORD - SAVE BUTTON
$("#SubmitButton").click(function() {
// check that input fields are not empty
if($("#holidex").val()!="" && $("#mod_name").val()!="" && $("#mod_date").val()!="") {
$.ajax({
url: "../../plugins/MySQL/ajax_action.php",
type: "POST",
async: true,
data: { action:"mod_calendar",type:"new_entry",holidex:$("#holidex").val(),mod_name:$("#mod_name").val(),mod_date:$("#mod_date").val()},
dataType: "html",
success: function(data) {
$('#mod_output').html(data);
drawVisualization();
},
});
} else {
//notify the user they need to enter data
alert("Please choose a hotel, staff name and MOD date from the list.");
return;
}
// close modal and refresh page
setTimeout(function(){location.reload()}, 1000);
return;
});
</script>

stack overflow call stack #timememoryfunctionlocation 10.0000143728

Hi this is my second time posting on this site. I looked # the other article pertaining to this message and am unable to figure this out.
So i'm trying to dynamically populate the content of a drop down box with data store in the DB.
I'm getting the following error message displayed in the drop down for each record in the DB (3times)
Any help would be appreciated.
Thanks
<!DOCTYPE html>
<?php
$con=mysqli_connect("localhost","root","","project1");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// this block would be at the top of your file above the html
$query = "select * from countries";
$country_results = mysqli_query($con,$query);
$number_of_returns = mysqli_num_rows($country_results);
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="site.css">
</head>
<body>
<h1>Insert Site into DB</h1>
<h2 class="button"><a href=/index.html>Home</a></h2>
<h2 class="button"><a href=/insert.html>add site</a></h2>
<h2 class="button"><a href=/delete.html>delete site</a></h2>
<h2 class="button"><a href=/search.html>search site</a></h2>
<form class="insert" action="insert.php" method="post">
<p>Site Info</p>
Site code:<input type="text" name="site_code"><br>
Site name: <input type="text" name="site_name"><br>
Address: <input type="text" name="site_address"><br>
City:<br>
Postal code: <input type="text" name="site_postalcode"><br>
Province: <select name="province"></select><br>
Country: <select name=”country”>
<?php while (($row = mysqli_fetch_row($country_results)) != null){ ?>
<option value=”<?php echo $row[‘country’];?></option>
<?php } ?>
</select><br>
<p>Site Contact Info</p>
Site contact name: <input type="text" name="site_contact_name"><br>
Phone number 1: <input type="number" name="site_contact_number1"><br>
Phone number 2: <input type="number" name="site_contact_number2"><br>
Email address: <input type="email" name="site_contact_email"><br>
<input type="submit">
</form>
</body>
</html>
If you want to access the result as an associative array e.g. $row['country'] you have to use mysqli_fetch_assoc. By using mysqli_fetch_row you can access you results as $row[0]. Also, the are some odd quotes in your code which have to be replaced as well as some other errors in your html e.g. missing value attribute closing quotes in options.This will work:
<select name="country">
<?php while($row = mysqli_fetch_assoc($country_results)){ ?>
<option value="<?php echo $row['title'];?>"><?php echo $row['title'];?></option>
<?php } ?>
</select>

Undefined index when loading page

When the page loads i get the undefined index error message enumerated 7 times, I assume it's 1 message per variable.
When I click submit all the form data still get submitted to the DB.
Once I submit the form the Undefined Index error goes away! on page reload.
Weird
<!DOCTYPE html>
<?php
$con=mysqli_connect("localhost","root","","project1");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// check variables set
if (isset($_POST['submit']))
{
$site_code = $_POST['site_code'];
$site_name = $_POST['site_name'];
$site_address = $_POST['site_address'];
$site_city = $_POST['site_city'];
$site_postalcode = $_POST['site_postalcode'];
$province = $_POST['province'];
$country = $_POST['country'];
}
// Query from Countries table
$query_countries = "select * from countries";
$country_results = mysqli_query($con,$query_countries);
$number_of_returns_country = mysqli_num_rows($country_results);
// Query from Provinces Table
$query_provinces = "select * from provinces";
$provinces_results = mysqli_query($con,$query_provinces);
$number_of_returns_province = mysqli_num_rows($provinces_results);
//insert form values into sites table
$sql_site="INSERT INTO sites (site_code, site_name, site_address, site_city, site_postalcode, id_province, id_country)
VALUES
('$_POST[site_code]','$_POST[site_name]','$_POST[site_address]','$_POST[site_city]','$_POST[site_postalcode]',$_POST[province],$_POST[country])";
mysqli_query($con,$sql_site);
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="site.css">
</head>
<body>
<h1>Insert Site into DB</h1>
<h2 class="button"><a href=/index.html>Home</a></h2>
<h2 class="button"><a href=/insert.php>add site</a></h2>
<h2 class="button"><a href=/delete.html>delete site</a></h2>
<h2 class="button"><a href=/search.html>search site</a></h2>
<form class="insert" action="insert.php" method="post">
<h3>Site Info</h3>
Site code: <input type="text" name="site_code"><br>
Site name: <input type="text" name="site_name"><br>
Address: <input type="text" name="site_address"><br>
City: <input type="text" name="site_city"><br>
Postal code: <input type="text" name="site_postalcode"><br>
Province: <select name="province">
<?php while($row = mysqli_fetch_assoc($provinces_results)){ ?>
<option value="<?php echo $row['id'];?>"><?php echo $row['province'];?></option>
<?php } ?>
</select><br>
Country: <select name="country">
<?php while($row = mysqli_fetch_assoc($country_results)){ ?>
<option value="<?php echo $row['id'];?>"><?php echo $row['country'];?></option>
<?php } ?>
</select><br>
<h3>Site Contact Info</h3>
Site contact name: <input type="text" name="site_contact_name"><br>
Phone number 1: <input type="number" name="site_contact_number1"><br>
Phone number 2: <input type="number" name="site_contact_number2"><br>
Email address: <input type="email" name="site_contact_email"><br>
<input type="submit">
</form>
</body>
</html>
This happens because, when you load your page for the first time, data of the form isn't set. When you compile and send it, the error doesn't show up simply because now data is set.
You are getting the error, because there is no data in your $_POST variable. To fix it, you will have to add a name to your submit button:
<input type="submit" name="form_posted">
and enclose your PHP code into this if:
if(isset($_POST['form_posted'])) {
}
Alternatively, you can add this on top of your PHP, to exclude warnings:
error_reporting(E_ALL ^ E_WARNING);

Categories