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>
Related
This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 6 months ago.
I am having this issue for days now, every SQL command (i am using PDO statements) work except INSERT INTO (i am able to SELECT and CREATE tables, but not to add data from my form into it ). I have checked and I have all the privileges that i need + i have tried all the versions of this code i could find online but nothing seems to work. Any idea?
//Sorry for the pic, it's my first post and i did'nt knew.
<!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>
<form method="post">
<input class="input" type= "text" name="nom" placeholder="nom" required> <br>
<input class="input" type= "password" name="password" placeholder="password" required><br>
<input class="button" type= "submit" value="Signup">
</form> <br>
</body>
</html>
<?php
//connessione bd
try {
$bd = new PDO("mysql:host=localhost;dbname=ems_db;charset=utf8", "root", "root");
// set the PDO error mode to exception
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
//recupero
$arr['nom'] = $_POST ['nom'];
$arr['password'] = hash('sha1', $_POST ['password']);
print_r($arr);
//
$sql = 'INSERT INTO users ( nom, password) VALUES( :nom, :password,)';
$statement = $bd->prepare($sql);
$statement->execute([
':userid' => $arr['userid'],
':nom' => $arr['nom'],
':password' => $arr['password'],
':rankid' => $arr['rankid'],
]);
$publisher_id = $bd->lastInsertId();
echo 'The publisher id ' . $publisher_id . ' was inserted';
to answer your problem, to insert a data, the whole line must be inserted, you can't just insert one data but several data
enter image description here
enter image description here
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.
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>';
}
This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 1 year ago.
I'm trying to update an SQL database from GUI. If I fill out all the fields in the form it works, but if any of the fields is NULL or empty nothing will update. No error is thrown, but database won't update in phpmyadmin.
I want to be able to accept NULL and empty fields, including be able to erase content in a field.
I'm not a programmer so I'd appreciate explanations on how to deal with these empty fields.
<?php
include ("connection.php");
include ("foundation.php");
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP UPDATE DATA USING PDO</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form name="frmUser" method="post" action="">
<input type="text" name="id" required placeholder="id"><br><br>
<input type="text" name="person" required placeholder="person"><br><br>
<input type="text" name="dob" required placeholder="dob"><br><br>
<input type="text" name="dod" required placeholder="dod"><br><br>
<input type="submit" name="update" required placeholder="Update Data">
</form>
</body>
</html>
<?php
if(isset($_POST['update']))
{
// get values from input text and number
$id = $_POST['id'];
$person = $_POST['person'];
$dob = $_POST['dob'];
$dod = $_POST['dod'];
// mysql query to Update data
$pdoquery = "UPDATE people SET id=:id, person=:person,dob=:dob,dod=:dod WHERE id='" . $_GET['id'] . "'";
$pdoQuery_run = $pdocbcon->prepare($pdoquery);
$pdoQuery_exec = $pdoQuery_run->execute(array(":person"=>$person,":dob"=>$dob,":dod"=>$dod,":id"=>$id));
if($pdoQuery_exec)
{
echo 'Uppdaterat';
}
else
{
echo 'FEL';
}
}
?>
ID value cannot be null so in front end it must be inserted and in database you need to allow null for all the other columns.
if(isset($_POST['update']))
{
// get values from input text and number
$id = $_POST['id'];
$person = $_POST['person'];
$dob = $_POST['dob'];
$dod = $_POST['dod'];
if(empty($id)){
echo("Missing Information! You must input ID");
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.