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

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

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();
}
?>

PHP / MySQLi registration form just returns a blank white page with no echoes or errors

so I'm just making a very basic registration for for PHP, and well...everytime I try to run it, it just returns a blank page, there are no errors or echos, just a plain, blank white page. I was hoping you guys could explain why as there are no obvious errors in my code.
Here is my reg.php file:
<html>
<head>
<title>Registered!</title>
</head>
<body>
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'database');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
if(isset($_POST['submit']))
{
$name = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$username = mysqli_real_escape_string($db, $name);
$email = mysqli_real_escape_string($db, $email);
$password = mysqli_real_escape_string($db, $password);
$query = mysqli_query($db, "INSERT INTO users (username, password,
email)VALUES ('$name', '$password', '$email')");
if($query)
{
echo "You are now registered!";
}
else
{
echo "failed";
}
}
?>
</body>
</html>
and here is my html For the form section
<div id="id01" class="modal">
<form class="modal-content animate" action="reg.php" method="post">
<div class="container">
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" id="username"
name="username" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" id="password"
name="password" required>
<label><b>Email</b></label>
<input type="text" placeholder="Enter Email" id="email" name="email"
required>
<button class="btn waves-effect waves-light teal lighten-1" type="submit"
name="submit" id="submit" value="submit">Submit<i class="material-icons
right">send</i></button>
</div>
</form>
</div>
And yes, I know, the form is open to SQL injection, I'll take care of that as soon as I can actually get the basic form to work!
Sorry, I know this will probably end up being some stupid fix, but I can't figure it out for the life of me...
Thanks everyone!
There is a SQL error in your code, try changing:
$query = mysqli_query($db, "INSERT INTO users (username, password,
email)VALUES ('$name', '$password', '$email')");
to
$query = mysqli_query($db, "INSERT INTO users (username, password,
email) VALUES ('$name', '$password', '$email')");

PHP sign in user after registration

I'm creating a simple login and registration form. What I'm trying to do is when a user registers, it should log them in. In order to get logged in, the user's ID that gets registered needs to be sent to the home page so the username can be displayed. I'm not sure what is wrong with my code.
Register:
<!DOCTYPE html>
<?php
session_start();
if(isset($_SESSION['userID']) AND !empty($_SESSION['userID'])) {
header("Location: home.php");
}
if(isset($_POST['register'])) {
$firstName = mysqli_real_escape_string($dbConnect, $_POST['firstName']);
$lastName = mysqli_real_escape_string($dbConnect, $_POST['lastName']);
$username = mysqli_real_escape_string($dbConnect, $_POST['username']);
$email = mysqli_real_escape_string($dbConnect, $_POST['email']);
$password = mysqli_real_escape_string($dbConnect, $_POST['password']);
{ // Check if data exists already in the database
$exists = mysqli_query($dbConnect, "SELECT user_id, username, email FROM users WHERE username = '$username' AND email = '$email'");
$row = mysqli_fetch_array($exists);
$dbusername = $row['username'];
$dbemail = $row['email'];
if ($username == $dbusername) {
die("Username already taken.");
} else if ($email == $dbemail) {
die("Email already registered.");
}
}
$registerUser = "INSERT INTO users (first_name, last_name, username, email, password) VALUES('$firstName', '$lastName', '$username', '$email', '$password')";
{ // Select ID from registered user
$selectID = "SELECT user_id FROM users WHERE username = '$username'";
$selectID_Query = mysqli_query($dbConnect, $selectID);
$fetch = mysqli_fetch_array($selectID_Query);
$userID = $fetch['user_id'];
$_SESSION['userID'] = $userID;
}
if(mysqli_query($dbConnect, $registerUser)) {
header("Location: home.php");
} else {
echo "<script>alert('error while registering you...');</script>";
}
}
include "includes/head.php";
include "includes/nav.php";
?>
<div id="main-content">
<div class="welcome-msg">
<h1 class="huge">Registration form</h1>
<h3 class="medium">Please fill in all the inputs</h3>
<form id="login-form" method="post">
<label for="firstName">First Name</label>
<input type="text" name="firstName" id="firstName" required>
<label for="lastName">Last Name</label>
<input type="text" name="lastName" id="lastName" required>
<label for="username">Username</label>
<input type="text" name="username" id="username" required>
<label for="email">Email</label>
<input type="email" name="email" id="email" required>
<label for="password">Password</label>
<input type="password" name="password" id="password" required>
<button type="submit" name="register">Register</button>
</form>
</div>
</div>
</body>
Home:
<!DOCTYPE html>
<html>
<?php
session_start();
if(!isset($_SESSION['userID'])) {
header("Location: index.php");
}
$tUsers_Select_Query = mysqli_query($dbConnect, "SELECT * FROM users WHERE user_id=".$_SESSION['userID']);
$row = mysqli_fetch_array($tUsers_Select_Query);
include "includes/head.php";
include "includes/nav.php";
?>
<div id="main-content">
<h1 class="huge">Welcome back, <?php echo $row['username'] ?>!</h1>
Logout
</div>
</body>
If you need any more details, please comment.
Try to Check first the value of your session $_SESSION['userID']. Have you tried checking it in your DOM ? session values must be displayed there.
All I had to use was the function mysqli_insert_id. In the if statement that checks if the SQL command is correct, I just had to add
$_SESSION['userID'] = mysqli_insert_id($dbConnect);
If the last SQL query was an UPDATE or an INSERT query, it would return the ID. If the query was SELECT for example, it would've returned 0.
$registerUser = "INSERT INTO users (first_name, last_name, username, email, password) VALUES('$firstName', '$lastName', '$username', '$email', '$password')";
if(mysqli_query($dbConnect, $registerUser)) {
$_SESSION['userID'] = mysqli_insert_id($dbConnect);
header("Location: home.php");
} else {
echo "<script>alert('error while registering you...');</script>";
}
http://php.net/manual/en/mysqli.insert-id.php

Checkbox variable causing error when NOT submitted in form PHP MYSQL

I have a PHP variable $admin which corresponds to a checkbox. When the form is submitted with the checkbox ticked, the value is passed (set as 1) and everything is fine, however if it's not ticked the variable causes an undefined index error:
Notice: Undefined index: admin in C:...\admin.php
This is the php section of the form that queries the db:
if($row == 1)
{
echo '<div id="errormsg">This username is already taken</div>';
}
else
{
$add = mysqli_query($dbcon, "INSERT INTO users (id, firstname, lastname, username, password, admin) VALUES
(null, '$fname', '$lname', '$user', '$pass', '$admin') ") or die ("Can't insert data");
echo '<div id="create-success">Successfully added user!</div>';
}
And the HTML form:
<form action="admin.php" method="post" onSubmit="return validate(this)">
<fieldset>
<label class="reg">Username *</label> <input type="text" name="user" /><br />
<label class="reg">Password *</label> <input type="password" name="pass" /><br />
<label class="reg">Repeat Password *</label> <input type="password" name="rpass" /><br />
<label class="reg">First name:</label> <input type="text" name="fname" /><br />
<label class="reg">Last name:</label> <input type="text" name="lname" /><br />
<label class="reg">Admin?:</label> <input type="checkbox" value="1" name="admin" /><br/>
</fieldset>
<input type="submit" name="submit" value="Create User" />
</form>
Ha anyone any ideas why NOT checking the box causes an error specific to the $admin variable?
Checkboxes are only actually passed to the script if they are checked.
So you need to check for there existance in your php code, something like this:
if ( $_POST && isset( $_POST['admin'] ) {
$admin = $_POST['admin'];
} else {
$admin = 0;
}
EDIT:
In your script I would do this
if($row == 1) {
echo '<div id="errormsg">This username is already taken</div>';
} else {
$admin = ( $_POST && isset( $_POST['admin'] ) ? $_POST['admin'] : 0;
$add = mysqli_query($dbcon, "INSERT INTO users
(id, firstname, lastname, username, password, admin)
VALUES(null, '$fname', '$lname', '$user', '$pass', '$admin') ") or die ("Can't insert data");
echo '<div id="create-success">Successfully added user!</div>';
}
First, you have to check is that admin variable in Post Array. Please check code.
<?php
if($row == 1)
{
echo '<div id="errormsg">This username is already taken</div>';
}
else
{
// check is exist in post array
$isAdminCheck = (isset($_POST['admin']) && $_POST['admin'] == 1 )? $_POST['admin']:0;
$add = mysqli_query($dbcon, "INSERT INTO users (id, firstname, lastname, username, password, admin) VALUES (null, '$fname', '$lname', '$user', '$pass', '$isAdminCheck') ") or die ("Can't insert data");
echo '<div id="create-success">Successfully added user!</div>';
}
?>

PHP register issues

I'd like to know if there are any errors/exploits in this piece of coding, and also can someone help me because I register but it doesn't insert data into the database. If there are any mistakes can you correct them please. I want it so if the username exists, redirect them to error?=1, and so on with passwords not matching. Any help is appreciated.
Register.php
<form action="register_acc.php" method="post">
<input type="text" name="username" class="input" value="" autocomplete="off" placeholder="Username" maxlength="25" /><br />
<br />
<input type="password" name="password" class="input" value="" autocomplete="off" placeholder="Password" maxlength="20" /><br />
<br />
<input type="password" name="password2" class="input" value="" autocomplete="off" placeholder="Password again" maxlength="20" /><br />
<br />
<input type="text" name="email" class="input" value="" autocomplete="off" placeholder="Email" maxlength="255" /><br />
<br />
<input type="submit" name="submit "class="submit" value="Sign up">
</form>
register_acc.php
<?php
error_reporting(1);
include 'site/inc/config.php';
if (isset($_POST['submit'])) {
session_start();
$username = $_POST['username'];
$password = md5($_POST['password']);
$pass_conf = md5($_POST['password2']);
$email = $_POST['email'];
$ip = $_SERVER['REMOTE_ADDR'];
$date= date("d-m-Y");
$q = "SELECT * FROM `users` WHERE username = '$username'";
$r = mysql_query($q);
if (empty($username)) {
header("Location: register.php?error=1");
exit;
}
if ($password != $pass_conf) {
header("Location: /site/register.php?error=2");
exit;
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: /site/register.php?error=3");
exit;
}
if (mysql_num_rows($r) == 0) {
// Continue w/ registration, username is available!
$query = "INSERT INTO `users` (id, username, password, email, ip, rank, reg_date)
VALUES (0, '$username', '$password', '$email', '$ip', 1, '$date'())";
$run = mysql_query($query);
header("Location: /site/register.php?succsess=1");
}
}
else {
header("Location: register.php?error=4");
}
?>
You don't concatenate the $username variable into the query.
Try this:
"SELECT * FROM `users` WHERE username = '".$username."'"
Also your INSERT query looks a bit weird with the date() function. Try this:
$date = date("Y-m-d");
"INSERT INTO `users` (id, username, password, email, ip, rank, reg_date)
VALUES (0, '$username', '$password', '$email', '$ip', 1, '".$date."')"
EDIT: SCRIPT EXAMPLE
<?php
if(!isset($_POST['username'])||!isset($_POST['email'])||!isset($_POST['password']))//enter more values if necessary
{
header("Location: error_page.php?error=1");
}
else
{
//do whatever, eg execute query
}
?>

Categories