Data not inserting into database when using pdo - php

i am learning pdo and i tried to play with CRUD method. I am trying to insert data into database using pdo but it isn't inserting. Below is my code
<?php
$username = $_POST['username'];
$password = password_hash($_POST['password'], PASSWORD_BCRYPT ));
try {
$query = $connect->prepare("INSERT INTO users(username, password) VALUES(?,?)");
$query->execute(array($username, $password));
echo "data";
}
catch (PDOException $event) {
echo $event->getMessage();
}
?>
i have this index file named as index.php
<?php
require_once 'db.php';
session_start();
session_regenerate_id();
?>
<!DOCTYPE html>
<html>
<head>
<title>Sign-Up/Login Form</title>
</head>
<?php
if ($_SERVER['REQUEST_METHOD'] == '$_POST') {
if (isset($_POST['login'])) {
require 'login.php';
}
elseif (isset($_POST['register'])) {
require 'register.php';
}
}
?>
<body>
<form action="index.php" method="POST">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" name="register" value="Submit">
</form>
</body>
</html>
my db.php looks like
<?php
try {
$connect = new PDO('mysql:dbname=pdologin;host=localhost', 'root', '$$$$');
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $event) {
$event->getMessage();
}
?>

The problem is that your code never reaches your require scripts (login.php or register.php) because your conditional is incorrect.
You have: if ($_SERVER['REQUEST_METHOD'] == '$_POST')
It should be if ($_SERVER['REQUEST_METHOD'] == 'POST')

You're going to end up with something like below while learning or doing some small script that will need a connection, in the long run wrapping this stuff in a function or using a small helper or framework can make this a little easy. Great idea to learn but its still tedious boiler plate no matter how many years you write this stuff.
<?php
//db settings that are typically in a config somewhere
$db_servername = "localhost";
$db_username = "username for your database";
$db_password = "password for your database";
$db_name = "your_db_name";
try {
$connect = new PDO("mysql:host=$db_servername;dbname=$db_name, $db_username, $db_password");
// set the PDO error mode to exception
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo "Connected successfully";
}catch(PDOException $e){
//echo "Connection failed: " . $e->getMessage();
}
$sth = $connect->prepare("INSERT INTO users(username, password) VALUES(:username,:password)");
$username = $_POST['username'];
$password = password_hash($_POST['password'], PASSWORD_BCRYPT );
$sth->bindValue(':username', $username, PDO::PARAM_STR);
$sth->bindValue(':password', $password, PDO::PARAM_STR);
$sth->execute();
as a example my team now just writes database binding code like
<?php
//array of ids to insert
$binds['ids'] = array(1,3,4,5,6,7,9,08098);
//Database class is auto included with every script
$success = Database::query('insert into my_table (id) values(:ids)',$binds);

connect first
$connect = mysqli_connect("localhost","root","root","my_db");
then remove the parameters when executing
$query->execute();
try this
<?php
$connect = mysqli_connect("localhost","root","root","my_db");
$username = $_POST['username'];
$password = password_hash($_POST['password'], PASSWORD_BCRYPT );
try {
$query = $connect->prepare("INSERT INTO users(username, password) VALUES('$username', '$password')");
$query->execute();
}
catch (PDOException $e) {
echo $e->getMessage();
}
?>

Related

Code to submit data from login page to MySQL database

I have created a simple HTML Login page.
I have created a PHP file to transfer data to MySQL database(Using MySQL workbench 8.0)
However, when I click submit, a page just open with some code from my PHP file and no data is transferred to my database.
How can I transfer data from my Login page to my MYSQL database?
I have saved my PHP file in the C://
Code for Login Page:
<html>
<head>
<title>Login</title>
</head>
<body>
<form action="/Test1.php">
Username:<br>
<input type="text" value="username"><br>
Password:<br>
<input type="text" value="password"><br>
<input type="submit" value="submit"><br>
</form>
</body>
</html>
CODE for PHP:
<html>
<? php
$username = filter_input(INPUT_POST, 'username');
$password = filter_input(INPUT_POST, 'password');
if (!empty($username)){
if (!empty($password)){
$host = "localhost:3306";
$dbusername = "root";
$dbpassword = "";
$dbname = "login";
// Create Connection
$conn = new mysqli ($host, $dbusername, $dbpassword, $dbname);
if (mysql_connect_error()){
die ( 'Connect Error ('.mysqli_connect_errno().')'.mysqli_connect_error());
}
else {
$sql = "INSERT INTO login.user (username, password)
values ('$username', '$password')";
if ($conn->query($sql)){
echo "New record is inserted successfully";
}
else {
echo "Error:".$sql."<br>".$conn->error;
}
$conn->close();
}
}
else {
echo "Password should not be empty";
die ();
}
else {
echo "Username should not be empty";
die();
}
?>
</html>
I expect data from HTML file to be inputed in MYSQL Database but instead a new page open up with this:
query($sql)){ echo "New record is inserted successfully"; } else { echo "Error:".$sql."
".$conn->error; } $conn->close(); } } else { echo "Password should not be empty"; die (); } else { echo "Username should not be empty"; die(); } ?>
Try this:
<html>
<?php
$username = filter_input(INPUT_POST, 'username');
$password = filter_input(INPUT_POST, 'password');
if (empty($username)) {
echo 'Username should not be empty';
exit;
}
if (empty($password)) {
echo 'Password should not be empty';
exit;
}
$host = 'localhost:3306';
$dbusername = '';
$dbpassword = '';
$dbname = '';
// Create Connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
$connection = new mysqli($host, $dbusername, $dbpassword, $dbname);
} catch (Exception $exception) {
exit('Error connecting to database');
}
$connection->set_charset('utf8mb4');
try {
$statement = $connection->prepare("INSERT INTO login.user (username, password) values (?, ?)");
$statement->bind_param('ss', $username, $password);
$statement->execute();
$statement->close();
echo 'New record is inserted successfully';
} catch (Exception $exception) {
echo 'Error: ' . $exception->getMessage();
}
$connection->close();
?>
</html>

Entering $_POST into html form is causing 403 Forbidden error

I have done comment section on my website:
<form method="post" name="dodawanieKomentarzy">
<div>Your Name:</div>
<div><input type="text" name="autor" required></div>
<div>Message:</div>
<div><textarea name="komentarz" required></textarea></div>
<div><input type="submit" value="Add comment" name="Dodaj"></div>
</form>
and PHP:
<?php
$pdo=new PDO('mysql:host=localhost;dbname=my_dbase_name',
'my_dbase_login','my_dbase_passw',[PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4"]
);
if(isset($_POST['Dodaj'])) {
$data=strftime("%Y-%m-%d %X");
$pdo->prepare("INSERT INTO komentarze VALUES (NULL,?,?,?,'')")->execute([$data,$_POST['autor'],$_POST['komentarz']]);
};
?>
Everything works (I can insert normal text (for example :'This is comment'), but when I insert for example: '$_POST' to text field, I've got 403 Forbidden error.
I don't see what is wrong with the code, so I would appreciate if you could help me out.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
if(isset($_POST['Dodaj'])) {
try {
$pdo=new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$data=strftime("%Y-%m-%d %X");
$author = $_POST['autor'];
$komentarz = $_POST['komentarz'];
$insert_query = $pdo->prepare("INSERT INTO komentarze (`autor`,`komentarz`) VALUES ('".$author."', '".$komentarz."' )");
$insert_query->execute();
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $insert_query . "<br>" . $e->getMessage();
}
}
?>
I hope this will work for you
You can try with variable like: $author= $_POST['autor']; $text = $_POST['komentarz']; then use $author and $text both to your query.

PHP is not sending values to database using a simple form

Hello I am using PHPStorm and I am trying to send data to my database using php.
When the form is submitted my database creates a new id which is set to auto-increment but the values are empty!
This is my html form in a file called create_account.php
<!DOCTYPE>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>NABI| Find the perfect music teach today!</title>
<link rel="stylesheet" href="css/normalize.css">
<meta name="viewport" content="width=device-width, initial-scale =1.0, user-scalable=no">
</head>
<body>
<form method="post" action="info.php">
<input type="text" name="name" id="name">
<input type="submit" value="send">
</form>
</body>
</html>
Here is my info.php file
<?php
$host = "localhost";
$user = "root";
$db = "nabi_data";
$pass = "";
$name = filter_input(INPUT_POST, 'name');
try {
$conn = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO just_name (name)
VALUES ('$name')";
// 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;
?>
This is how my database table looks like
just_name
If you put an echo, Does It return the name value?
....
Try to get name field content with $_POST['name'];
To avoid the "undefined index" error, you may want to do something like this:
if ($_POST and !empty($_POST['name'])) {
$host = "localhost";
$user = "root";
$db = "nabi_data";
$pass = "";
$name = filter_input(INPUT_POST, 'name');
// debugging step to check to see what you're getting back from the filter_input call (or write it to a log)
var_dump($name); exit;
if ($name != '') {
try {
$conn = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO just_name (name) VALUES ('$name')";
$conn->exec($sql);
echo "New record created successfully";
} catch (PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
}
else {
// filtered name was blank; raise an error and/or redirect them to create_account.php
}
$conn = null;
}
else {
// handle this case; maybe just redirect back to create_account.php
}
The biggest key is to check that "name" exists in the $_POST (also accessible through the $_REQUEST global variable); you can do that through isset() or empty().
(And yes, as others have suggested, checking the value you get in $name after the filter_input call would be a great thing to verify if you haven't already.)
"Thank you #Parene but this is what I get when I set $name = $_POST['name']; ---Notice: Undefined index: name in C:\Users\Vanessa\PhpstormProjects\nabi\info.php on line 6--- – Vanessa Charles 5 mins ago"
$name = filter_input(INPUT_POST, 'name'); you're getting undefined index because you're not checking if it's empty or not.
You need to use a conditional statement for it while checking if it's "empty".
$name = filter_input(INPUT_POST, 'name');
if(!empty($name)){
// do something as in "enter" it in the database
$name = $name;
$sql = "INSERT INTO just_name (name)
VALUES ('$name')";
// ... rest of your query here
}
Edit:
Modify your code to read as this and copy/paste it exactly as show and reload it while clearing your cache.
I also added ticks to the name column, sometimes that helps.
<?php
$host = "localhost";
$user = "root";
$db = "nabi_data";
$pass = "";
if(!empty($_POST['name'])){
$name = $_POST['name'];
}
else {
echo "Something went wrong.";
}
try {
$conn = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO just_name (`name`) VALUES ('$name')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
A prepared statement should be used for this though.
http://php.net/pdo.prepared-statements
I.e. as a prepared statement:
<?php
$host = "localhost";
$user = "root";
$db = "nabi_data";
$pass = "";
if(!empty($_POST['name'])){
$name = $_POST['name'];
}
else {
echo "Something went wrong.";
}
try {
$conn = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("INSERT INTO just_name (`name`) VALUES (:name)");
$stmt->bindParam(':name', $name);
$stmt->execute();
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
The issue is you're using PhpStorm built-in web server which has issues with POST.
As of PHP 5.4.0, the CLI SAPI provides a built-in web server, try using that by selecting "PHP Built-in Web Server" type of Run/Debug Configuration.
Or try this manually:
cd ~/www/your_project
php -S localhost:8000
Here's the manual page

OOP PHP Login/Register System

I'm busy with learning OOP PHP and my goal is to make a simple login/register system for users. The idea is to simply register your first name, last name and password, that would be stored into a MySQL database.
Right now i'm trying to store some data into the database, but I'm stuck.. I can't get any data stored into my database. Here is the code I'm working on:
register.php :
<?php
error_reporting(E_ALL);
require_once 'inc/user.php';
$user = new User();
if(isset($_POST['register'])) {
$firstname = ($_POST['firstname']);
$lastname = ($_POST['lastname']);
$password = ($_POST['password']);
$email = ($_POST['email']);
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title> Project Hour </title>
<script src="js/script.js"></script>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<div class="logo">
<img src="img/logo.png">
</div>
<div class="login">
<div class="form">
<form method="POST" action="#" class="register-form">
<input type="text" name="firstname" placeholder="voornaam"/>
<input type="text" name="lastname" placeholder="achternaam"/>
<input type="password" name="password" placeholder="************"/>
<input type="text" name="email" placeholder="emailadres"/>
<button type="submit" name="register">create</button>
<p class="message"> Al geregistreerd? Inloggen </p>
</form>
</div>
user.php :
<?php
error_reporting(E_ALL);
require_once 'connect.php';
class User {
private $dbase;
public function __constructor() {
$this->dbase = new Connect();
$this->dbase = $this->dbase->dbConnect();
}
public function userRegiser($firstname, $lastname, $password, $email) {
try {
$st = $dbase->prepare("INSERT INTO users(firstname, lastname, password, email) VALUES (:firstname, :lastname, :password, :email)");
$st->bindparam(":firstname", $firstname);
$st->bindparam(":lastname", $lastname);
$st->bindparam(":password", $password);
$st->bindparam(":email", $email);
if($st->execute()) {
echo 'Inserted successfully.';
}
} catch (PDOException $e) {
echo 'Something failed :' . $e->getMessage;
}
}
}
?>
connect.php
<?php
class Connect {
public function dbConnect() {
$user = "root";
$pass = "";
$pdo = 'mysql:host=localhost;dbname=projecthour';
try {
$db = new PDO($pdo, $user, $pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed : ' . $e->getMessage();
}
}
}
?>
There are several errors I see here.
First - when form submitted and you have user data - you should call userRegister method:
if(isset($_POST['register'])) {
$firstname = ($_POST['firstname']);
$lastname = ($_POST['lastname']);
$password = ($_POST['password']);
$email = ($_POST['email']);
$user->userRegister($firstname, $lastname, $password, $email);
}
Next problem is
$this->dbase = $this->dbase->dbConnect();
So here $this->dbase is equals to something that is returned by dbConnect method. But this method returns nothing. But it should return PDO instance:
public function dbConnect() {
$user = "root";
$pass = "";
$pdo = 'mysql:host=localhost;dbname=projecthour';
try {
$db = new PDO($pdo, $user, $pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// here, return new PDO instance
return $db;
} catch (PDOException $e) {
echo 'Connection failed : ' . $e->getMessage();
}
}
And finally, your userRegiser (by the way it should be userRegis**t**er) method uses $dbase. But $dbase is not what you expect it to be. It's just a local variable, but you need a class property:
public function userRegiser($firstname, $lastname, $password, $email) {
try {
$st = $this->dbase->prepare("INSERT INTO users(firstname, lastname, password, email) VALUES (:firstname, :lastname, :password, :email)");
// ^ here
And thanks to #RajdeepPaul: constructor definition should be:
public function __construct() { // not __constructor!
if(!empty($_POST)) {
$firstname = ($_POST['firstname']);
$lastname = ($_POST['lastname']);
$password = ($_POST['password']);
$email = ($_POST['email']);
// call userRegiser
echo $user->userRegiser($firstname, $lastname, $password, $email);
}
and in User.php
public function userRegiser($firstname, $lastname, $password, $email) {
try {
$st = $dbase->prepare("INSERT INTO users(firstname, lastname, password, email) VALUES (:firstname, :lastname, :password, :email)");
$st->bindparam(":firstname", $firstname);
$st->bindparam(":lastname", $lastname);
$st->bindparam(":password", $password);
$st->bindparam(":email", $email);
if($st->execute()) {
return 'Inserted successfully.';
}
} catch (PDOException $e) {
return 'Something failed :' . $e->getMessage;
}
}

PDO connection class prepare error

I got my connection class in a different folder core/connect.php, it's giving me this error and i dont know how to fix it? sorry for the newb question.
Fatal error: Call to a member function prepare() on a non-object in C:\wamp\www\register.php on line 11
<?php
function dbconnect(){
try{
$username = 'root';
$password = '';
$pdo = new PDO("mysql:host=localhost;dbname=lr;", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
echo 'ERROR',$e->getMessage();
}
}
?>
register.php
<form method="POST">
<input type="text" name="username"><br/>
<input type="password" name="password"><br />
<input type="submit">
</form>
<?php
if(isset($_POST['username'], $_POST['password'])){
require 'core/connect.php';
$query = dbconnect()->prepare('INSERT INTO `users` (username, password) VALUES (?, ?)');
$query->bindParam(1, $_POST['username']);
$query->bindParam(2, $_POST['password']);
$query->execute();
}
?>
Try this:
<?php
function dbconnect(){
try{
$username = 'root';
$password = '';
$pdo = new PDO("mysql:host=localhost;dbname=lr;", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
} catch(PDOException $e){
echo 'ERROR',$e->getMessage();
}
}
?>
Make sure you include connect.php in register.php or are using an autoloader etc.

Categories