Insert into database in OOP doesn't work - php

I'm trying to make object oriented login and insert into database, following tutorial but this doesn't work. It won't make connection to database, error: No database selected. Can you help me?
This is code:
form in index.php
<form action="insert.php" method="post">
Firstname: <input type="text" name="fname" /><br><br>
Lastname: <input type="text" name="lname" /><br><br>
<input type="submit" />
Class in insert_class.php:
<?php
class Insert_class {
public $servername;
public $username;
public $password;
public $dbname;
public function __construct(){
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// insert into database
$sql = "INSERT INTO nametable (firstname, lastname)
VALUES ('$_POST[fname]','$_POST[lname]')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
}
Object for login and insert in database in insert.php:
require 'insert_class.php';
$insert = new Insert_class();
$insert->servername ='localhost';
$insert->username ='root';
$insert->password ='';
$insert->dbname ='newdatabase';

Try this
<?php
class Insert_class {
private $servername;
private $username;
private $password;
private $dbname;
private $con
public function __construct($servername,$username,$password,$dbname)
{
$this->servername = $servername;
$this->username = $username;
$this->password = $password;
$this->dbname = $dbname;
// Create connection
$this->conn = mysqli_connect($this->servername, $this->username,
$this->password, $this->dbname);
if ($this->con->connect_error) {
die('Connect Error (' . $this->con->connect_errno . ') '. $this->con->connect_error);
}
// etc
}
Then you can do
require 'insert_class.php';
$insert = new Insert_class('localhost','root','','newdatabase');
Notice I also captured the $con as a property. Your code would have lots it as it would only have been visible in __construct but none of the other methods you may want to write in this class.
Also Notice I changed the test for a successful connection. This is the correct way to check if a connection was successful. a simple if( ! $con ) is not good enough.

Rather than defining the connection details explicitly ,you can use DEFINE ..
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASSWORD", "");
define("DB_NAME", "newdatabase");
insert_class.php ...
public function __construct(){
$conn = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die(mysql_error());
mysql_select_db(DB_NAME, $conn) or die(mysql_error());
}

Related

How to instantiate PDO class functionality (::prepare method) in another class

I'm refactoring my PHP code, so that the insertion of data into my database is kept separate from the class that creates the database connection. I'm trying to implement the Single Responsibility Principle, but transferring my code (for inserting data) to a separate class results in the PDO::prepare statement becoming an 'undefined method'.
I have tried to instantiate my database class ('DB.php') and pass the object to the class that inserts data ('Register.php').
The DB class:
<?php
class DB
{
public $dbServer,
$dbUsername,
$dbPassword,
$dbName,
$pdo,
$stmt;
function __construct($dbServer,
$dbUsername,
$dbPassword,
$dbName)
{
$this->dbServer = $dbServer;
$this->dbUsername = $dbUsername;
$this->dbPassword = $dbPassword;
$this->dbName = $dbName;
$this->connect();
}
public function connect()
{
try {
$this->pdo = new PDO("mysql:host=" . $this->dbServer .
"; dbname=" . $this->dbName,
$this->dbUsername,
$this->dbPassword);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
exit("Could not connect to database: " . $e->getMessage() );
}
}
}
The Register class:
<?php
class Register
{
public $pdo,
$dbh,
$stmt,
$conn;
function __construct(DB $pdo)
{
$this->pdo = $pdo;
// $this->conn = $this->pdo->connect();
}
public function register(Validate $val)
{
try {
$this->stmt = $this->pdo->prepare(
"INSERT INTO registration(firstName,
surname,
email,
username,
password,
gender,
area)
VALUES(:firstName,
:surname,
:email,
:username,
:password,
:gender,
:area)");
$this->stmt->bindParam(':firstName', $val->firstName);
$this->stmt->bindParam(':surname', $val->surname);
$this->stmt->bindParam(':email', $val->email);
$this->stmt->bindParam(':username', $val->username);
$this->stmt->bindParam(':password', $val->password);
$this->stmt->bindParam(':gender', $val->gender);
$this->stmt->bindParam(':area', $val->area);
$this->stmt->execute();
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
}
}
My Configuration file:
<?php
$dbServer = '127.0.0.1';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'assignment';
spl_autoload_register(function($class)
{
require 'classes/' . $class . '.php';
} );
$db = new DB($dbServer, $dbUsername, $dbPassword, $dbName);
$database = new Register($db);
The actual Registration page:
<?php
require('core/config.php');
if( isset($_POST['submit']) ) {
$firstName = $_POST['firstName'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$username = $_POST['username'];
$password = $_POST['password'];
$gender = $_POST['gender'];
$area = $_POST['area'];
$val = new Validate($firstName, $surname, $email, $username, $password, $gender, $area);
$val->filter();
$database->register($val);
}
?>
This implementation results in the following notice:
Fatal error: Uncaught Error: Call to undefined method DB::prepare()
Why doesn't the PDO class communicate its in-built prepare() function to my Register class? I have viewed 'Fatal error: Call to undefined method Database::prepare()' on Stack Overflow and sought to remedy my code:
$this->conn = $this->pdo->connect();
(See the commented statement in my Register class.) However, $this->conn ends up returning a NULL instead of my database connection.

PHP connection and query error: Fatal error: Call to a member function query() on null in

I'm getting the above error in regards to my statement below, tried multiple fixes from other answers in stack but continue to get the same error :(
this is part of a php code in a user registration form, would like their info to insert in the table
if($conn->query( "INSERT INTO users (FIRST_NAME, LAST_NAME, USERNAME, PASSWORD)
VALUES ('$fname', '$lname', '$uname', '$pword')")==TRUE){
echo 'Inserted';
}else{
echo 'Not Inserted';
}
i have this other code in a separate file for the $conn
function dbConnect(){
$servername = "x";
$database = "activity2";
$username = "root";
$password = "root";
// Create connection
$conn = new
mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error);
} //echo "Connection successful"; //make variable global to access in other
functions global $conn; return $conn;}
First thing to do is to create the class that will return a connection:
<?php
//filename: dbConnect.php
class dbConnect
{
public function connect() {
global $conn;
$servername = "localhost";
$username = "root";
$password = "";
$database = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} //echo "Connection successful"; //make variable global to access in other
return $conn;
}
}
?>
Now you can execute your sql command in another file:
<?php
require 'dbConnect.php';
$db = new dbConnect();
$conn = $db->connect();
$nome = "Anailton";
$email = "jose#hotmail.com";
if($conn->query( "INSERT INTO clientes (NOME, EMAIL) VALUES ('$nome', '$email')")==TRUE){
echo 'Inserted';
}else{
echo 'Not Inserted';
}
?>

connection with database with OOP mysqli extending class

I know must coding part of mysql bt new at mysqli. I am not able to execute these insert query to the database. I have searched a lot but couldn't find simple suggestion, or may be i didn't understand.
Undefined variable: mysqli in C:\wamp\www\New folder\php\msqliconnect.php on line 32
Fatal error: Call to a member function mysqli_query() on a non-object in C:\wamp\www\New folder\php\msqliconnect.php on line 32
Any help is appreciated.
<?php
class connection
{
public $mysqli;
function connect()
{
$hostname = "localhost";
$username = "root";
$password = "";
$database = "demodatabase";
$mysqli = new mysqli($hostname, $username, $password, $database);
/* check connection */
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
return true;
}
}
class Index extends connection
{
function __construct()
{
parent::connect();
}
function insertdata($a, $b)
{
// echo $a. ' ' .$b;
// MySqli Insert Query
$status = 0;
$insert_row = $mysqli->mysqli_query("INSERT INTO tb_user (id, user, password, status) VALUES('','" . $a . "', '" . $b . "', '')");
if ($insert_row)
{
print 'saved';
}
else
{
die('Error : (' . $mysqli->errno . ') ' . $mysqli->error);
}
}
}
?>
In both of your connect() and insertdata() methods, you're using local variable $mysqli, not the instance variable public $mysqli;. You should use $this->mysqli instead of $mysqli in your instance methods. So your connect() and insertdata() methods would be like this:
function connect(){
$hostname = "localhost";
$username = "root";
$password = "";
$database = "demodatabase";
$this->mysqli = new mysqli($hostname, $username, $password, $database);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
return true;
}
and
function insertdata($a, $b){
$insert_row = $this->mysqli->query("INSERT INTO tb_user (id, user, password, status) VALUES('','".$a."', '".$b."', '')");
if($insert_row){
print 'saved';
}else{
die('Error : ('. $this->mysqli->errno .') '. $this->mysqli->error);
}
}
Sidenote: Learn about prepared statement because right now your query is susceptible to SQL injection attack. Also see how you can prevent SQL injection in PHP.

OOP mysqli database functions

I am a beginner in OOP in PHP and I am trying to play with my code. So first thing I wanted to do is to write one basic class with connect and insert functions for database. So my desired situation is this:
-I wanna create on class which will controll connect and insert functions. The problem is, my $connect variable isn't working from another function, so what could I do to make that possible?
You will understand more by the code provided.
<?php
class DB {
protected $dbhost = 'localhost';
protected $dbuser = 'root';
protected $dbpass = '';
protected $dbname = 'newdb';
public function connect()
{
$connect = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
if($connect->error)
{
echo "Failed to connect";
}
else
{
echo "connected";
}
}
public function insert($name, $second)
{
$insert = "INSERT INTO posts (name, second) VALUES ('$name', '$second')";
if ($connect->query($insert) === TRUE)
{
echo "New record created successfully";
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_connect_error();
}
}
}
require_once 'classes/DB.php';
$db = new DB;
if(isset($_POST['submit']))
{
$name = $_POST['name'];
$second = $_POST['second'];
$db->insert($name, $second);
}
?>
<form method="POST">
Add smth<input type="text" name="name"><br>
Also omg<input type="text" name="second"><br>
<input type="submit" name="submit">
</form>
Add $connect as a property of your class, so you may reuse it everywhere within the class using $this->connect:
class DB
{
protected $dbhost = 'localhost';
protected $dbuser = 'root';
protected $dbpass = '';
protected $dbname = 'newdb';
protected $connect;
public function connect()
{
$this->connect = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
if ($this->connect->error)
{
echo "Failed to connect";
}
else
{
echo "connected";
}
}
public function insert($name, $second)
{
$insert = "INSERT INTO posts (name, second) VALUES ('$name', '$second')";
if ($this->connect->query($insert) === TRUE)
{
echo "New record created successfully";
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_connect_error();
}
}
}
I have rewritten your class for a bit, so you can insert your database settings in the constructor. So it really is a object, and you can use multiple databases. What you did wrong in your class was using the variable $connect without declaring it into a variable usable in the whole class.
The class
<?php
class DB {
protected $dbhost;
protected $dbuser;
protected $dbpass;
protected $dbname;
protected $connection;
public function __construct($dbhost, $dbuser, $dbpass, $dbname)
{
$this->dbhost = $dbhost;
$this->dbuser = $dbuser;
$this->dbpass = $dbpass;
$this->dbname = $dbname;
$connection = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
if($connection->error)
die('Could not connect with the database!');
$this->connection = $connection;
}
public function connect()
{
$this->__construct($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
}
public function insert($name, $second)
{
$insert = "INSERT INTO posts (name, second) VALUES ('$name', '$second')";
if ($this->connection->query($insert) === TRUE)
{
echo "New record created successfully";
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_connect_error();
}
}
public function getConnection()
{
return $this->connection;
}
}
Usage
$db = new DB('localhost', 'root', '', 'newdb');
$db->insert('name', 'second');
I hope this helps you in your journal through OOP, sorry for my bad English.

How to connect to MySQLi server

I have a login-script, but when i proceed it there com a error:
Undefined property: Users::$host in C:\wamp\www\userlogin\classes\class.database.php on line 8
There is 4 files:
<?php
session_start();
include "classes/class.users.php";
if(isset($_POST['login'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$users->login($username, $password);
}
?>
<!DOCTYPE html>
<head>
<title>Basic Login Script</title>
</head>
<body>
<form method="POST" action="" name="login">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" name="login" value="Login">
</form>
</body>
</html>
<?php
class Database
{
public function __construct()
{
$host = 'localhost';
$user = 'root';
$pass = 'password';
$name = 'usersystem';
$this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->name);
if ($mysqli->connect_errno)
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
echo $mysqli->host_info . "\n";
}
} ?>
<?php
include "class.database.php";
class Users extends Database
{
public function login($username, $password)
{
$stmt = $this->mysqli->prepare("SELECT username, password FROM users WHERE username = ? and password = ? LIMIT 1");
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$stmt->bind_result($username, $password);
$stmt->store_result();
if($stmt->num_rows == 1) {
while($stmt->fetch()) {
$_SESSION['username'] == $username;
header("Location: dashboard.php");
}
}
else
return false;
$stmt->close();
$stmt->free_result();
}
}
$users = new users(); ?>
//dashboard
<?php echo "error"; ?>
I use localhost/index.php to run and the 3 files class.database.php and class.users.php dahsboard.php is in the directory: classes
Mybe it is a syntax-error, but i can not locate it.
I have created a database in phpmyadmin and inserted the data.
Can anybody help me?
You can't use $this for local variable, they will need to be property of the class, and you need a public one for the connection, like this:
<?php
class Database {
public $mysqli;
private $host = 'localhost';
private $user = 'root';
private $pass = 'password';
private $name = 'usersystem';
public function __construct() {
$this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->name);
if ($this->mysqli->connect_errno) {
echo "Failed to connect to MySQL: (". $this->mysqli->connect_errno . ") ";
}else{
echo $this->mysqli->host_info . "\n";
}
}
}
?>
Other thing I notice is you don't start a session before setting it.
You should also exit after redirecting
if($stmt->fetch()) {
session_start();
$_SESSION['username'] == $username;
header("Location: dashboard.php");
exit;
}
Try changing your database connection to this:
class Database
{
// Since you are calling this variable in other methods
// you need to make it available.
public $mysqli;
public function __construct()
{
$host = 'localhost';
$user = 'root';
$pass = 'password';
$name = 'usersystem';
$this->mysqli = new mysqli($host, $user, $pass, $name);
// You are mixing local with class-wide variables. Should all conform.
if ($this->mysqli->connect_errno)
echo "Failed to connect to MySQL: (".$this->mysqli->connect_errno.")".$this->mysqli->connect_error;
echo $this->mysqli->host_info."\n";
}
}
in the __construct method for Database change $user to $this->user, $host to $this->host etc..

Categories