So what I want to do is to show who's in a team. I've created a function called getTeam().
class admin
{
private $db;
public function __construct($conn)
{
return $this->db;
}
public function getTeam($teamname)
{
try
{
$sql = "SELECT * FROM `tbl_players` WHERE EXISTS (SELECT id FROM `tbl_teams` WHERE team_name=:team_name)";
$stmt = $this->db->prepare($sql);
$stmt->bindparam(":team_name", $teamname);
$stmt->execute();
return $stmt;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
}
Here is my dbconnect I'm using
session_start();
$DB_host = "localhost";
$DB_user = "root";
$DB_pass = "";
$DB_name = "project_fifa";
try
{
$conn = new PDO("mysql:host={$DB_host};dbname={$DB_name}",$DB_user,$DB_pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
include ('assets/classes/admin.php');
$user = new admin($conn);
So now I'm trying to use the function here
require('../dbconnect.php');
if(isset($_POST['findteam'])){
$teamname = $_POST['teamname'];
getTeam($teamname);
}
It can't find the function and I don't know why.
If you are doing code with OOPS, First you have to learn some basics about it Read it
Object(new) :
To create an instance of a class, the new keyword must be used. An object will always be created unless the object has a constructor defined that throws an exception on error. Classes should be defined before instantiation (and in some cases this is a requirement).
If a string containing the name of a class is used with new, a new instance of that class will be created. If the class is in a namespace, its fully qualified name must be used when doing this.
$adminObject = new admin();
$adminObject->getTeam($teamname);
Related
I wanna get data on table and write a class. But this class doesn't work because pdo doesn't access. How can I get table data with this class?
$db = new PDO("mysql:host=localhost;dbname=xxx;charset=utf8", "xxx", "xxx");
class uye extends PDO{
var $id;
var $kadi;
function cek($id){
$query = $db->query("SELECT * FROM btc WHERE id='{$id}'", PDO::FETCH_ASSOC);
if ( $query->rowCount() ) {
foreach( $query as $row ){
$this->id=$row["id"];
$this->kadi=$row["kadi"];
}
}
}
}
$bilgiler=new uye;
$bilgiler->cek(1);
echo $bilgiler->kadi;
So I'm running this off of fetching all data as I dont know where you're getting $id from.
I generally break my code up into files and folders as I found this easier to work with and others to work on.
// database connection file (dbc.php)
class Database
{
private $host = "127.0.0.1";
private $db = "";
private $user = "";
private $password = "";
public $conn;
public function dbConnect()
{
$this->conn = null;
try
{
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db, $this->user, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $exception)
{
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
}
I then make a common file, this is where you can store all of your frequently used functions or your static functions
// Common file (common.php)
require_once('dbc.php');
class DBCommon
{
private $conn;
public function __construct()
{
$database = new Database();
$db = $database->dbConnect();
$this->conn = $db;
}
public function run($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
}
So to explain this a little more, you will see a function of run() this is just to save the tedious $this->conn->prepare on every query.. Now you can run $this->run()
The next would be your class file.. this is where your logic goes:
// your class file... (class.btc.php)
require_once "common.php";
class BTC extends DBCommon
{
public function getQuery()
{
$stmt = $this->run("SELECT * FROM `btc`");
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_OBJ))
{
$rows[] = $row;
}
return $rows;
}
}
Self explanatory..
And then your calling method.. Lets say index.php
// File you're calling your class from (index.php)
require_once "class.btc.php";
$fetch = new BTC();
$returnData = $fetch->getQuery();
foreach ($returnData as $data)
{
echo
"<p>$data->something</p>
<p>$data->somethingElse</p>";
}
It seems a little long winded I know, but the time you'll save overall will help!
Having trouble understanding classes and inheritance:
core.php:
$servername = "****";
$database = "****";
$username = "****";
$password = "****";
try {
$pdo = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
class Database {
protected $pdo;
public function __construct($pdo) {
$this->pdo = $pdo;
}
}
class User extends Database {
private $ip;
private $sessionId;
public function __construct($ip, $sessionId) {
$this->ip = $ip;
$this->sessionId = $sessionId;
}
public function getSessionInfo () {
$stmt = $this->pdo->prepare(".."); <-- error here
....
}
}
When calling:
require_once 'api/core.php';
$database = new Database($pdo);
$user = new User($_SERVER['REMOTE_ADDR'], $_SESSION['info']['id']);
In this contest $database, and $user variables are not related to each other:
require_once 'api/core.php';
$database = new Database($pdo);
$user = new User($_SERVER['REMOTE_ADDR'], $_SESSION['info']['id']);
Thus, calling prepare() on $user won't work.
You need a mechanism, at least like this , although not a good practice to assign Database to a User:
$user->setDatabase($database);
Instead create a static Database object, initiate it before User initiation, and call it statically within User object, or any other object, make it available for all objects.
A quick fix would look like this, where User doesn't extend Database, because it's wrong. User is not a Database.
$database = new Database();
$user = new User();
$user->setDatabase($database); //sets $db variable inside User
//User.php
namespace MyApp;
class User{
private Database $db;
public function setDatabase($db){
$this->db = $db;
}
public function doSomething(){
$this->db->getPdo()->prepare('..');
}
}
//Database.php
namespace MyApp;
class Database{
private $pdo; //returns PDO object
function __construct(){
//create pdo connection
$this->pdo = ..
}
function getPdo(){
return $this->pdo;
}
}
Database should be injected to objects or used by objects, you shouldn't be extending Database just to have it. If you want to do it properly, in an object-oriented way.
Remember PHP doesn't allow multiple inheritances by extend. Tomorrow, you might want to have a Person class that every User will extend, but since you did it wrong in the beginning, and wasting precious extend on Database, it won't be possible. And by not having a control of how many database instances you have created, you will run into issues. You need to know for sure that you have only a single connection object for one database, if of course the opposite is a must - which in your case I doubt.
Of course this will change if you have multiple database requirements, and more sophisticated app structure.
You are receiving this error because User Instance has pdo empty. try this code
$servername = "****";
$database = "****";
$username = "****";
$password = "****";
try {
$pdo = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
class Database {
protected $pdo;
public function __construct($pdo) {
$this->pdo = $pdo;
}
}
class User extends Database {
private $ip;
private $sessionId;
public function __construct($pdo, $ip, $sessionId) {\
parent::__construct($pdo)
$this->ip = $ip;
$this->sessionId = $sessionId;
}
public function getSessionInfo () {
$stmt = $this->pdo->prepare("..");
....
}
}
then
require_once 'api/core.php';
$user = new User($pdo, $_SERVER['REMOTE_ADDR'], $_SESSION['info']['id']);
hope it helps.
I have a PHP class with two methods. One connects to a MySQL database for output, and the other connects to a MySQL database for input.
My question is, for both functions, I repeated the code for connecting to the database. What would be a better way to maybe have a third function in the class to connect to the DB and have the other two call the function to establish the connection, rather than repeat the code twice? I'm a PHP n00b trying to improve my OOP coding. Notice how I connected to the DB twice--using the exact same code:
class output_mysql {
var $db_name = 'database';
var $db_username = 'name';
var $db_password = 'mypassword';
function print_table_cell($tbl_name, $colm_name, $array_index_num) {
try {
$pdo = new PDO("mysql:host=localhost;dbname=$this->db_name", $this->db_username, $this->db_password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e) {
$error = 'Unable to connect to the database server.';
include 'output_mysql_error.php';
exit();
}
try {
$sql = "SELECT $colm_name FROM $tbl_name";
$result = $pdo->query($sql);
}
catch (PDOException $e) {
$error = 'Error fetching content: ' . $e->getMessage();
include 'output_mysql_error.php';
exit();
}
while ($row = $result->fetch()) {
$all_content[] = $row["$colm_name"];
}
echo $all_content[$array_index_num];
}
function update_content($tbl_name, $colm_name, $error_message_text, $id_num) {
try {
$pdo = new PDO("mysql:host=localhost;dbname=$this->db_name", $this->db_username, $this->db_password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e) {
$error = 'Unable to connect to the database server.';
include 'output_mysql_error.php';
exit();
}
try {
$sql = 'UPDATE website_content SET
content = :content,
date_added = CURDATE()
WHERE id = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':content', $error_message_text);
$s->bindValue(':id', $id_num);
$s->execute();
}
catch (PDOException $e) {
$error = 'Error: ' . $e->getMessage();
include 'output_mysql_error.php';
exit();
}
}
}
This question is tagged [oop], but the code in it is far from OOP.
Your methods are doing waaaaaaaaaaaaay too much. What you should do is inject the database connection into the constructor of the output_mysql class (which is a terrible name btw).
namespace App\Page;
class Content
{
private $dbConnection;
public function __construct(\PDO $dbConnection)
{
$this->dbConnection = $dbConnection
}
public update($id, $content)
{
$stmt = $this->dbConnection->prepare('UPDATE website_content SET content = :content, date_added = CURDATE() WHERE id = :id');
$stmt->execute([
'id' => $id,
'content' => $content,
]);
}
}
$dbConnection = new \PDO("mysql:host=localhost;dbname=$this->db_name", $this->db_username, $this->db_password);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pageContent = new \App\Page\Content($dbConnection);
$pageContent->update(1, 'new content');
If you have a method called print_table_cell you are probably doing OOP wrong, because it probably means you code is doing too much and probably violates the Single Responsibility Principle. I mean a class in almost all circumstances would never need to be able to access any column of just any table.
class Model
{
protected $pdo;
/**
* Inject the pdo driver in the model.
*/
public function __construct(PDO $pdo)
{
$this->pdo = $pdo;
}
public function print_table_cell($tbl_name, $colm_name, $array_index_num)
{
// Use the pdo object $this->pdo
}
}
// Create the connection
$dbName = '';
$dbUsername = '';
$dbPassword = '';
$pdo = new PDO("mysql:host=localhost;dbname=$dbName", $dbUsername, $dbPassword);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Create your model and inject the pdo object.
$model = new Model($pdo);
$model->print_table_cell() ...
As said above you need to use prepared statements, because PDO will escape the values which prevents SQL injections. But anyway all input data must be filtered : you have some basic filters http://php.net/manual/fr/function.filter-var.php.
The model class should only interact with the database, and doesn't print anything.
For priting output you can use a so called View class that get data from the model and displays it.
class View
{
protected $model;
public function __construct(Model $model)
{
$this->model = $model;
}
public function render()
{
echo $this->model->getData();
}
}
class Model
{
protected $pdo;
public function __construct(PDO $pdo)
{
$this->pdo = $pdo;
}
public function getData()
{
// Do your query here with $this->pdo and prepared statement.
// and return the data
}
}
$pdo = new PDO(...);
$model = new Model($pdo);
$view = new View($model);
$view->render();
I have an insert query, and I want to get the ID from the table. I have been searching, and I found lastInsertId() for PDO. When I want to use it, I get PHP errors.
This is my code:
$db = new database();
$naam = $db->quoteQuery($_POST['naam']);
$barcode = $db->quoteQuery($_POST['barcode']);
$sql = "INSERT INTO products(name, barcode) VALUES (".$name.",".$barcode.")";
$results = $db->executeQuery($sql);
$lastid = $results->lastInsertId();
But this gives an error, this one:
Fatal error: Call to undefined method PDOStatement::lastInsertId() in /home/onlineweuh/domains/onlinewebapps.nl/public_html/vsb/admin/add-product.class.php on line 297
My database class:
class database
{
private $handleDB;
public function __construct()
{
$host = ;
$user = ;
$database = ;
$password = ;
try
{
$this->handleDB = new PDO('mysql:host='.$host.';dbname='.$database, $user, $password);
}
catch (PDOException $e)
{
print_r($e);
}
$this->handleDB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
}
I hope someone can help me solve it, I want the ID which is given at the insert Query.
You get the lastinsertid from the PDO object and not your results object.
Try $db->lastInsertId()
edit below.
Your database class is encapsulating your handleDB / PDO object. Since the handleDB variable is private, you cannot access this outside your class. You would need to either make it public like so;
class database
{
public $handleDB;
public function __construct()
{
$host = 'removed';
$user = 'removed';
$database = 'removed';
$password = 'removed';
try
{
$this->handleDB = new PDO('mysql:host='.$host.';dbname='.$database, $user, $password);
}
catch (PDOException $e)
{
print_r($e);
}
$this->handleDB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
}
}
Now you can call $db->handleDB->lastInsertId();
Or you could expose the handleDB->lastInsertId() as a function like:
class database
{
private $handleDB;
public function __construct()
{
$host = 'remove';
$user = 'removed';
$database = 'removed';
$password = 'removed';
try
{
$this->handleDB = new PDO('mysql:host='.$host.';dbname='.$database, $user, $password);
}
catch (PDOException $e)
{
print_r($e);
}
$this->handleDB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
}
public function lastInsertId(){
return $this->handleDB->lastInsertId();
}
}
You would call using $db->lastInsertId();
lastInsertId is a method of PDO, not PDOStatement. Therefore:
$db->lastInsertId();
your database class needs to be a subclass of PDO by extending PDO
class database extends PDO
that way all the methods in PDO are available to your subclass.
im trying to understand oophp a litle bit but now im stuck in getting information out of my database. What am i doing wrong? After the tip off PDO I tried the following but also no results...
index.php
<?php
include('classes/database.class.php');
$db = new Database();
$db->connect();
$res = $db->select();
print_r($res);
?>
database.class.php
<?php
class Database {
private $db_host = 'localhost'; // Database Host
private $db_user = 'root'; // Gebruikersnaam
private $db_pass = 'root'; // Passwoord
private $db_name = 'quickscans'; // Database naam
public function connect()
{
try
{
$db = new PDO('mysql:host='.$this->db_host.';dbname='.$this->db_name,$this->db_user,$this->db_pass);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
public function disconnect()
{
$db = null;
}
public function select()
{
$sql = 'SELECT id FROM bedrijf';
$results = $db->query($sql);
foreach($results as $row)
{
echo $row['id'].'<br>';
}
}
}
?>
Maybe this code is a bit cleaner.. but still no results :(.
You aren't assigning any instance variables in this class.
The query method has no access to the connection you create because the object has no state.
Your constructor for the class should create the connection, and then queries can be called on this property.
class Database {
private $db_host = 'localhost'; // Database Host
private $db_user = 'root'; // Gebruikersnaam
private $db_pass = 'root'; // Passwoord
private $db_name = 'quickscans'; // Database naam
public function __construct(){
$this->connect();
}
public function connect()
{
try
{
$this->connection = new PDO('mysql:host='.$this->db_host.';dbname='.$this->db_name,$this->db_user,$this->db_pass);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
public function disconnect()
{
$this->connection = null;
}
public function select()
{
$sql = 'SELECT id FROM bedrijf';
$results = $this->connection->query($sql);
foreach($results as $row)
{
echo $row['id'].'<br>';
}
}
}
The $this keyword sets instance variables for the class, so the connection property becomes a PDO instance that other methods can act upon. Without this, the varibles created in the methods, in this case $db are just orphaned in the local function scope and not accessible in the greater class.
Utilizing this approach elminates the need to run connect() in the calling context. You don't need to use the constructor to do this if you don't want to, you'll just always need to connect first in order to create the connection property and have it available to the rest of the class. Also note you can name the property whatever you like, I just used connection because it made the most sense in the API.
Also, as commented, to make this a bit more usable you should have the select method return the query results array rather than having it output directly.
public function select()
{
$sql = 'SELECT id FROM bedrijf';
$results = $this->connection->query($sql);
if(!empty($results)){
return $results
}else{
return false;
}
}