PDO connection class prepare error - php

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.

Related

Insert Into with PDO

I new with PHP, MySQL and PDO.
With a lot of search, I made this piece of code to insert a new user/customer with a password.
<?php
require_once '../../src/mysql/dbconfig.php';
try
{
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
echo "Connected to $dbname at $host successfully.";
}
catch (PDOException $pe)
{
die("Could not connect to the database $dbname :" . $pe->getMessage());
}
$stmt = $conn -> prepare($sql);
$email = $_POST['email'];
$password = $_POST['password'];
$stmt -> bindValue(":email", $email);
$stmt -> bindValue(":password", $password);
$sql = "INSERT INTO customer (email, password) VALUES (:email, SHA2(:password,512))";
$stmt -> execute();
$conn = null;
?>
<html>
<body>
Welcome <?php echo $_POST["email"]; ?><br>
Your password is: <?php echo $_POST["password"]; ?>
</body>
</html>
When I submit, go to another PHP page, say the user's email and password.
So when I do SELECT * FROM, I receive an empty SET.
(Basically, the Insert is not working, but on the PHP page, it says the information that was inserted in the INSERT)
What am I doing wrong?
Basically, what I was doing wrong was calling a statement after its values.
<?php
require_once '../../src/mysql/dbconfig.php';
try
{
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
echo "Connected to $dbname at $host successfully.";
}
catch (PDOException $pe)
{
die("Could not connect to the database $dbname :" . $pe->getMessage());
}
$sql = "INSERT INTO customer (email, password) VALUES (:email, SHA2(:password,512))";
$stmt = $conn -> prepare($sql);
$email = $_POST['email'];
$password = $_POST['password'];
$stmt -> bindValue(":email", $email);
$stmt -> bindValue(":password", $password);
$stmt -> execute();
$conn = null;
?>

Data not inserting into database when using pdo

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

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.

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;
}
}

SQL INSERT TROUBLE

I'm sitting infront of this code for 2 hours i cant figure out whats wrong :(
I've been trying to have a html form which calls the php function to insert the information from the form into the database but for some reason does not work :/
here is my form code :
<?php include 'connection.php'; ?>
<html>
<body>
<form action="user_create.php" method="POST">
username: <input type="text" name="username"/>
password: <input type="text" name="password"/>
email: <input type="text" name="email"/>
<input type="submit" name='submit' value="user_create"/>
</form>
</body>
</html>
database connection
<?php
//Connecting databases
$localhost = "";
$dbuser = "";
$dbpass = "m";
$dbname = "";
$connect = mysql_connect($localhost, $dbuser, $dbpass);
mysql_select_db("$dbname", $connect);
?>
my php function
<?php include 'connection.php';?>
<?php
if (isset($_POST['submit']))
{
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$query = mysql_query("INSERT INTO users( username,password,email,type)
VALUES ('$username', '$password', '$email','1')");
mysql_query($query);
echo '<script type="text/javascript">alert("You have been registered");</script>';
}
else
{
echo '<script type="text/javascript">alert("jo");</script>';
}
?>
You should use PHP-PDO in order to avoid from SQL Injection attacks also it will fix insert trouble too.
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'username';
/*** mysql password ***/
$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=animals", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database<br />';
/*** INSERT data ***/
$sql = "INSERT INTO users(username,
password,
email,
type) VALUES (
:username,
:password,
:email,
:type)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':username', $_POST['username'], PDO::PARAM_STR);
$stmt->bindParam(':password', $_POST['password'], PDO::PARAM_STR);
$stmt->bindParam(':email', $_POST['email'], PDO::PARAM_STR);
$stmt->bindParam(':type', $_POST['type'], PDO::PARAM_INT);
$stmt->execute();
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
Are you connecting properly?
$dbuser = "";
Maybe must be "root" or other user?
Check this part :
//Connecting databases
$localhost = "";
$dbuser = "";
$dbpass = "m";
$dbname = "";

Categories