Not posting to SQLite Database - php

How can i get my form to submit to my SQLite database, i think i need to add an INSERT INTO statement somewhere. I'm stupid when it comes to PHP, could someone explain why its not working and help me get it to work?
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>Input</title>
<link href="css/style.css" type="text/css" rel="stylesheet" />
</head>
<body>
<?php
try {
$dbh = new PDO('sqlite:mydb.sqlite3');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->exec("CREATE TABLE IF NOT EXISTS test (
name VARCHAR(30),
gender VARCHAR(30),
age INTEGER)"
);
$data = array(
array('name' => 'Daniel', 'gender' => 'Male', 'age' => '21')
);
$insert = "INSERT INTO test (name, gender, age)
VALUES (:name, :gender, :age)";
$stmt = $dbh->prepare($insert);
foreach ($data as $m) {
$name = $m['name'];
$gender = $m['gender'];
$age = $m['age'];
$stmt->bindParam('name', $name);
$stmt->bindParam('gender', $gender);
$stmt->bindParam('age', $age);
$stmt->execute();
}
$result = $dbh->query('SELECT * FROM test');
$dbh = null;
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
<div id="wrapper">
<div class="banner1">
<h2>Input</h2>
</div>
<form id="form" method="post">
Name:<br>
<input type="text" name="name[0]"/> <br>
Gender:<br>
<input type="text" name="gender[0]"/> <br>
Age:<br>
<input type="number" name="age[0]" min="1" max="99"/> <br>
<input id="submit" type="submit" value="Input">
</form>
</div>
<div id="results">
<div class="banner2">
<h2>Results</h2>
</div>
<div class="data">
<?php
unset($_POST['submit']);
$data=$_POST;
foreach ($result as $row) {
echo $row['name'] . " ";
echo $row['gender'] . " " ;
echo $row['age'] . "<br>" . " ";
}
?>
</div>
</div>
</body>
</html>
Here is a screenshot so you can grasp an idea of the form and how i'd like it to work. The results section is just generated from the array so i can see what is being inputted, but i'd like the input form to send data to the SQLite database that i have created/connected to above. Thank you.

Related

Data not inserting in sqlite3 database using php

Hy guys, I have a sqlite database named signup.db and a signup table in it and I have a php code of a signup page but it us not inserting any data on submit I also am not getting Amy error even on clicking on submit
*don't mind SQL injection this is just testing I will use SQL prepared statement when I make my next project
Code
<?php
if(isset($_POST['submit'])){
//connection to sqlite3 database
$dir = 'sqlite: sign.db';
$db = new PDO($dir) or die ("Unable to open");
//select table
//saving data
$email = $_POST["Email"];
$first = $_POST["First"];
$last = $_POST["Last"];
$password = $_POST["Password"];
$male = $_POST["Male"];
$female = $_POST["Female"];
$date = $_POST["Dateofb"];
$sql = "INSERT INTO Signup (First, Last, Email, Password, Male, Female, Dateofb) VALUES ('$first', '$last', '$email', '$pass', '$male', '$female', '$date');";
$sql->execute();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="index.css" >
<script src="index.js" ></script>
<title>Survey</title>
</head>
<body>
<form action="" method="post" >
<div class="container" >
<div class="form" >
<input type="email" class="first" id="email" placeholder="Email" required="required">
<input type="text" class="second" id="first" placeholder="First name" required="required">
<input type="text" class="last" id="last" placeholder="Last name" required="required">
<input type="password" class="pass" id="pass" placeholder="Password" required="required">
<div class="day" >
<p class="bd" >Birthday Date:</p>
<input type="date" class="date" id="date" >
</div>
<div>
<div class="malee" >
<input type="checkbox" class="male" id="male" >
<p class="mal" >Male</p>
</div>
<div class="femalee" >
<input type="checkbox" class="female" id="female" >
<p class="fem" >Female</p>
</div>
</div>
<div >
<input class="submit" id="submit" type="submit" >
</div>
<div class="acc" >
already have account <a href="#" >Login</a>
</div></div>
</div>
</form>
</body>
</html>
(https://i.stack.imgur.com/vYkug.jpg)
Your code has two issues:
You should query on a db connection
$db->exec($sql);
In $sql string
$pass should be $password
$sql = "INSERT INTO Signup (First, Last, Email, Password, Male, Female, Dateofb)
VALUES ('$first', '$last',
'$email', ******'$pass'*******, '$male', '$female', '$date');";
I created sandbox for you. Working fine . You can copy this code into a separate test.php file and try running it
Check this sandbox
<?php
try {
$conn = new PDO("sqlite: sign.db");
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$email = "test2";
$first = "";
$last = "";
$password = "";
$male = "";
$female = "";
$date = "";
$sql = "CREATE TABLE IF NOT EXISTS Signup (
First text NOT NULL,
Last text NOT NULL,
Email text NOT NULL,
Password text NOT NULL,
Male text NOT NULL,
Female text NOT NULL,
Dateofb text NOT NULL
);";
$conn->exec($sql);
$sql = "INSERT INTO Signup (First, Last, Email, Password, Male, Female, Dateofb) VALUES ('$first', '$last', '$email', '$password', '$male', '$female', '$date');";
$conn->exec($sql);
echo "New record created successfully \n";
$sql = "SELECT * FROM Signup";
$result = $conn->query($sql);
while ($row = $result->fetch()) {
echo $row['Email']."\n";
}
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
?>

Shows wrong data Decrypy PDO/PHP

I have a question about my code. The problem is that when i say echo $collumB than he shows the student_city. that is in my database but i want that it shows the decrypted password. It just shows the wrong data
(there is an another page where i encrypt the password but i need the decrypted password echo'ed
<html>
<head>
<title>insert data in database using PDO(php data object)</title>
<link rel="stylesheet" type="text/css" href="style-login.css">
</head>
<body>
<div id="main">
<h1>Login using PDO</h1>
<div id="login">
<h2>Login</h2>
<hr/>
<form action="" method="post">
<label>Email :</label>
<input type="email" name="stu_email" id="email" required="required" placeholder="john123#gmail.com"/><br/><br />
<label>Password :</label>
<input type="password" name="stu_ww" id="ww" required="required" placeholder="Please Enter Your Password"/><br/><br />
<input type="submit" value=" Submit " name="submit"/><br />
</form>
</div>
</div>
<?php
//require ("encrypt.php");
if(isset($_POST["submit"])){
$hostname='localhost';
$username='root';
$password='';
$pdo = "college";
$student_email = $_POST["stu_email"];
$encrypt_key = "4ldetn43t4aed0ho10smhd1l";
try {
$dbh = new PDO("mysql:host=$hostname;dbname=college","root","$password");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Query
$statement = $dbh->prepare("SELECT student_email, student_city, AES_DECRYPT(student_password, '$encrypt_key')
AS student_password FROM students WHERE student_email = :student_email ORDER BY student_email ASC");
// Assign and execute query
$statement->bindParam(':student_email', $student_email, PDO::PARAM_STR);
$statement->setFetchMode(PDO::FETCH_ASSOC);
$statement->execute();
// Get data
while($row = $statement->fetch()) {
echo "1 ,";
//$columnA_value = $row['student_city'];
$columnB_value = $row['student_password'];
}
echo "2 ,";
echo $columnB_value;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
?>
</body>
</html>
SELECT student_email, student_city, CAST(AES_DECRYPT(student_password, '$encrypt_key') AS char(50)) AS student_password FROM students WHERE student_email = :student_email ORDER BY student_email ASC;
Try to explicitly cast it to string. You can change the '50' according to your requirement.
Also your echo is outside while loop, hence it will print only last record if there are more than 1 records.

Prevent duplicate SQL entries and insert data to SQLite in PHP

On submit/refresh the same predefined data in my array is added. How do i stop it being added more than once. I'd like to get rid of the data in my array if possible and just catch user input from the form which then is submitted to the array but i'm not sure how. Also how can i get my form to submit to my SQLite database, i think i need to add an INSERT INTO statement somewhere. Any help would be nice as i need this finished soon. :(
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>Input</title>
<link href="css/style.css" type="text/css" rel="stylesheet" />
</head>
<body>
<?php
try {
$dbh = new PDO('sqlite:mydb.sqlite3');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->exec("CREATE TABLE IF NOT EXISTS test (
name VARCHAR(30),
gender VARCHAR(30),
age INTEGER)"
);
$data = array( //Want to remove this prewritten data and store user input instead.
array('name' => 'Daniel', 'gender' => 'Male', 'age' => '21')
);
$insert = "INSERT INTO test (name, gender, age)
VALUES (:name, :gender, :age)";
$stmt = $dbh->prepare($insert);
foreach ($data as $m) {
$name = $m['name'];
$gender = $m['gender'];
$age = $m['age'];
$stmt->bindParam('name', $name);
$stmt->bindParam('gender', $gender);
$stmt->bindParam('age', $age);
$stmt->execute();
}
$result = $dbh->query('SELECT * FROM test');
$dbh = null;
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
<div id="wrapper">
<div class="banner1">
<h2>Input</h2>
</div>
<form id="form" method="post">
Name:<br>
<input type="text" name="name[0]"/> <br>
Gender:<br>
<input type="text" name="gender[0]"/> <br>
Age:<br>
<input type="number" name="age[0]" min="1" max="99"/> <br>
<input id="submit" type="submit" value="Input">
</form>
</div>
<div id="results">
<div class="banner2">
<h2>Results</h2>
</div>
<div class="data">
<?php
unset($_POST['submit']);
$data=$_POST;
foreach ($result as $row) {
echo $row['name'] . " ";
echo $row['gender'] . " " ;
echo $row['age'] . "<br>" . " ";
}
?>
</div>
</div>
</body>
</html>
Here is a screenshot so you can grasp an idea of the form and how i'd like it to work. The results section is just generated from the array so i can see what is being inputted, but i'd like the input form to send data to the SQLite database that i have created/connected to above. Thank you.
First you have to test if Post exists
And second, check if the user already exist
if (isset($_POST)) {
// check for existing user
// Save
}

This webpage has a redirect loop - php

Got a simple form on my index.php page that when submitted is processed on my post.php page.
index.php
<form id="form" action="post.php" method="post">
Name:<br>
<input type="text" name="name"/> <br>
Gender:<br>
<input type="text" name="gender"/> <br>
Age:<br>
<input type="number" name="age" min="1" max="99"/> <br>
<input id="submit" type="submit" value="Input">
</form>
<div class="data">
<?php
include ('post.php');
foreach ($result as $row) {
echo $row['name'] . " ";
echo $row['gender'] . " " ;
echo $row['age'] . "<br>" . " ";
}
?>
</div>
post.php
Below is the code for my post.php page, at the top is my header but i keep getting the same error when i submit the form.
<?php
header("Location: index.php");
try {
$dbh = new PDO('sqlite:mydb.sqlite3');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->exec("CREATE TABLE IF NOT EXISTS test (
name VARCHAR(30),
gender VARCHAR(30),
age INTEGER)"
);
if (!empty($_POST)) {
$stmt = $dbh->prepare("INSERT INTO test (name, gender, age) VALUES (:name, :gender, :age)");
$stmt->execute(array(':name' => $_POST['name'], ':gender' => $_POST['gender'],':age' => $_POST['age']));
$title = $_POST['name'];
$message = $_POST['gender'];
$age = $_POST['age'];
}
$result = $dbh->query('SELECT * FROM test');
$dbh = null;
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
Inside index.php you are include-ing the post.php file which immediately forwards you back to index.php.
You need to make the forwarding in post.php conditional or you need to rework your logic.

Form saying its sent but there is no data is showing up in the database

I'm new to PHP and still trying to get my head round it. this form says that the data has been sent to the database but when I look the database is empty, no errors are showing up? is there a problem with my code.
Note: I understand that this form is not protected from SQL Injection.
HTML
<?php
session_start();
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Page Form</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<div class="main">
<h2>PHP Page 3 Form</h2><hr/>
<span id="error">
</span>
<form action="page4_insertdata.php" method="post">
<label>Company Name :<span>*</span></label><br />
<input name="company_name" type="text" placeholder="Joes Cleaner" required>
<br />
<label>Ref :<span>*</span></label><br />
<input name="ref" type="text" placeholder="H123" required>
<br />
<label>Website :<span>*</span></label><br />
<input name="website" type="text" placeholder="www.google.com" required>
<br />
<label>Email :<span>*</span></label><br />
<input name="email" type="email" placeholder="Joescleaners#gmail.com" required>
<br />
<label>Telephone :<span>*</span></label><br />
<input name="tel" type="text" placeholder="07123456789" required>
<br />
<label>Message :<span>*</span></label><br />
<input name="message" id="message" type="text" size="500" required>
<br />
<input type="reset" value="Reset" />
<input name="submit" type="submit" value="Submit" />
</form>
</div>
</div>
</body>
</html>
PHP
<?php
session_start();
?>
<!DOCTYPE HTML>
<html>
<head>
<title>PHP Multi Page Form</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<div class="main">
<h2>PHP Multi Page Form</h2><hr/>
<?php
$servername = "localhost";
$db_database = 'form';
$username = "root";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "DB Connected successfully. ";
$company_name = $_POST['company_name'];
$ref = $_POST['ref'];
$website = $_POST['website'];
$email = $_POST['email'];
$tel = $_POST['tel'];
$message = $_POST['message'];
$sql = "INSERT INTO detail (company_name,ref,website,email,tel,message)
VALUES ('$company_name','$ref','$website','$email','$tel','$message')";
if($sql){
echo " Database Sent.";
}
else {
echo "ERROR to insert into database";
};
?>
</div>
</div>
</body>
</html>
Change the following code:
if($sql){
echo " Database Sent.";
}
else {
echo "ERROR to insert into database";
};
To:
$result = $conn->query($sql);
if($result){
echo " Database Sent.";
}
else {
echo "ERROR to insert into database";
};
This way you are actually performing the query and checking on failure of query...
To make your query a bit safer, try the following:
$sql = "
INSERT INTO detail (
company_name,
ref,
website,
email,
tel,
message
)
VALUES (
'" . mysqli_real_escape_string($company_name) . "',
'" . mysqli_real_escape_string($ref) . "',
'" . mysqli_real_escape_string($website) . "',
'" . mysqli_real_escape_string($email) . "',
'" . mysqli_real_escape_string($tel) . "',
'" . mysqli_real_escape_string($message) . "'
)";
Better yet, use binding of params by replace the $sql instantiation and query execution ($conn->query()) with the following:
$stmt = $conn->prepare("INSERT INTO detail (company_name,ref,website,email,tel,message) VALUES (?, ?, ?, ?, ?, ?)");
$stmt->bind_param('ssssss', $company_name, $ref, $website, $email, $tel, $message);
$stmt->execute();
You can read up on binding parameters with mysqli by visiting PHP: mysqli_stmt::bind_param - Manual
Complete code:
<?php
session_start();
?>
<!DOCTYPE HTML>
<html>
<head>
<title>PHP Multi Page Form</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<div class="main">
<h2>PHP Multi Page Form</h2><hr/>
<?php
$servername = "localhost";
$db_database = 'form';
$username = "root";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $db_database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "DB Connected successfully. ";
$stmt = $conn->prepare("INSERT INTO detail (company_name,ref,website,email,tel,message) VALUES (?, ?, ?, ?, ?, ?)");
$stmt->bind_param('ssssss',
$_REQUEST['company_name'],
$_REQUEST['ref'],
$_REQUEST['website'],
$_REQUEST['email'],
$_REQUEST['tel'],
$_REQUEST['message']
);
if($stmt->execute()) {
echo " Database Sent.";
} else {
echo "ERROR to insert into database: " . $stmt->error;
};
?>
</div>
</div>
</body>
</html>
You arent actually sending a query, you are setting the variable $sql = "INSERT....."
which is always true.
you need to do:
$result = $mysqli->query($sql);
if ($result......)

Categories