After I fill up the PHP form, the data is not showing in mysql. What is wrong with my code and how can i fix it?
These are all my codes. Please help me I am still a beginner in php. I tried searching my error in other websites however it is not working.
This is the code for the form
index.php
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
</head>
<body>
<!-- C R E A T E D A T A -->
<form class="" action="createdatatry.php" method="post">
<h3>ENTER THE FOLLOWING SUPPLIER INFORMATION:</h3>
<input type="text" name="Supplier_Name" placeholder="Enter Supplier Name" required/>
<input type="text" name="Supplier_Contact" placeholder="Enter Contact No." required/>
<input type="text" name="Supplier_StreetNo" placeholder="Enter Street No." required/>
<input type="text" name="Supplier_Province" placeholder="Enter Province" required/>
<input type="text" name="Supplier_PostalCode" placeholder="Enter Postal Code" required/>
<input type="text" name="Supplier_Country" placeholder="Enter Country" required/>
<input type="submit" name="create" value="CREATE">
</form>
</body>
</html>
This is the code for the mysql connection
database.php
<?php
$host = 'localhost';
$user = 'root';
$password = '';
$database = 'sourcingdb';
$connection = mysqli_connect($host, $user, $password, $database);
if (mysqli_connect_error()) {
echo "Error Unable to connect to MySQL server <br>";
echo "Message: ".mysqli_connect_error()."<br>";
}
?>
This is the code in creating/ inserting data into mysql
createdatatry.php
<?php
require('./database.php');
if (isset($_POST['create'])) {
$Supplier_Name = $_POST['Supplier_Name'];
$Supplier_Contact = $_POST['Supplier_Contact'];
$Supplier_StreetNo = $_POST['Supplier_StreetNo'];
$Supplier_Prov = $_POST['Supplier_Prov'];
$Supplier_PostalCode = $_POST['Supplier_PostalCode'];
$Supplier_Country = $_POST['Supplier_Country'];
$queryCreate = "INSERT INTO supplierinfo (`Supplier_Name`, `Supplier_Contact`, `Supplier_StreetNo`, `Supplier_Province`, `Supplier_PostalCode`, `Supplier_Country`) VALUES ('$Supplier_name', '$Supplier_Contact', '$Supplier_StreetNo', '$Supplier_Prov', '$Supplier_PostalCode', '$Supplier_ountry')";
$sqlCreate = mysqli_query($connection, $queryCreate);
echo '<script>alert("Successfully created!")</script>';
//echo '<script>window.location.href = "/sourcing/index.php"</script>';
}
?>
Problem solved: Apparently, I did not check the structure of my table (ex. data types) that is why the data is not visible in mysql.
You have given wrong file name in forms action on index.php
You have to write action="createdata.php" in form on index.php
Form action should be like this :
form action = "createdata.php" method="POST"
Your query should be like this :
$queryCreate = "INSERT INTO supplierinfo (Supplier_Name, Supplier_Contact, Supplier_StreetNo, Supplier_Province, Supplier_PostalCode, Supplier_Country) VALUES ('$Supplier_name', '$Supplier_Contact', '$Supplier_StreetNo', '$Supplier_Prov', '$Supplier_PostalCode', '$Supplier_Country')";
For your query
$queryCreate = "INSERT INTO supplierinfo (`Supplier_Name`, `Supplier_Contact`, `Supplier_StreetNo`, `Supplier_Province`, `Supplier_PostalCode`, `Supplier_Country`) VALUES ('$Supplier_name', '$Supplier_Contact', '$Supplier_StreetNo', '$Supplier_Prov', '$Supplier_PostalCode', '$Supplier_ountry')";
$sqlCreate = mysqli_query($connection, $queryCreate);
You only assigned mysqli_query($connection, $queryCreate) to a PHP variable , but you didnt execute it.
Try this
if(mysqli_query($connection, $queryCreate)){
echo '<script>alert("Successfully created!")</script>';
}
Related
I'm super new to PHP and I recently tried to create a "system" that adds customers to the SQLite database and displays them in a table. Well, every time I navigate to the HTML page in order to add a new customer, the script runs itself creating empty values within the database. When I click submit after filling the values it just works properly. Below I attach my code for this specific part of the "system".
<!DOCTYPE html>
<html lang="en">
<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>New Customer</title>
<style>
form {
display:flex;
flex-direction:column;
width:65%;
max-width:75%;
margin:0 auto;
}
</style>
</head>
<body>
<form action="" method="POST">
<h1>Insert a new customer</h1>
<label for="id">Customer Id</label>
<input type="text" name="id" id="id">
<label for="name">Customer Name</label>
<input type="text" name="name" id="name">
<label for="age">Customer Age</label>
<input type="number" name="age" id="age">
<label for="address">Customer Address</label>
<input type="text" name="address" id="address">
<button type="submit">Submit</button>
</form>
<?php
class COMPANY extends SQLite3 {
function __construct() {
$this->open('customers.db');
}
}
$database = new COMPANY();
if (!$database) {
echo $database->lastErrorMsg();
} else {
echo "Database accessed!\n";
}
$insert ="INSERT INTO CUSTOMERS (ID, NAME, AGE, ADDRESS) VALUES ('".$_POST["id"]."', '".$_POST["name"]."', '".$_POST["age"]."','".$_POST["address"]."');";
$result = $database->exec($insert);
if(!$result) {
echo $database->lastErrorMsg();
} else {
echo "Records added successfully!\n";
}
$database->close();
?>
</body>
</html>
You need to use isset() and check if the form has actually posted the values. In your code, the page loads and PHP code executes without checking if the form has submitted and the blanks are inserted in the database
if(isset($_POST['id'],isset($_POST['name'],isset($_POST['age'], isset($_POST['address']) {
.. your code
}
PS: this doesn't include sanitization and validation of fields, please add them as you wish
There should be validation, values should not be empty.
Hello I have problem with my php code it won't insert value to the database and when it does the value is duplicate.
Here is the php code:
if (isset($_GET['addform']))
{
include '../includes/db.inc.php';
try
{
$sql = 'INSERT INTO author SET Author_name = :Author_name, Author_email =:Author_email';
$s = $pdo->prepare($sql);
$s->bindvalue(':Author_name', $_POST['Author_name']);
$s->bindvalue(':Author_email', $_POST['Author_email']);
$s->execute();
}
catch (PDOException $e)
{
$error = 'Error adding submitted author.';
include 'error.html.php';
exit();
}
header ('Location COMP1321/recipes/admin/authors/authors.html.php');
exit();
}
And here is the html form
<? php include 'index.php' ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?php html($pageTitle); ?></title>
</head>
<body>
<h1><?php html($pageTitle); ?></h1>
<form action="?addform" method="GET">
<label for="name"> Name: <input type="text" name="Author_name" id="Author_name"></label>
<br/>
<label for="email"> Email: <input type="text" name="Author_email" id="Author_email" ></label>
<br/>
<input type="hidden" name="id" value="<?php html($id); ?>">
<input type="submit" value="<?php html($button); ?>">
</form>
</body>
</html>
Any idea what went wrong here?
In your HTML code:
<form action="?addform" method="GET">
You are using GET as form method
And in your PHP code:
$s->bindvalue(':Author_name', $_POST['Author_name']);
$s->bindvalue(':Author_email', $_POST['Author_email']);
you are using POST
Try using same method to submit form from html code and get value in PHP code
I am making a basic registration form and my code is not working I tried problem-solving but I do not see any issues in my code. When the user submits the form the page does not go to register.php
Here is my connect.php code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "WifiP";
/* Attempt to connect to MySQL database */
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if($conn === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
?>
Here is my header.php code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>WifiP | Home</title>
<link rel="stylesheet" type="text/css" href="main.css">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
</head>
<body>
<ul>
<li>Home</li>
<li>Wifi</li>
<li>Login</li>
</ul>
Here is my footer.php code:
</body>
</html>
Here is my register.php code:
<?php
require_once 'connect.php' ;
$sql = "INSERT INTO users (email, password)
VALUES ('".$_POST["email"]."','".$_POST["password"]."')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Here is my register_page.php code:
<?php require_once 'header.php' ?>
<center>
<h1 class='pageTitle'>Register</h1>
<a href="register_page.php" class='registerLink'> Or Login</a><br>
<form action="register.php" method="post">
<input type="text" name="email" placeholder="Email"> <br>
<input type="password" name="password" placeholder="Password"><br>
<input type="password" name="rPassword" placeholder="Retype Password"><br>
<input type="button" value="Submit">
</form>
</center>
<?php require_once 'footer.php' ?>
The HTML element defines a form that is used to collect user input and after user insert that data need to submit the form to send that inserted data to action path.
To submitting a form there are some possible ways but according to your question you want to send data to 'register.php' by clicking the button you defined.
Form elements are different types of input elements, like text fields, checkboxes, radio buttons, submit buttons, and more.
In this case for submission the form you need a submit button that type should be "submit" not "button"
try change your register page like below
<input type="submit" value="Submit">
please according to the input type that it is "submit" not "button"
now by clicking the submit button your form data will send to action path.
I am a complete beginner when it comes to PHP. I have successfully created a login form/page that requires a user to enter his/her username and password which is then added to a database. I have also managed to create a page (using php) to display the data contained in all the data fields. I have the db connection file separately which works well. I have a functions.php file which contains the functions.
Now, I have created a php file in which I should be able to update the data in the various fields in the database. Instead of updating/replacing the existing data (username & password) in the selected row (targeting the id) it creates a new row in the db with the new username & password. Herewith my code to update existing data fields.
<?php include "db.php";?>
<?php include "functions.php";?>
<?php
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$id = $_POST['id'];
$query = "UPDATE users SET ";
$query .= "username = '$username', ";
$query .= "password = '$password', ";
$query .= "WHERE id = $id ";
$result = mysqli_query($connection, $query);
if(!$result) {
die("QUERY FAILED" . mysqli_error($connection));
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="col-sm-6">
<form action="login_create.php" method="post">
<div class="form-group">
<label for="username">Username</label>
<input type="text" name="username" class="form-control">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" name="password" class="form-control">
</div>
<div class="form-group">
<select name="id" id="">
<?php
showAllData();
?>
</select>
</div>
<input class="btn btn-primary" type="submit" name="submit" value="UPDATE">
</form>
</div>
</div>
</body>
</html>
I can simply not find the problem. Since people use PHP differently I am unable to find a solution based on the specific coding I have tried.
Update
Kindly note that I am working on a localhost as part of learning php and have not yet started looking at security. I am initialising the $connection via a different file (db.php) which I am calling in the first line of my previous code.
<?php
$connection = mysqli_connect('localhost', 'root', '', 'loginapp');
if(!$connection) {
die("Database connection failed");
}
?>
Since you didn't say what does the login_create.php do and what is the filename of that php code in your post. I can only guess that your login_create.php file is to create a new account not update it. Perhaps your file with that UPDATE query is not named login_create.php. Hence, my guess is that you put a wrong filename in your <form action="login_create.php" method="post">
(Posted solution on behalf of the question author).
The problem was with the incorrect naming of the form action. I used
<form action="login_create.php" method="post">
instead of
<form action="login_update.php" method="post">
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);