OOP mysqli database functions - php

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.

Related

I want to display table rows in same class and difference function in PHP

how to display rows in my users table in PHP
arr() function can't connect with database
class DB {
protected $db_server = 'localhost';
protected $db_username = 'root';
protected $db_password = 'root';
protected $db_name = 'dbname';
public function connect() {
$connect_db = new mysqli($this->db_server, $this->db_username, $this->db_password, $this->db_name);
if(mysqli_connect_errno()) {
printf("Connection failed!", mysqli_connect_error());
exit();
} else {
echo "connected";
}
return true;
}
function arr() {
$conn = $this->connect();
if($query = mysqli_query($conn, "SELECT * FROM users")) {
echo 'row is ' . mysqli_num_rows($query);
}
}
}
$db = new DB();
$db->arr();
result -> "connected row is " not count rows
In the connect() function, change
return true;
to
return $connect_db;
so that it returns the connection object. Then you can use it in your other functions.

PHP Code not selecting from database

UPDATE: There was no issue with the code used in counting. There was just a typo error in connecting to database
$this->conn = new PDO("mysql:host=". $this->host . ";db_name=" . $this->db_name, $this->username, $this->password);
the db_name should be dbname. So its something like
$this->conn = new PDO("mysql:host=". $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
I am try a PHP REST api with mysql database but this doesn't seem to be working as i have tried to select from my database as the first step but this returns no result despite there being a record in the database
Below are my codes
database.php
<?php
class Database
{
//Database Credentials
private $host = "localhost";
private $username = "root";
private $password = "password";
private $db_name = "rtmdb";
public $conn;
//Get Database Connection
public function getConnection()
{
$this->conn = null;
//Try connection
try
{
$this->conn = new PDO("mysql:host=". $this->host . ";db_name=" . $this->db_name, $this->username, $this->password);
$this->conn->exec("set names utf8");
}
catch(PDOException $exception)
{
echo "Connection error:" . $exception->getMessage();
}
return $this->conn;
}
}
admin.php to select from database
<?php
class Admin
{
//Database Connection and Table name
private $conn;
private $table_name = "admin";
//object properties
public $id;
public $fname;
public $lname;
public $oname;
public $uname;
public $email;
public $idnumber;
public $password;
public $profimage;
public $datecreated;
public $modifiedby;
public $datemodified;
public $status;
//Construct $db as database connection
public function __construct($db)
{
$this->conn = $db;
}
public function crawl()
{
$query = "SELECT * FROM " . $this->table_name;
$stmt = $this->conn->prepare($query);
$stmt->execute();
return $stmt;
}
}
crawl.php file to get data and json_encode results
//Include database and object files
include_once "../config/database.php";
include_once "../objects/admin.php";
$database = new Database();
$db = $database->getConnection();
$admin = new Admin($db);
//Query Admin
$stmt = $admin->crawl();
$num = $stmt->rowCount();
echo json_encode($num);
if($num > 0)
{
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
$admin_list = array(
"id" => $id,
"uname" => $uname
);
array_push($admin_arr['records'], $admin_list);
}
echo json_encode($admin_arr);
}
else
{
echo json_encode(
array("message" => "No registered admin found.")
);
}
But i get rowCount() as 0 and "no registered admin" despite having records
Below are screenshots of my table structures
the database structure
I also have only one data in the database
But these seem to give me no result. Please what the issue and how do i fix?

Call to a member function query() on null with PDO

I just checked all of the answers are available on stackoverflow,they are similar but not my answer exactly. So please don't take this post as duplicate.
these are my codes when I'm executing it say's
Fatal error: Call to a member function query() on null in
C:\wamp64\www\ourCMS\index.php on line 12
Here is my snippet :
<?php
class DB
{
private $dbHost;
private $dbName;
private $dbUser;
private $dbPass;
protected $con;
function set_db($host, $db, $user, $pass)
{
$this->dbHost = $host;
$this->dbName = $db;
$this->dbUser = $user;
$this->dbPass = $pass;
}
function connect()
{
$info = 'mysql:host='.$this->dbHost.';dbname='.$this->dbName;
try
{
$this->con = new PDO($info, $this->dbUser, $this->dbPass);
}
catch(PDOException $e)
{
print "Error Founds: ".$e->getMessage().PHP_EOL;
die();
}
}
}
// here is the place where i'm trying to use this actually
if (isset($_POST['submit']))
{
include('include/database.php');
$database = new DB;
$database->set_db("localhost", "ourcms", "root", "");
$conn = $database->connect();
$name = $_POST['nm'];
$query = "INSERT INTO testingpdo (name) VALUES ('$name')";
$data = $conn->query($query);
$result = $data->fetchAll(PDO::FETCH_ASSOC);
print_r($result);
}
You don't return nothing from DB::connect ($conn = $database->connect();). Add return $this->con; at the end of the function.
function connect()
{
$info = 'mysql:host='.$this->dbHost.';dbname='.$this->dbName;
try
{
$this->con = new PDO($info, $this->dbUser, $this->dbPass);
}
catch(PDOException $e)
{
print "Error Founds: ".$e->getMessage().PHP_EOL;
die();
}
return $this->con;
}

Insert into database in OOP doesn't work

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

php oop database query

I am self learning php and trying oop, I am struggling with following problem, Would anyone could help me how can I use following database connection in to another class function. In php.net it is defined as $mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db'); but when I use this within a class it dose not work. Thanks
class dbconnect{
private $host;
private $user;
private $pass;
private $dabase;
function doConnect()
{
$this->host = 'localhost';
$this->user = 'root';
$this->pass = 'abc#123';
$this->dabase = 'database_5';
$db = new mysqli($this->host, $this->user, $this->pass, $this->dabase);
if (mysqli_connect_errno())
{
echo "<br /><hr />";
echo "<p style='align:center;'>Error : could not connect to database.. </p>";
echo "<hr />";
exit;
}
}
$mysql = new dbconnect();
function doQuery($mysql){
$queryUser = $mysql->query("SELECT * FROM b_admin_user WHERE username_d = 'admin'");
echo $queryUser_row = $queryUser->num_rows;
}
doQuery($mysql);
Try this
<?php
class MySQL {
//objekto kintamieji
private $host;
private $username;
private $password;
private $database;
private $conn; // connection
public function __construct($set_host, $set_username, $set_password){
$this->host = $set_host;
$this->username = $set_username;
$this->password = $set_password;
// jungiuosi prie db
$this->conn = mysql_connect($this->host, $this->username, $this->password)
or die("Couldn't connect");
}
public function database($set_database)
{
$this->database=$set_database;
//pasirenku lentele
mysql_select_db($this->database, $this->conn) or die("cannot select Database");
}
}
// jungiames
$connect = new MySQL('localhost','root','');
$connect->database('job');
?>

Categories