I can't insert data inTO my sql table using PDO [duplicate] - php

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

Related

PHP running script after reload with empty values

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.

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>

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

A database is not updated if some values are not filled in the form [duplicate]

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");

PHP not sending the UPDATE info to the database

I'm not that big of a genius in PHP nor in SQL but I'm getting this strange error, where I see the info that I want to send to the data base on the link and I get no errors, however my database is not getting updated.
<!DOCTYPE html>
<html lang="PT">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Alteração do produto</title>
</head>
<body>
<?php
$lig=new mysqli("localhost", "root", "", "pie");
if($lig->connect_errno != 0){
echo ("Base de dados indisponível");
}
$instrucao=$lig->prepare("UPDATE produto SET produto1 = ? , quantidade1 = ? , preco1 = ? WHERE codigo1 = ?");
$instrucao->bind_param("isid", $_GET['codigo1'], $_GET['produto1'], $_GET['quantidade1'], $_GET['preco1']);
$resultado=$instrucao->execute();
if($resultado==FALSE){
echo "<p>produto não editado</p>";
}
else {
//header( "Location: shoppinglist.php" );
}
$lig->close();
?>
<form method="get">
<label>Código: <input name="codigo1" readonly value="<?php echo $_GET['codigo1'] ?>"></label>
<label>Nome: <input name="produto1" value="<?php echo $_GET['produto1'] ?>"></label>
<label>Quantidade: <input name="quantidade1" value="<?php echo $_GET['quantidade1'] ?>"></label>
<label>Preço: <input name="preco1" value="<?php echo $_GET['preco1'] ?>"></label>
<button type="submit" value="POST">Alterar</button>
</form>
</body>
</html>
I know that there can be some syntax errors on this code, and I'm sorry if so. Thanks in advance!
try with
$instrucao->bind_param("sidi", $_GET['produto1'], $_GET['quantidade1'], $_GET['preco1'], $_GET['codigo1']);
i think you are binding the wrong params shouldn't the first one be $_GET['produto1'] (since it's the first one in the update statement..

Categories