Database insert not working (MySQL, PHP) - php

I have this PHP that basically is being used for inserting an email and password into an SQL database:
<?php
error_reporting(E_ALL ^ E_STRICT);
require "database.php";
$message = '';
if (!empty($_POST["email"]) &&!empty($_POST["password"])):
//Enter the new user in the database
$sql = "INSERT INTO users (email, password) VALUES (:email, :password)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":email", $_POST['email']);
$stmt->bindParam(":password", password_hash($_POST['password'], PASSWORD_BCRYPT));
if ($stmt->execute() ):
$message = 'Successfully created a new user';
else:
$message = 'Sorry there must have been an issue whilst registering';
endif;
endif;
?>
Here is the form:
<div class="jumbotron" id="jumbotron-6">
<div class="container text-center">
<?php if (!empty($message)):
?>
<h3 id="h3message"><?= $message ?> </h3>
<?php endif; ?>
<form action="signup.php" method="POST">
<input type="text" placeholder="enter your email" name="email">
<input type="password" placeholder="and password" name="password">
<input type="password" placeholder="confirm password" name="confirm_password">
<input type="submit">
</form>
</div>
</div>
It doesn't insert into the database (all the fields, variables are correct i think - just email and password) and it comes back with the error message that I created that says 'Sorry there must have been an issue whilst registering'
Here is the database.php file
<?php
$server = 'localhost';
$username = "root";
$password = "";
$database = "auth";
try{
$conn = new PDO ("mysql:host={$server};dbname={$database};" , $username, $password);
}
catch (PDOException $e) {
die ( "Connection failed; " . $e->getMessage());
}
?>

Hash the password before you bind it:
$UserPWHash = password_hash($_POST['password'], PASSWORD_BCRYPT);
$stmt->bindParam(":password", $UserPWHash));

Related

Insert into sql table with php from html form

I am trying to insert into my table (courses) in my sql database. But when I run my code (by clicking submit) I get this error:
I am no longer getting an error, I get the message:
New course created successfully
But when I check the database, the course has not been added
This is my code:
<?php
if (isset($_POST['submit'])) {
try {
require "../config.php";
require "../common.php";
$connection = new PDO($dsn, $username, $password);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO course (courseName, cDescription, programID, programYear, credit)
VALUES (:courseName, :cDescription, :programID, :programYear, :credit)";
$courseName = $_POST['courseName'];
$cDescription = $_POST['cDescription'];
$programID = $_POST['programID'];
$programYear = $_POST['programYear'];
$credit = $_POST['credit'];
$statement = $connection->prepare($sql);
$statement->bindParam(':courseName', $courseName, PDO::PARAM_STR);
$statement->bindParam(':cDescription', $cDescription, PDO::PARAM_STR);
$statement->bindParam(':programID', $programID, PDO::PARAM_STR);
$statement->bindParam(':programYear', $programYear, PDO::PARAM_STR);
$statement->bindParam(':credit', $credit, PDO::PARAM_STR);
$connection->exec($statement);
echo "New course created successfully";
} catch(PDOException $error) {
echo $statement. "<br>" . $error->getMessage();
}
}
?>
<?php include "templates/header.php"; ?>
<h2>Add a course</h2>
<form method="post">
<label for="courseName">Course Name:</label>
<input type="text" name="courseName" id="courseName" required>
<label for="cDescription">Course Description:</label>
<input type="text" name="cDescription" id="cDescription" size="40" required>
<label for="programID">Program ID:</label>
<input type="number" name="programID" id="programID" required>
<label for="programYear">Program Year:</label>
<input type="number" name="programYear" id="programYear" required>
<label for="credit">credit:</label>
<input type="number" name="credit" id="credit" required>
<input type="submit" name="submit" value="Submit">
</form>
Back to home
<?php include "templates/footer.php"; ?>
To try and see what was wrong, I tried simplifying this to, which works
<?php
if (isset($_POST['submit'])) {
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "courseselector";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO course (courseName, cDescription, programID, programYear, credit)
VALUES ('courseName', 'cDescription', 1, 4, 1)";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
?>
<?php include "templates/header.php"; ?>
<h2>Add a course</h2>
<form method="post">
<input type="submit" name="submit" value="Submit">
</form>
Back to home
<?php include "templates/footer.php"; ?>
I was missing
$statement->execute();
Above
$connection->exec($statement);

Someone can check my session?

Please someone can check whether my session is working or not.
I am not sure as i am still beginner.
login.php is the main page for user to login the username and password :
<body>
<form action="" method="post">
<div class="imgcontainer">
<img src="KBR2xN6.jpg" alt="Avatar" class="avatar">
</div>
<div class="container">
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="name" required>
<br />
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="pass" required>
<button type="submit">Login</button>
<button type="reset" class="cancelbtn">Reset</button>
</div>
</form>
</body>
As for connections.php is to connect to the local server :
$host = "localhost";
$username = "root";
$password = "";
$database = "netbook 1 malaysia";
try {
$connect = new PDO("mysql:host=$host; dbname=$database", $username, $password);
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $ex) {
echo 'Connection Failed : '.$ex->getMessage();
}
As for session.php i am not sure:
session_start();
include('connections.php');
$username = $_POST['name'];
$password = $_POST['pass'];
$sql = "SELECT * FROM pengguna WHERE username = '$username' AND password = '$password'";
$result = $connect->query($sql);
if($result->rowcount()>0){
foreach($result AS $data){
$_SESSION['name'] = $data['name'];
$_SESSION['pass'] = $data['pass'];
echo "<script>alert('Login Success');
window.location.href='view.php';
</script>";
}
}
else {
echo "<script>alert('Login Failed');
window.location.href='login.php';
</script>";
}
Check for me please.
Just add this code to your view.php file.
session_start();
print_r($_SESSION);
If it prints values you saved in session then its working.

$stmt -> execute() returning false

I've tried debuggind this issue for almost 4 hours with no luck. No error messages, $stmt -> execute() gives false for whatever reason that I do not know of.
register.php
<?php
session_start();
if( isset($_SESSION['id'])){
header("Location: index.php");
}
require 'database.php';
$message = '';
if(!empty($_POST['user']) && !empty($_POST['password'])):
$pass = $_POST['password'];
$user = $_POST['user'];
$sql = "Insert into user (username, password) values (:user, :password)";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':user', $_POST['user']);
$stmt->bindValue(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));
//var_dump($_POST['password']);
//var_dump($_POST['user']);
if($stmt -> execute()):
$message = 'Successfully created new user';
else:
$message = 'Sorry there must have been an issue creating your account';
endif;
endif;
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Register Below</title>
</head>
<body>
<?php if(!empty($message)): ?>
<p><?= $message ?></p>
<?php endif; ?>
<h1>Register</h1>
<form class="" action="register.php" method="post">
<input type="text" placeholder="Username" name="user" id="user">
<input type="password" placeholder="and password" name="password" id="password">
<input type="password" placeholder="confirm password" name="confirm_password">
<button type="submit" name="button">Register</button>
</form>
home
</body>
</html>
database.php
<?php
$server = 'localhost';
$username ='master';
$password ='master';
$database = 'quiz';
try{
$conn = new PDO("mysql:host=$server;dbname=$database;" , $username, $password);
} catch(PDOException $e){
die ("Connection failed" . $e->getMessage());
}
?>
I know I am ignoring the confirm password, but I want to make sure I can insert into the database first.
Solution: my password length was 15 in my database... hashed password >> 15 characters. Changed the length to 255 and it's all good. Hopefully this will be useful for someone else.

Storing data entered when signing up

I need to create a sign up page that will store user name email passwords and put them in a database so that the user can then login and access a profile etc.
I have made a database database however nothing will go into it. I input one manually but anything I try to do from the webpage won't go to the database.
Code for the webpage: Signup is the page I want displayed and adduser is the code for adding the data to the database.
Signup:
<?php include '../view/header.php';
?>
<br>
<br>
<h1 class="light white-text text-lighten-3">Sign up!</h1>
<br>
<br>
<form class="form" id="signup" action="addUser.php" method="post">
<div class="form-group ">
<label for="email">Email</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter Your Email">
</div>
<br>
<div class="form-group ">
<input id="user_name" type="text" class="validate" name="user_name"required="required">
<label for="user_name">User Name</label>
</div>
<br>
<div class="form-group col s6">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password" placeholder="Enter a Password">
</div>
<br>
<br>
<button type="submit" class="orange btn btn-primary">Submit</button>
</form>
<?php
include '../view/footer.php';
AddUser:
<script src="../js/materialize.js" type="text/javascript"></script>
<script src="../js/materialize.min.js" type="text/javascript"></script>
<script src="../js/init.js" type="text/javascript"></script>
<?php
$server = "localhost";
$username = 'root';
$Password ="";
$database = 'commish';
$con = mysqli_connect($server, $username, $Password, $database);
$email = filter_input(INPUT_POST, 'email');
$user_name = filter_input(INPUT_POST, 'user_name');
$password = filter_input(INPUT_POST, 'password');
new_user( $user_name, $password,$email, $con);
function new_user($user_name, $password, $email,$con)
{
global $con;
$query = "INSERT into users (user_name, password, email) VALUES (:user_name, :password, :email)";
$statement = $con->prepare($query);
$statement->bindValue(":user_name", $user_name);
$statement->bindValue(":password", $password);
$statement->bindValue(":email", $email);
$statement->execute();
echo 'Successfully created new user';
}
There's no bindValue() method in mysqli, PDO has. So here are the two approaches to solve your problem:
1)mysqli method:
Use bind_param() method to bind variables to your prepared statement. So your new_user() function should be like this:
function new_user($user_name, $password, $email,$con){
$query = "INSERT into users (user_name, password, email) VALUES (?, ?, ?)";
$statement = $con->prepare($query);
$statement->bind_param("sss", $user_name, $password, $email);
if($statement->execute()){
echo 'Successfully created new user';
}else{
// query failed
}
}
NOTE: Since you're passing the connection handler $con to this function, there's no need to use global $con;. Plus Globals are evil.
2)PDO method:
Keep your new_user() function as it is and change this line
$con = mysqli_connect($server, $username, $Password, $database);
to
$con = new PDO("mysql:host=$server;dbname=$database",$username,$Password);
Sidenote: Never store password as a plain readable text, always perform salted password hashing on raw password before inserting it into the table.
There's no bindValue() method in mysqli, you should use bind_param()
new_user function :
function new_user ($user_name, $password, $email)
{
global $con;
$stmt = $con->prepare("INSERT into users (user_name, password, email) VALUES (?,?,?)";
$stmt->bind_param("sss", $user_name, $password, $email);
$stmt->execute();
$stmt_error = $stmt->error;
$stmt->close();
if ($stmt_error)
echo 'Error on create new user: '.$stmt_error;
else
echo 'Successfully created a new user';
}

Cannot insert into table. PHP/MySQL

I have a table named 'Directors' in the database 'db2'.
I have an HTML form. I would like when I insert the values and hit submit button, to insert the content into the table in a new row (to INSERT INTO), after it makes some validations (you'll notice them in the script). I've tried to do it by myself, but it is always echoing me 'Fail';
This is my HTML form:
<form action="process.php" method="post" accept-charset="utf-8">
<input type="hidden" name="pages_edit_nonce" />
<div class="section-item page-title-section">
<label for="title">Full Name:</label><span class="help">*</span><div class="input-wrap"><input type="text" name="name" value="" /></div> </div>
<div class="section-item">
<label for="label">Phone:</label><span class="help">*Optionally</span><div class="input-wrap"><input type="text" name="phone" value="" /></div> </div>
<div class="section-item">
<label for="redirect">Е-mail:</label><span class="help">*</span><div class="input-wrap"><input type="text" name="email" value="" placeholder="" /></div> </div>
<div class="section-item">
<label for="redirect">School:</label><span class="help">*</span><div class="input-wrap"><input type="text" name="school" value="" placeholder="" /></div> </div>
<div class="section-item">
<label for="redirect">City:</label><span class="help">*</span><div class="input-wrap"><input type="text" name="city" value="" placeholder="" /></div> </div>
<div class="section-item">
<label for="redirect">Password:</label><span class="help">*</span><div class="input-wrap"><input type="password" name="password" value="" placeholder="" /></div> </div>
<div class="admin-bar">
<div class="admin-bar-inner">
<input type="submit" value="Submit" class="btn" />
</div>
</div>
</form>
This is my process.php file:
$server = "localhost";
$user = "****";
$pass = "****";
$conn = mysql_connect($server, $user, $pass);
$db = mysql_select_db("****", $conn);
session_start();
if(!$db) {
$_SESSION['ERRMSG'] = "<strong>Error:</strong> The access to the database is denied!";
header("Location: ../../admin/error/");
exit();
}
session_start();
function UniqueID() {
$UID = rand(); //Create unique ID
$check = mysql_query("SELECT * FROM `Directors` WHERE `UID` = '$UID'");
if(mysql_num_rows($check) > 0) { //Check if it exists
UniqueID(); //Redo the function
} else {
return $UID; //return the uniqueid
}
}
$UID = UniqueID(); //Unique ID
$email = $_POST['email'];
$password = $_POST['password'];
$name = $_POST['name'];
$phone = $_POST['phone'];
$school = $_POST['school'];
$city = $_POST['city'];
//Create INSERT query
$qry = "INSERT INTO `oclass`.`Directors`(`UID`,`Name`, `Phone`, `Email`, `SchoolGymnasium`, `City`, `Password`) VALUES('$UID','$name','$phone','$email','$school','$city','" . md5($password) . "')";
$result = mysql_query($qry);
//Check whether the query was successful or not
if($result) {
$_SESSION['SUCCMSGADDDIR'] = 'Sucessful.';
header("location: URL");
exit();
} else {
$_SESSION['ERRMSGADDDIR'] = 'Fail';
header("location: URL");
}
After changing the error session with mysql_error() it gave me the following error:
Fatal error: Can't use function return value in write context in ... on line 10;
Line 10 is:
mysql_error() = "<strong>Error:</strong> The access to the database is denied!";
I've removed the column named ID (which was Primary Key) and set UID column as Primary Key, and now is working. Thank you guys.
Firstly you must have never heard of SQL injection http://en.wikipedia.org/wiki/SQL_injection. Your current code is opening you up for attacks. You can't directly insert user input into the database like you're doing. Also mysql_* functions are deprecated. To help your code be safer and more update try something like this:
session_start();
$host = "localhost";
$user = "****";
$pass = "****";
$db = "****";
$dbh = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("INSERT INTO `oclass`.`Directors`(`UID`,`Name`, `Phone`, `Email`, `SchoolGymnasium`, `City`, `Password`) VALUES (:uid, :name, :phone, :email, :school, :city, :password)");
$stmt->bindParam(':uid', uniqid());
$stmt->bindParam(':name', $_POST['name']);
$stmt->bindParam(':phone', $_POST['phone']);
$stmt->bindParam(':email', $_POST['email']);
$stmt->bindParam(':school', $_POST['school']);
$stmt->bindParam(':city', $_POST['city']);
$stmt->bindParam(':password', md5($_POST['password']));
$stmt->execute();

Categories