PHP running script after reload with empty values - php

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.

Related

Inserting record into SQLite using PHP

For the past two hours, I have been trying to create a simple insertion form that connects to a SQLite. For some reason, the insertion of a new record won't work. I get no error message when I run my app using php -S localhost:1234. My form is just emptied out without any insertion after a click on the Submit button.
My database is named database.db, the table is named students_tb, and the columns in the table are id, sname and score.
Here is my code, which is based on https://www.youtube.com/watch?v=cyl0Oj3rmmg&list=PLU70qqWW4frENsWYAm-tAKp2ZJQ_dt3WR&index=8. I checked and rechecked the 3-minute-long tutorial, but wasn't successful at tracking down my bug. I guess this must be a silly mistake, but I really can't find it.
<!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>Add Student</title>
<style>
label, input {
display: block;
}
</style>
</head>
<body>
<h1>Add student to database</h1>
<?php
// has the form been submitted?
// if not, show the HTML form
if (!isset($_POST['submit'])) {
?>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<label for="sname">Student's Name</label>
<input type="text" name="sname" required>
<label for="score">Score</label>
<input type="number" name="score" required>
<button type="submit">Submit</button>
</form>
<?php
} else {
try {
$db = new PDO("sqlite:database.db");
$sql = "INSERT INTO students_tb (sname, score) VALUES (:sname, :score)";
$stat = $db->prepare($sql);
// named params
$sname = filter_input(INPUT_POST, "sname");
$stat->bindValue(":sname", $sname, PDO::PARAM_STR);
$score = filter_input(INPUT_POST, "score");
$stat->bindValue(":score", $score, PDO::PARAM_INT);
$success = $stat->execute();
// does the value exist?
if ($success) {
echo "The student has been added to the database.";
} else {
echo "The student has NOT been added to the database.";
}
$db = null;
} catch (PDOException $e) {
// for development
print "We had an error: " . $e->getMessage() . "<br>";
die();
}
}
?>
</body>
</html>
It has been a while since I worked in PHP, but I think the problem might be in the HTML code of the form. You have:
<button type="submit">Submit</button>
And your PHP code is checking for a value of the variable named submit, but this field does not have a name, only a type. Should it be:
<button type="submit" name="submit">Submit</button>

PHP POST requests only inserts blank rows

So i'm pretty new to PHP and can't understand why my POST request is not working. .
I'm just building a simple TodoApp and have a Add new task view like this:
add.php
<!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" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" rel="stylesheet" />
<link rel="stylesheet" href="../css/style.css" />
<title>To-Do List</title>
</head>
<body>
<div class="wrapper">
<form action="" method="post">
<h2 class="title">Add a new task</h2>
<div class="content">
<div class="inputFields">
<label for="task">Task:</label>
<input type="text" name="task" placeholder="Task name" />
<label for="task">Description:</label>
<br />
<textarea type="text" name="description" placeholder="Add a description" rows="5"
cols="40"></textarea>
<br />
<button type="submit" class="btn">Save</button>
</div>
</div>
</form>
<button class="btn">Go back</button>
</div>
</body>
</html>
My db file DB.php looks like this:
<?php
error_reporting (E_ALL ^ E_NOTICE);
/**
* #package DBConnection
* #author Frida
*/
// DB Connection
$pdo = new PDO('mysql:host=localhost;port=3306;dbname=TodoApp', 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// GET - Get All tasks
$statement = $pdo->prepare('SELECT * FROM todo_list ORDER BY created DESC');
$statement->execute();
// Fetch all tasks as an assoc array
$tasks = $statement->fetchAll(PDO::FETCH_ASSOC);
// POST - Add a task
$task = $_POST['task'];
$description = $_POST['description'];
$date = date('Y-m-d H:i:s');
$pdo->exec("INSERT INTO todo_list (task, description, status, created)
VALUES ('$task', '$description', 0, '$date')
")
?>
This is my schema:
Todo schema
I've done var_dump($_POST) which shows the array without any issues, if anyone can help me out?
In your HTML form action attribute is empty which mean that form is submit to same file in your case add.php.
So you should use $_POST in add.php file either you must submit form to DB.php for example
<form action="DB.php" method="post">

Can not Insert data into MySQL from PHP form

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>';
}

PHP form is not inserting value

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

Error Count - PHP

I have a form which has email as field name. What I am trying to do is if the email is it no equal to $emailToCheck is not equal to $_POST['email'], it should throw an error first time. The second time if the user enters wrong email id again it should always redirect to "error.htm" even if the page refreshes.
It doesn't work the form always shows even if the email id is entered wrong twice.
<?php
if (!empty($_POST['email'])) {
$email="website#test.com";
if($email!=$_POST['email'])
{
$count="1";
}
if($count=="2"){
header("Location: /error.htm");
exit(0);
}
}
if($count!="2"){
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Form</title>
</head>
<body id="main_body" >
<div id="form_container">
<h1><a>Form</a></h1>
<form id="form_1123848" class="appnitro" method="post" action="">
<div class="form_description">
<h2>Form</h2>
<p> <input type="text" name="email" value="" /></p>
</div>
<ul >
<li class="buttons">
<input id="saveForm" class="button_text" type="submit" name="submit" value="Submit" />
</li>
</ul>
</form>
</body>
</html>
<?
}
?>
You have two issues here:
1. You are defining $count as a string, and never incrementing it. If you look over your code, $count is getting specifically set to 1 every time there is a mismatch. How is supposed to ever get to 2?
2. Furthermore, data here is stateless. How is the script supposed to know what $count was set to on the previous call? You need to also set $count as a session variable so that the script will know what its previous value.
You should try updating your code to something similar to this:
// Check if `email` passed in POST request:
if ($_POST['email']) {
$email = "website#test.com"; //Manually define expected email address.
// Check if provided email does *not* match the expected email:
if ($email !== $_POST['email']) {
// Record the mismatch attempt in session and increment:
if (!($_SESSION['incorrectEmailCount'])) {
// If this is the first mismatch, define the session variable, and set to 1.
$_SESSION['incorrectEmailCount'] = 1;
} else {
// Session variable already set due to previous mismatch. Increment it.
$_SESSION['incorrectEmailCount']++;
}
}
// If user entered incorrect email more than once:
if ($_SESSION['incorrectEmailCount'] > 1) {
// Redirect to error page and stop execution.
header("Location: /error.htm");
exit(0);
}
}
Once the form is submitted, the page reloads, resetting the counter. In order to actually count, you need to provide that value in the form and pass it along to the PHP when the form is submitted.
<?php
// Try to get the amount of attempts from the POSTed data
$count = isset($_POST['count']) ? $_POST['count'] : 0;
if (isset($_POST['email'])) {
$email = "website#test.com";
if ($email != $_POST['email']) {
$count++;
}
if ($count == 2) {
header("Location: /error.htm");
}
}
if ($count <= 2):
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Form</title>
</head>
<body id="main_body" >
<div id="form_container">
<h1><a>Form</a></h1>
<form id="form_1123848" class="appnitro" method="post" action="">
<!-- Let the POST data know this is the x attempt -->
<input type="hidden" name="count" value="<?php echo $count; ?>">
<div class="form_description">
<h2>Form</h2>
<p> <input type="text" name="email" value="" /></p>
</div>
<ul>
<li class="buttons">
<input id="saveForm" class="button_text" type="submit" name="submit" value="Submit" />
</li>
</ul>
</form>
</div>
</body>
</html>
<?php endif; ?>
Also, your coding style is far from consistent. Try to work on that!

Categories