Registration with PDO/PHP doesn't work - php

I've got a problem through build a registration system. I don't know where is the problem, because I'm a beginner in PHP OOP.
Here's my registration class:
<?php
/*
*=======================
* REGISTRATION CLASS !!!
* ======================
*/
include_once '/../core/registration.php';
include_once '/../core/db_connect.php';
class registration {
private $db;
function __construct() { /* Connecting with MySQL */
$this->db = new db_connect();
$this->db = $this->db->connect();
} /* End of connection */
function registration($username, $password1, $password2, $email, $date) {
if(!empty($username) && !empty($password1) && !empty($password2) && !empty($email)) {
$q = $this->db->prepare("INSERT INTO users(username, password, email, date, logged, admin) VALUES (?, ?, ?, ?, ?, ?)");
$q->bindParam(1, $username);
$q->bindParam(2, $password1);
$q->bindParam(3, $email);
$q->bindParam(4, $date);
$q->bindParam(5, '0');
$q->bindParam(6, '0');
$q->execute();
}
}
}
?>
Here is a file, that is running, when user clicks on 'register' button:
<?php
include_once '/../classes/registration.php';
if(isset($_POST['regUser'])) {
$username = $_POST['regUsername'];
$pass1 = $_POST['regPassword1'];
$pass2 = $_POST['regPassword2'];
$email = $_POST['regEmail'];
$date = date("Y-m-d H:i:s");
$obj = new registration();
$obj->registration($username, $password1, $password2, $email, $date);
}
?>
For safety, I'll put also a connection file:
<?php
class db_connect {
function connect() {
return new PDO("mysql:host=127.0.0.1;dbname=oop", "root", "");
}
}
?>

It's one of the most common "error" with PDO.
With bindParam, you can only pass variables, not values.
In your registration() method, replace:
$q->bindParam(5, '0');
$q->bindParam(6, '0');
By:
$q->bindValue(5, '0');
$q->bindValue(6, '0');
With bindValue you can pass values and variables.
You can read the PHP manual for more info (here and here).

Related

Need help to get rid of in this PHP code that restricts me from having the same entry in a category in a database. (please help)

I need to get rid of the part that restricts me from adding the same value in a field from previous entries. I need to get rid of the part that gives me an error message if the entry matches a value from the database. Can someone please help me?
<?php
class DbOperation
{
private $conn;
//Constructor
function __construct()
{
require_once dirname(__FILE__) . '/Constants.php';
require_once dirname(__FILE__) . '/DbConnect.php';
// opening db connection
$db = new DbConnect();
$this->conn = $db->connect();
}
//Function to create a new user
public function createUser($RC, $Date, $Value)
{
if (!$this->isUserExist($RC, $Date, $Value)) {
$password = md5($pass);
$stmt = $this->conn->prepare("INSERT INTO MyInventory (username, password, email, name, phone) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param("sssss", $username, $password, $email, $name, $phone);
if ($stmt->execute()) {
return ENTRY_CREATED;
} else {
return ENTRY_ALREADY_EXIST;
}
} else {
return ENTRY_ERROR;
}
}
private function isUserExist($username, $email, $phone)
{
$stmt = $this->conn->prepare("SELECT id FROM users WHERE username = ? OR email = ? OR phone = ?");
$stmt->bind_param("sss", $username, $email, $phone);
$stmt->execute();
$stmt->store_result();
return $stmt->num_rows > 0;
}
as you can see in the photo below, every single entry in the database is different. I need to get rid of this and make it so that it is possible for 2 "RC" values to be the same.
When createUser is called, it first checks if the user already exists (if a record exists in the database with the same RC) by calling isUserExist. If you want to allow duplicate RC values, simply remove the if/else statement and only keep the code inside of the if block.

Unable to save form data to sql table using php

I am trying to save a form data into sql table using php. Eventhough I am not getting error while submit, data is not showing up in table.
My submit button name is input_submit
Here is my code:
if(isset($_POST['input_submit'])){
include 'dbConnection.php';
include 'saveData.php';
}
dbConnection.php
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
include_once $path . '/wp-load.php';
include_once $path . '/wp-config.php';
class ConnectDB{
private $servername;
private $username;
private $password;
private $dbname;
protected function connect(){
$this->servername ="localhost";
$this->username ="root";
$this->password ="";
$this->dbname ="testdb";
$conn = new mysqli($this->servername,$this->username,$this->password,$this->dbname);
if($conn -> connect_error) {
die("connection failed:".$conn-> connect_error);
}
return $conn;
}
}
?>
saveData.php:
<?php
class saveinput extends ConnectDB {
public function Savein(){
$date = $_POST['date'];
$entry_type = $_POST['entry_type'];
$amount = $_POST['amount'];
$sql = $conn->prepare("INSERT INTO wp_myexpenses (date, entry_type, amount)
VALUES(?, ?, ?)");
$sql->bind_param("sss",$date, $entry_type, $amount);
$sql->execute();
if ($sql->execute()) {
echo "success";
} else {
echo "failed";
}
}
}
?>
while submit, form is getting submitted. But when I check the db table, nothing is showing up. I am not understanding whats wrong here. Can someone guide me please.
You should call your "connect" method inside your Savein method in a var. So, your Savein method should be:
public function Savein(){
$conn = parent::connect(); // This is the only thing i've added
$date = $_POST['date'];
$entry_type = $_POST['entry_type'];
$amount = $_POST['amount'];
$sql = $conn->prepare("INSERT INTO wp_myexpenses (date, entry_type, amount)
VALUES(?, ?, ?)");
$sql->bind_param("sss",$date, $entry_type, $amount);
if ($sql->execute()) {
echo "success";
} else {
echo "failed";
}
}

how to fix easily this error Fatal error: Call to a member function execute() on boolean in /Applications/XAMPP/xamppfiles/htdocs

I developed php simple page to register users and check if the user exists or not but it is not working and displays the fallowing error :
Fatal error: Call to a member function execute() on boolean in /Applications/XAMPP/xamppfiles/htdocs/one/include/DbOperation.php on line 31
and php code here please help us for this issue
<?php
class DbOperation
{
private $conn;
enter code here
//Constructor
function __construct()
{
require_once('Constants.php');
require_once('DbConnect.php');
// opening db connection
$db = new DbConnect();
$this->conn = $db->connect();
}
//Function to create a new user
public function createUser($username, $pass, $email, $name, $phone)
{
if (!$this->isUserExist($username, $email, $phone)) {
$password = md5($pass);
$stmt = $this->conn->prepare("INSERT INTO users (username, password, email, name, phone) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param("sssss", $username, $password, $email, $name, $phone);
if ($stmt->execute()) {
return USER_CREATED;
} else {
return USER_NOT_CREATED;
}
} else {
return USER_ALREADY_EXIST;
}
}
private function isUserExist($username, $email, $phone)
{
$stmt = $this->conn->prepare("SELECT id FROM users WHERE username = ? OR email = ? OR phone = ?");
//if($query = $this->db->conn->prepare($sql)){
$stmt->bind_param(array("sss", $username, $email, $phone));
$stmt->execute();
$stmt->store_result();
$stmt->fetch();
$stmt->close();
return $stmt->num_rows > 0;
}
}
?>
In your isUserExist() function it looks like your bind_param has an array which shouldn't be there:
$stmt->bind_param(array("sss", $username, $email, $phone));
should be:
$stmt->bind_param("sss", $username, $email, $phone);
This is most likely why mysqli->bind_param is returning FALSE
change your isUserExist as below:
private function isUserExist($username, $email, $phone)
{
$stmt = $this->conn->prepare("SELECT id FROM users WHERE username = ? OR email = ? OR phone = ?");
//if($query = $this->db->conn->prepare($sql)){
$stmt->bind_param("sss", $username, $email, $phone); // change here remove array
$stmt->execute();
$stmt->store_result();
$stmt->fetch();
//$stmt->close(); // change this comment or remove this
return $stmt->num_rows > 0;
}
use this in isUserExist() function
$stmt->bind_param("sss", $username, $email, $phone);

How to use PHP prepared statements in OOP

I am saving my data using this code (pasting my code)
Connection.php:
<?php
namespace Database;
use Mysqli;
class Connection {
public $con;
function __construct() {
$this->con = new mysqli(connection strings here);
}
function save($sql) {
$this->con->query($sql);
}
}
?>
then my Save.php is like this:
<?php
require 'config.php';
class Save {
function __construct($username, $password) {
$connect = new Database\Connection;
$sql = "INSERT INTO sample(string1, string2) VALUES ('$test1', '$test2')";
$connect->save($sql);
}
}
$save = new Save("last", "last");
?>
my question is how do I implement bind params here and prepared statement for PHP?
and also I would like to ask what are the best way to do this and best practices that I should implement for my code
thanks guys
Your classes are structured in a weird way, I am guessing you want some sort of ORM like class?
If so, you may want to rename your Save class to User (that's a guess since you are trying to save a username and password) and move your constructor logic, e.g.
class User {
function save($username, $password) {
$sql = "INSERT INTO users (username, password) VALUES (?,?)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
}
}
This example explain how you can do it .
<?php
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
$stmt->bind_param('sssd', $code, $language, $official, $percent);
$code = 'DEU';
$language = 'Bavarian';
$official = "F";
$percent = 11.2;
/* execute prepared statement */
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
/* close statement and connection */
$stmt->close();
/* Clean up table CountryLanguage */
$mysqli->query("DELETE FROM CountryLanguage WHERE Language='Bavarian'");
printf("%d Row deleted.\n", $mysqli->affected_rows);
/* close connection */
$mysqli->close();
?>
And you can find more info in this link : http://php.net/manual/tr/mysqli-stmt.bind-param.php
And i suggest you to use PDO its better way to connect with the
database .
Use like this.
public function insert_new_user($username, $email, $password){
$mysqli = $this->link;
$sql = "INSERT INTO users"
. " (user_name, user_email, user_pass)"
. " VALUES (?, ?, ?)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("sss", $username, $email, $password);
if ($stmt->execute()) {
return "success";
} else {
return "failed: " . $mysqli->error;
}
}

ERROR in register.php

Please help:
Fatal error: Call to a member function prepare() on a non-object in C:\wamp\www\ooploginreg\functions.php on line 14 Call Stack # Time Memory Function Location 1 0.0010 252552 {main}( ) ..\register.php:0 2 0.0020 265888 LoginRegistration->registerUser( ) ..\register.php:50
Codeline in functions.php:
<?php
require "config.php";
class LoginRegistration{
function _construct(){
$database = new DatabaseConnection();
}
public function registerUser($username, $password, $name, $email, $website){
global $pdo;
$query = $pdo->prepare("SELECT id FROM users WHERE username = ? AND email = ?");
$query->execute(array($username, $email));
$num = $query->rowCount;
if($num == 0){
$query = $pdo->prepare("INSERT INTO users (username, password, name, email, website)VALUES (?, ?, ?, ? ,?)");
$query->execute(array($username, $password, $name, $email, $website));
return true;
}else{
return print "<span style='color:=#e53d37'>Error...username/email already used.</span>";
}
}
}
?>
It looks like you are calling $pdo before it is initialized.
You called database connection in constructor. But your var "pdo" already have value. Your PDO make some data before this class runs.
Just Use
$this->database = new DatabaseConnection();
You create the variable $database but never used it:
$database = new DatabaseConnection();
Problems
You never used the $database variable
It is bad practice to use global
It is bad practice to have your class depend on database object
Connection should be passed to constructor
Solution
Your class should be like this:
class LoginRegistration
{
private $pdo;
function __construct($database)
{
$this->pdo = $database;
}
public function registerUser($username, $password, $name, $email, $website)
{
$query = $this->pdo->prepare("SELECT id FROM users WHERE username = ? AND email = ?");
$query->execute(array($username, $email));
$num = $query->rowCount;
if ($num == 0) {
$query = $this->pdo->prepare("INSERT INTO users (username, password, name, email, website)VALUES (?, ?, ?, ? ,?)");
$query->execute(array($username, $password, $name, $email, $website));
return true;
} else {
return print "<span style='color:=#e53d37'>Error...username/email already used.</span>";
}
}
}
usage:
$database = new DatabaseConnection();
$login = new LoginRegistration($database);

Categories