Data not inserting in sqlite3 database using php - 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();
}
?>

Related

add data from html forms to database. undefined sql error and empty query error

I am trying to add data from html form to database. However , I think everthing is OK but there are 2 errors: undefined sql and empty query. I research something and I learned sql injection but I dont understand what is the difference in INSERT INTO query. How can I solve this problem?(I have also one more column in database its name is id and it is auto inceremented. So I havent add it)
<?php
include('dbConnection.php');
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="addMember.css">
<script src="addMember.js"></script>
<title>Nature Apartment-Add Member</title>
</head>
<body>
<h1>Nature Apartment</h1>
<?php
if($_SERVER["REQUEST_METHOD"]=="POST"){
if(isset($_POST['submit'])){
$apartmentID= $_REQUEST['apartmentID'];
$uname= $_REQUEST['uname'];
$pwd= $_REQUEST['pwd'];
$phoneNumber= $_REQUEST['phoneNumber'];
$secondPhoneNumber= $_REQUEST['secondPhoneNumber'];
$whoseNumber= $_REQUEST['whoseNumber'];
$sql = "INSERT INTO members (apartmentID, username, password, phoneNumber, secondPhoneNumber, whoseNumber)
VALUES '$apartmentID', '$uname', '$pwd', '$phoneNumber', '$secondPhoneNumber', '$whoseNumber')";
}
}
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
?>
<ul>
<li>HomePage</li>
<li>Members</li>
<li>Payments</li>
<li>General Expenses </li>
<li>Chat</li>
<li>Settings</li>
</ul>
<br><br>
<h2>Add New Member</h2>
<br><br>
<form id="form" method="POST" >
<label for="apartmentID">Apartment ID</label><br>
<input type="text" id="id" name="id"><br><br>
<label for="username">Username</label><br>
<input type="text" id="uname" name="uname"><br><br>
<label for="Password">Password</label><br>
<input type="password" id="pwd" name="pwd"><br><br>
<label for="phoneNumber">Phone number</label><br>
<input type="text" id="phoneNumber" name="phoneNumber"><br><br>
<label for="secondPhoneNumber">Second phone number</label><br>
<input type="text" id="secondPhoneNumber" name="secondPhoneNumber"><br><br>
<label for="whoseNumber">Whose phone number? </label><br>
<input type="text" id="whoseNumber" name="whoseNumber"><br><br>
<input type="submit" value="Add" name="submit" >
</form>
</body>
</html>
I think you forgot a bracket??
$sql = "INSERT INTO members (apartmentID, username, password, phoneNumber, secondPhoneNumber, whoseNumber)
VALUES '$apartmentID', '$uname', '$pwd', '$phoneNumber', '$secondPhoneNumber', '$whoseNumber')";
Should be
$sql = "INSERT INTO members (apartmentID, username, password, phoneNumber, secondPhoneNumber, whoseNumber)
VALUES **(**'$apartmentID', '$uname', '$pwd', '$phoneNumber', '$secondPhoneNumber', '$whoseNumber')";

How to navigate html forms and save their input using php mysql without proceeding to .php file page?

I have 2 html forms. first page is registration page and next is login page. I managed to send the input from registration page to mysql using a php file named connect.php. the 'proceed' button in registration page will navigate to the php file but now i want the 'proceed' button in registration page link to login page and not the connect.php file nd update mysql. i tried putting the connect.php's codes into the registration page's html code but it didnt seem to work. Where should i put the php code in my html code and am i suppose to use bootstrap?
this is my connect.php code:
<?php
$name = $_POST['name'];
$age = $_POST['age'];
$gender = $_POST['gender'];
$email = $_POST['email'];
$username = $_POST['username'];
$password = $_POST['password'];
$host = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "ktm_member";
//Create connection
$conn = new mysqli($host, $dbusername, $dbpassword, $dbname);
if (!empty($username))
{
if (!empty($password))
{
if (mysqli_connect_error())
{
die ('Connect error('.mysqli_connect_errno().')'.mysqli_connect_error());
}
else
{
$sql = "INSERT INTO `member list`(`name`, `age`, `gender`, `email`, `username`, `password`) VALUES ('$_POST[name]', '$_POST[age]', '$_POST[gender]', '$_POST[email]', '$_POST[username]', '$_POST[password]')";
if ($conn->query($sql))
{
echo "New record added successfully.";
}
else
{
echo "Error".$sql."<br>".$conn->error;
}
$conn->close();
}
}
else
{
echo "Password should not be empty";
}
}
else
{
echo "Username should not be empty";
die();
}
?>
and this is my registration page html code:
<!doctype html>
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Register Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="./W3.CSS Template_files/w3.css">
<link rel="stylesheet" href="./W3.CSS Template_files/css">
<link rel="stylesheet" href="style.css">
<style>
body,h1 {font-family: "Raleway", sans-serif}
body, html {height: 100%}
.bgimg {
background-image: url('forestbridge.jpg');
min-height: 100%;
background-position: center;
background-size: cover;
}
</style>
</head>
<body><div class="bgimg w3-display-container w3-animate-opacity w3-text-white"><div class="w3-display-middle">
<center><h2>Register</h2></center>
<form name="form1" method="post" action="welcomeloginpage.php" autocomplete = "off">
<p class="w3-large w3-center">
<label for="name">Name: </label>
<input type="text" name="name" id="name" placeholder="Your full name" autofocus required>
</p>
<p class="w3-large w3-center">
<label for="age">Age: </label>
<input type="number" name="age" id="age">
</p>
<p class="w3-large w3-center">
<label for="gender">Gender: </label>
<input type="radio" name="gender" value="M"> Male
<input type="radio" name="gender" value="F"> Female<br> <id="gender">
</p>
<p class="w3-large w3-center">
<label for="email">Email: </label>
<input type="email" name="email" id="email" placeholder="xxx#xx.xx">
</p>
<p class="w3-large w3-center">
<label for="username">Username: </label>
<input type="text" name="username" id="username">
</p>
<p class="w3-large w3-center">
<label for="password">Password: </label>
<input type="password" name="password" id="password" maxlength="10" placeholder="password" data-toggle="password">
</p>
<p style="text-align: center;">
<input type="submit" name="submit" id="submit" value="Submit">
</p>
</form>
If you want your connect.php script to send the user to another page if the registration is successful then you use a header() command like this
<?php
$name = $_POST['name'];
$age = $_POST['age'];
$gender = $_POST['gender'];
$email = $_POST['email'];
$username = $_POST['username'];
$password = $_POST['password'];
$host = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "ktm_member";
//Create connection
$conn = new mysqli($host, $dbusername, $dbpassword, $dbname);
if (!empty($username)) {
if (!empty($password)) {
if (mysqli_connect_error()) {
die ('Connect error('.mysqli_connect_errno().')'
.mysqli_connect_error());
} else {
// this query style is very dangerous see note below
$sql = "INSERT INTO `member list`
(`name`, `age`, `gender`,
`email`, `username`, `password`)
VALUES ('$_POST[name]', '$_POST[age]', '$_POST[gender]',
'$_POST[email]', '$_POST[username]', '$_POST[password]')";
if ($conn->query($sql)) {
// remove echo as you will never see it now
//echo "New record added successfully.";
header('Location: otherPage.php');
exit; // important as header does not stop code execution in this script
} else {
echo "Error".$sql."<br>".$conn->error;
}
$conn->close();
}
} else {
echo "Password should not be empty";
}
} else {
echo "Username should not be empty";
die();
}
?>
You do have at least 2 serious flaws in this code though that I must mention.
Your script is wide open to SQL Injection Attack
Even if you are escaping inputs, its not safe!
Use prepared parameterized statements in either the MYSQLI_ or PDO API's
Never store plain Text password in your database. The most likely place where these things get compromised is from within the company running this database. An unhashed password is a total givaway for a DB Admin who just got refused a pay rise!
PHP provides password_hash()
and password_verify() please use them.
And here are some good ideas about passwords
If you are using a PHP version prior to 5.5 there is a compatibility pack available here

Can't enter data into sql database

I am using this code to add some data to my already existing sql database, but the can't seem to do so, it's also not giving any errors. I have tried everything that i could think of. This is a form which lets user input the data and then when user clicks submit it gives a success message in url but i get the success message but no data in my database.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Signup Form</title>
</head>
<body>
<form action="signup.php" method="POST">
<input type="text" name="firstname" placeholder="First Name">
<br>
<input type="text" name="lastname" placeholder="Last Name">
<br>
<input type="text" name="email" placeholder="E-mail">
<br>
<input type="text" name="uid" placeholder="User name">
<br>
<input type="password" name="pwd" placeholder="Password">
<br>
<button type="submit" name="submit">Sign up</button>
</form>
<?php
$sql = "SELECT * FROM users;" ;
$result = mysqli_query($conn,$sql); //connects the database to the query we just generated
$resultcheck = mysqli_num_rows($result); // it returns the number of rows in the query
if($resultcheck > 0){
//the if condition checks if there is any data inside $resultcheck
//The mysqli_fetch_assoc() function fetches a result row as an associative array.
while($row = mysqli_fetch_assoc($result)){
echo $row['user_uid'].'<br>';
}
}
?>
</body>
</html>
<?php
include_once 'dbh.php';
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$uid = $_POST['uid'];
$pwd = $_POST['pwd'];
$sql = "INSERT INTO users (`user_firstname`, `user_firstname`, `user_email`, `user_uid`, `user_pwd` ) VALUES (\'$firstname\',\'$lastname\',\'$email\',\'$uid\', \'$pwd\');";
//require 'dbh.php';
mysqli_query('$conn','$sql');
/* if($result=$mysqli->query($sql)){
echo "<p>User successfully added to database</p>".'<br>';
}
else{
echo "Error enterting user into database!".mysql_error().'<br>';
} */
header("Location: index.php?signup=success");
?>
<?php
$dbServername = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName = "login_system"; // selecting the database
$conn = mysqli_connect($dbServername,$dbUsername,$dbPassword,$dbName );
//$mysqli = new mysqli('localhost','root',"",$dbName );
if(mysqli_connect_errno()){
printf("connection failed %s\n",mysqli_connect_error());
exit();
}
$mysqli->select_db("login_system");
?>
Please remove single quotes in $conn and $sql
mysqli_query($conn, $sql);
in your insert PHP file.
$sql = "INSERT INTO `users` (`user_firstname`, `user_lastname`, `user_email`, `user_uid`, `user_pwd` ) VALUES ('".$firstname."', '".$lastname ."', '".$email."', '".$uid."', '".$pwd."');";
$result=mysqli_query('$conn','$sql');
if($result)
{
echo "succsessfuly...";
}
else
{
echo "Not succsessfuly...";
}
Try this one:
<?php
include_once 'dbh.php';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> Signup Form </title>
</head>
<body>
<form action="signup.php" method="POST">
<input type="text" name="firstname" placeholder="First Name">
<br>
<input type="text" name="lastname" placeholder="Last Name">
<br>
<input type="text" name="email" placeholder="E-mail">
<br>
<input type="text" name="uid" placeholder="User name">
<br>
<input type="password" name="pwd" placeholder="Password">
<br>
<button type="submit" name="submit">Sign up</button>
</form>
<?php
$sql = "SELECT * FROM users; " ;
$result = $mysqli->query($sql); //connects the database to the query we just generated
$resultcheck = $result->num_rows; // it returns the number of rows in the query
if($resultcheck > 0){
while($row = $result->fetch_assoc()){
echo $row['user_uid'].'<br>';
}
}
?>
</body>
</html>
signup.php
<?php
include_once 'dbh.php';
$firstname = $mysqli->real_escape_string($_POST['firstname']);
$lastname = $mysqli->real_escape_string($_POST['lastname']);
$email = $mysqli->real_escape_string($_POST['email']);
$uid = $mysqli->real_escape_string($_POST['uid']);
$pwd = $mysqli->real_escape_string($_POST['pwd']);
$sql = "INSERT INTO users (`user_firstname`, `user_lastname`, `user_email`, `user_uid`, `user_pwd` ) VALUES ('$firstname','$lastname','$email','$uid', '$pwd');";
if($result=$mysqli->query($sql)){
echo "<p>User successfully added to database</p>".'<br>';
}
else{
echo "Error enterting user into database!".$mysqli->error.'<br>';
}
header("Location: index.php?signup=success");
dbh.php
<?php
$dbServername = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName = "login_system"; // selecting the database
$mysqli = new mysqli($dbServername,$dbUsername,$dbPassword,$dbName);
if($mysqli->connect_errno){
printf("connection failed %s\n",$mysqli->connect_error);
exit();
}
Please read this reference http://php.net/manual/en/book.mysqli.php
should be like this
$sql = "INSERT INTO users (firstname, lastname, email, uid, pwd ) VALUES ('$firstname','$lastname','$email','$uid', '$pwd')";
mysqli_query($conn,$sql);

Can't insert into a database with PHP

For learning purposes, I am creating a password manager on my local system. However there is a problem when it comes to inserting data into the database and I'm not sure why it isn't working.
My entire document can be the found below.
<?php
$user = 'root';
$pass = '';
$db = 'accounts';
$server = 'localhost';
$db_handle = mysql_connect($server, $user, $pass);
if (!$db_handle) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
$db_found = mysql_select_db($db, $db_handle);
if ($db_found) {
if (isset($_POST['type'])) {
$getOrSet = $_POST['type'];
$site = $_POST['site'];
$login = $_POST['login'];
if ($getOrSet == 'get') {
$pass = mysql_fetch_assoc(mysql_query("SELECT password FROM manager WHERE site = '$site' AND username = '$login'"))['password'];
} else if ($getOrSet == 'set') {
$url = $_POST['url'];
$pass = $_POST['pass'];
mysql_query("INSERT INTO manager (site, url, username, password) VALUES ('$site', '$url', '$login' '$pass')");
}
}
} else {
echo "Unable to select database: " . mysql_error();
}
mysql_close($db_handle);
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#left,#right{width:50%;margin:0;padding:0;float:left;text-align:center}
form{width:300px;margin:0 auto}
label{width:300px;display:block;line-height:1.65em}
input{float:right}
#pass{width:300px}
#pass>span{float:right}
</style>
</head>
<body>
<h1>Password Manager</h1>
<div id="left">
<h2>Get Password</h2>
<form action="index.php" method="post">
<label>Site: <input type="text" name="site" /></label>
<label>Email/Username: <input type="text" name="login" /></label>
<input type="hidden" name="type" value="get" />
<?php if(isset($_POST['type'])){if ($getOrSet == 'get') {echo "<span id=\"pass\">Password: <span>$pass</span></span>";}} ?>
<input type="submit" value="Submit" />
</form>
</div>
<div id="right">
<h2>Set Password</h2>
<form action="index.php" method="post">
<label>Site: <input type="text" name="site" /></label>
<label>URL: <input type="text" name="url" /></label>
<label>Email/Username: <input type="text" name="login" /></label>
<label>Password: <input type="password" name="pass" /></label>
<input type="hidden" name="type" value="set" />
<input type="submit" value="Submit" />
</form>
</div>
</body>
</html>
Can someone please tell me why this code doesn't work?
mysql_query("INSERT INTO manager (site, url, username, password) VALUES ('$site', '$url', '$login' '$pass')");
use escapes before insert like
$site = mysql_real_escape_string($site);
$url = mysql_real_escape_string($url);
$login = mysql_real_escape_string($login);
$pass = mysql_real_escape_string($pass);
// now insert
mysql_query("INSERT INTO manager (site, url, username, password) VALUES ('$site', '$url', '$login', '$pass')");
Note : mysql_* is deprecated. use mysqli_* or PDO
The problem is that there is a missing , after '$login' so
mysql_query("INSERT INTO manager (site, url, username, password) VALUES ('$site', '$url', '$login' '$pass')");
should have been
mysql_query("INSERT INTO manager (site, url, username, password) VALUES ('$site', '$url', '$login', '$pass')")

I can connect to mysql db but my table is not updating

I am able connect to mysql db where i have created a table called attorney_users. I would like to know what i am missing or doing wrong? I have post my function code below. when i register the user it confirms the success, but the table is not updated.
<?php
require_once('appvars.php');
require_once('connectvars.php');
// Connect to the database
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (isset($_POST['submit'])) {
// Grab the profile data from the POST
$username = mysqli_real_escape_string($dbc, trim($_POST['username']));
$firstname = mysqli_real_escape_string($dbc, trim($_POST['firstname']));
$lastname = mysqli_real_escape_string($dbc, trim($_POST['lastname']));
$firmname = mysqli_real_escape_string($dbc, trim($_POST['firmname']));
$email = mysqli_real_escape_string($dbc, trim($_POST['email']));
$password = mysqli_real_escape_string($dbc, trim($_POST['password']));
$password2 = mysqli_real_escape_string($dbc, trim($_POST['password2']));
if (!empty($username) && !empty($password) && !empty($password2) && ($password == $password2)) {
// Make sure someone isn't already registered using this username
$query = "SELECT * FROM attorney_users WHERE username = '$username'";
$data = mysqli_query($dbc, $query);
if (mysqli_num_rows($data) == 0) {
// The username is unique, so insert the data into the database
$query = "INSERT INTO attorney_users (username, firstname, lastname, firmname, email, password, date) VALUES ('$username', '$firstname', '$lastname', $firmname, $email, SHA('$password'), NOW())";
mysqli_query($dbc, $query);
// Confirm success with the user
echo '<p>Your new account has been successfully created. You\'re now ready to log in.</p>';
mysqli_close($dbc);
exit();
}
else {
// An account already exists for this username, so display an error message
echo '<p class="error">An account already exists for this username. Please use a different username.</p>';
$username = "";
}
}
else {
echo '<p class="error">You must enter all of the sign-up data, including the desired password twice.</p>';
}
}
mysqli_close($dbc);
?>
<div id="main-wrapper">
<div id="register-wrapper">
<form method="post" action = "<?php echo $_SERVER['PHP_SELF'];?>">
<fieldset>
<ul>
<label for="username">Username : </label>
<input type="text" id="username" name = "username" value = "<?php if (!empty($username)) echo $username; ?>" />
<label for="firstname">First Name : </label>
<input type="text" id="firstname" name = "firstname" />
<label for="lastname">Last Name : </label>
<input type="text" id="lastname" name = "lastname" />
<label for="firmn">Firm Name : </label>
<input type="text" id="firmname" name = "firmname" />
<label for="email">Email : </label>
<input type="text" id="email" name = "email" />
<label for="password">Password : </label>
<input type="password" id="password" name="password" />
<label for="password2">Verify Password : </label>
<input type="password" id="password2" name="password2" />
</li>
<li class="buttons">
<input type="submit" value="Register" name="submit" />
<input type="button" name="cancel" value="Cancel" onclick="location.href='index.php'" />
</li>
</ul>
</fieldset>
</form>
</div>
</div>
</body>
</html>
date is reserved in mysql, use ` around column name
$query = "INSERT INTO attorney_users (`username`, `firstname`,
`lastname`, `firmname`, `email`, `password`, `date`)
VALUES ('$username', '$firstname', '$lastname', $firmname,
$email, SHA('$password'), NOW())";
And why are you using mysqli_real_escape_string for escaping , you can use prepared statement here.
Edit
Use this for checking error in query
$data = mysqli_query($dbc, $query) or die(mysqli_error());
change your $query from
$query = "INSERT INTO attorney_users (username, firstname, lastname, firmname, email, password, date) VALUES ('$username', '$firstname', '$lastname', $firmname, $email, SHA('$password'), NOW())";
to
$password = SHA1($password);
$query = "INSERT INTO attorney_users (`username`, `firstname`, `lastname`, `firmname`, `email`, `password`, `date`) VALUES ('{$username}', '{$firstname}', '{$lastname}', '{$firmname}', '{$email}', '{$password}', NOW())";

Categories