php with two class - php

my sample is good or not?
I have a good connection to the database, or too should be in the class?
Thanks
<?php
mysql_connect('localhost','root','admin');
mysql_select_db('test');
class UserDisplay
{
function getDisplayName()
{
$sql = 'select first_name, last_name, display_name from users where user_id = "3"';
$results = mysql_query($sql);
$row = mysql_fetch_array($results);
$this->user_id = $user_id;
return $this->user_id;
}
}
class UserInsert
function InsertName($name)
{
mysql_query("INSERT INTO Persons (first_name)VALUES ('".$name."')");
}
}
$userD = new UserDisplay();
echo "User known as: " . $userD->getDisplayName() . "\n";
$userI = new UserInsert();
$userI->InsertName("Peter");
?>

You should merge those classes into a single User class, then select the user array from the database in the constructor and store it in a class variable.
You would also ideally pass in the mysql connection to that class so that it doesn't always just use the default connection. The mysql functions all have a "link identifier" parameter, and it's considered good practice to use it if you aren't using an OO interface (like mysqli's OO class).

Probably be better off just making them functions, instead of wrapping them up in classes. Extract all of it, except the last into it's own php file. You forgot to extract display name from $user
// myFunctions.php
<?php
function connectDb() {
mysql_connect('localhost', 'root', 'admin');
mysql_select_db('test');
}
function closeDb() {
mysql_close();
}
function displayName() {
$sql = 'select first_name, last_name, display_name from users where user_id = "3"';
$results = mysql_query($sql);
$user = mysql_fetch_array($results);
return $user['display_name'];
}
function insertFirstName($name) {
mysql_query("INSERT INTO Persons (first_name)VALUES ('" . $name . "')");
}
?>
// index.php
<?php
require_once 'myFunctions.php';
connectDb();
echo "User known as: " . displayName() . "\n";
insertFirstName("Peter");
closeDb();
?>
But if you insist on using classes:
// User.php
<?php
class User {
private function connectDb() {
mysql_connect('localhost', 'root', 'admin');
mysql_select_db('test');
}
private function closeDb() {
mysql_close();
}
function displayName() {
$this->connectDB();
$sql = 'select first_name, last_name, display_name from users where user_id = "3"';
$results = mysql_query($sql);
$user = mysql_fetch_array($results);
$this->closeDB();
return $user['display_name'];
}
function insertFirstName($name) {
$this->connectDB();
mysql_query("INSERT INTO Persons (first_name)VALUES ('" . $name . "')");
$this->closeDB();
}
}
?>
// index.php
<?php
require_once 'User.php';
$user = new User;
echo "User known as: " . $user->displayName() . "\n";
$user->insertFirstName("Peter");
?>
Actually not bad. abstracted out the db connection and close.

Your sample is not really ideal. Classes should not depend on or modify any external resources, except whatever has been passed to them through arguments / properties / or method calls.

Related

Setting up a database connection class in PHP

I was recently introduced to the idea of classes in PHP, and after some research I've come to the conclusion that I need to store database related functions in a class to access later. It has worked for the most part, but some use cases I am still confused with. For example,
Below is an example of how I would normally connect to my database and display information from user id's in a table
dbcon.php:
<?php
$con = mysqli_connect("host","username","password","database") or die("Couldn't connect");
require_once("functions.php");
?>
functions.php
function getUserInfo($id) {
$query = mysqli_query($con, "SELECT * FROM users WHERE id = '$id'");
return mysqli_fetch_array($query);
}
Some random file:
require_once("dbcon.php");
$result = mysqli_query($con, "SELECT * FROM tablename");
while ($row = mysqli_fetch_assoc($result)) {
$userinfo = getUserInfo($row['userid']);
echo $userinfo['name'];
}
?>
I don't feel like this method of querying the database and displaying information is the neatest or most efficient way possible. I read this article about using classes to tamper with a database and call functions that I created in the class.
My first question is this: When I try to access $con in functions.php, it is undefined. How can I pass the variable from dbcon.php to functions.php over the require_once function?
I also would like to know what the best way to store my connection to the database is, and if there are any tutorials on how to set that up.
I hope you understood that lol.
You can do it like this way:-
Dbconnection.php:-
<?php
Class DbConnection{
function getdbconnect(){
$conn = mysqli_connect("host","username","password","database") or die("Couldn't connect");
return $conn;
}
}
?>
Function.php:-
<?php
require_once('Dbconnection.php');
Class WorkingExamples{
function getUserInfo($id) {
$Dbobj = new DbConnection();
$query = mysqli_query($Dbobj->getdbconnect(), "SELECT * FROM users WHERE id = '$id'");
return mysqli_fetch_array($query);
}
}
$data = new WorkingExamples();
echo "<pre/>";print_r($data->getUserInfo(3));
?>
Note:- this is an example, try it by changing values according to your requirement and get the result.
<?php
class DatabaseConnection
{
private $host = "127.0.0.1";
private $dbname = "online_english";
private $dbUsername = "root";
private $dbPass = "";
private $charset = 'utf8mb4';
private $dsn;
public function tryConnect(){
try{
$this->dsn = "mysql:host=$this->host;dbname=$this->dbname;charset=$this->charset";
$DBH = new PDO($this->dsn,$this->dbUsername,$this->dbPass);
$DBH->exec("set names utf8");
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $DBH;
}
catch (PDOException $e){
$e->getMessage();
}
}
}
?>
<?php
class Database{
const DB_HOSTNAME = 'localhost';
const DB_USERNAME = 'root';
const DB_PASSWORD = 'root';
const DB_NAME = 'stockganesha';
public $_db_connect;
protected $_sql;
protected $_result;
protected $_row;
function db_connect(){
$this->_db_connect = mysqli_connect(self::DB_HOSTNAME,self::DB_USERNAME,self::DB_PASSWORD,self::DB_NAME) or die(mysql_error());
return $this->_db_connect;
}
function sql(){
$this->_sql = 'SELECT * FROM customers';
}
function query(){
$this->_result = mysqli_query($this->_db_connect,$this->_sql);
}
function fetch_array(){
while($this->_row = mysqli_fetch_array($this->_result)){
$username = $this->_row['first_name'];
echo "<ul>";
echo "<li>".$username."</li>";
echo "</ul>";
}
}
function db_close(){
mysqli_close($this->_db_connect);
}
}
and Import this in another class
<?php
require_once('../Config/Dbconnection.php');
include './model.php';
class CustomerDTO{
private $mysql;
function __construct() {
$database = new Database();
$this->mysql = $database->db_connect();
}
function create($customer){
$firstName = $customer->getFirstName();
$lastName = $customer->getLastName();
$emailId = $customer->getEmailId();
$mobileNumber = $customer->getMobileNumber();
$dateOfBirth = $customer->getDateOfBirth();
$phoneNumber = $customer->getPhoneNumber();
$termAndCondtion = $customer->getTermAndCondition();
$result = mysqli_query($this->mysql, "Insert into customers (first_name,last_name,email_id,mobile_number,date_of_birth,phone_number,term_and_condition)
values('$firstName','$lastName','$emailId','$mobileNumber','$dateOfBirth','$phoneNumber','$termAndCondtion')");
return $result;
}
function read(){
$result = mysqli_query( $this->mysql, "Select * from customers");
return $result;
}
function update($id, $customer){
$result = mysqli_query($this->mysql, "update customers set
first_name = ".$customer->getFirstName()."
last_name = ".$customer->getLastName()."
email_id = ".$customer->getEmailId()."
mobile_number = ".$customer->getMobileNumber()."
date_of_birth = ".$customer->getDateOfBirth()."
phone_number = ".$customer->getPhoneNumber()."
term_and_condition = ".$customer->getTermAndCondition()."
where id = ".$customer->getId());
return $result;
}
public function delete($id){
$result = mysqli_query($this->mysql, "delete from customers where id =".$id);
return $result;
}
}

PHP Class Parameters used twice

I am new to OOP, and I am switching all of my websites code to it! I am currently writing a class that grabs a user's information, and will eventually update it.
The code I am using is below:
<?php
require("C:\wamp\www\postin'\db_connection.php");
session_start();
class user {
public function __construct($userid, $connection, $information) {
$this->userid = $userid;
$this->connection = $connection;
$this->information = $information;
}
public function user_information($userid, $connection, $information) {
$query = "SELECT * FROM users WHERE id = :id";
$params = array(':id' => $userid);
try{
$stmt = $connection->prepare($query);
$result = $stmt->execute($params);
}
catch(PDOException $ex){
echo ("Failed to run query: " . $ex->getMessage());
}
$columns = $stmt->fetch();
return $columns["$information"];
}
}
$username = new user($_SESSION["logged_in"], $connection, "username");
echo $username->user_information($_SESSION["logged_in"], $connection, "username");
?>
Now as you can see on the last two lines of code (one from the end) I have to use the parameters twice. Basically the first parameter says what the ID is, second says what the $connection is, and the third is what I want to grab from the database. So what am I doing wrong? Did I define something I did not need to?
EDIT
Would the following be valid as well?
<?php
require("C:\wamp\www\postin'\db_connection.php");
session_start();
class user {
public function user_information($userid, $connection, $information) {
$query = "SELECT * FROM users WHERE id = :id";
$params = array(':id' => $userid);
try{
$stmt = $connection->prepare($query);
$result = $stmt->execute($params);
}
catch(PDOException $ex){
echo ("Failed to run query: " . $ex->getMessage());
}
$columns = $stmt->fetch();
return $columns["$information"];
}
}
$username = new user();
echo $username->user_information($_SESSION["logged_in"], $connection, "username");
?>
Like is this in-properer, or wrong...?
If the user class has all the information it needs as data members, then user_information doesn't need to take any arguments:
public function user_information() {
$query = "SELECT * FROM users WHERE id = :id";
$params = array(':id' => $this->userid);
try{
$stmt = $this->connection->prepare($query);
$result = $stmt->execute($params);
}
catch(PDOException $ex){
echo ("Failed to run query: " . $ex->getMessage());
}
$columns = $stmt->fetch();
return $columns[$this->information];
}
Since you have a lot of questions about the way a class works and about OOP I will try to give you a little direction.
There is no standard way of building your class. You are the one that decides what goes where in terms of what belongs to the class and what needs to be injected. This is just to tell you that you cannot pin yourself down. You need to get a feel for it and build a logic.
I took your class and rebuild it some with added comments. Hope that will help you some. Good luck!
<?php
require ("C:\wamp\www\postin'\db_connection.php");
session_start();
class user {
public $dbconnection;
public function __construct($connection) {
/**
* Your user class interacts with the database.
* Inject the connection here and set your
* global class variable.
*/
$this -> dbconnection = $connection;
}
public function user_information($userid, $column) {
/**
* The userid and column are specific for this
* method action. No need to set these variables
* in the global scope of the class.
*/
$query = "SELECT" . $column . " FROM users WHERE id = :id";
$params = array(':id' => $userid);
try {
$stmt = $this -> dbconnection -> prepare($query);
$stmt -> execute($params);
} catch(PDOException $ex) {
echo("Failed to run query: " . $ex -> getMessage());
}
$result = $stmt -> fetch();
return $result;
}
}
$username = new user($connection);
echo $username -> user_information($_SESSION["logged_in"], $information);
?>

Creating, Returning & Using Objects in PHP

I have a set of functions:
One creates the connection, the others do different kinds of database interaction using that function.
I am retrieving the error;
Call to undefined method mysqli::execute()
this is telling me that I am failing to send the object through correctly, I have done some research but failed to find examples;
<?php
function con(){
$mysqli = new Mysqli("localhost","user","pass","image_blog");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}else{
return $mysqli;
}};
function getAll(){
$mysqli = con();
$stmt = $mysqli->prepare("SELECT * FROM posts");
$stmt = $mysqli->execute(); <--- ERROR HERE
$stmt = $mysqli->get_result();
$stmt = $mysqli->close();
while($row = mysqli_fetch_array($stmt, MYSQL_ASSOC)) {
echo "Username: " . $row["image"];
echo "Username: " . $row["title"];
echo "Username: " . $row["text"];
echo "Username: " . $row["up"];
echo "Username: " . $row["date"];
}
};
function anotherFunction(){
}
function yetAnotherFunction(){
}
you should execute the statement ($stmt) it self not the $mysqli
$stmt->execute();
also consider using PDO class in the futur as it makes things mush easier
I see what that you're trying to achieve a connection function with your mysqli. Rather than connecting from each function individually. As Mr. Smith has mentioned, you've declared the variable $stmt like:
$stmt = $mysqli->prepare('SELECT * FROM posts');
This is incorrect as a prepared statement doesn't return data to be used in the variable, hence your error.
Another method would be to use classes, and yet another more advanced method would be to extend the mySQLi class.
Class myClass{
protected $dbh;
public function __construct(){
$this->dbh=new mysqli('','','','');
}
public function getAll(){
$this->dbh->prepare('SELECT * FROM posts');
$this->dbh->execute();
$this->dbh->bind_result($image,$title,$text,$up,$date);
while($this->dbh->fetch()){
echo"Username:".$image;
//and so on
}
$this->dbh->close();
}
public function anotherFunction(){
}
public function yetAnotherFunction(){
}
}
If you haven't used classes before you now need to create an instance of the class:
$databaseUser = myClass();
And to start your function:
$databaseUser->getAll();
It should be
$stmt->execute();
$result = $stmt->get_result();
$stmt->close();
$mysqli->close();
Instead of
$stmt = $mysqli->execute();
$stmt = $mysqli->get_result();
$stmt = $mysqli->close();
See official docs (examples too).

How would it be possible to do something like this?

I'm trying to place these in a seperate file that'll be included on every page
$sql = 'select id, name, age, address, pincode from json where name = :name';
$arr = array(":name" => $name);
// There are some 30 diff sql's and arrays
Another page
$name = 'peter';
$conn = connect();
function myType(){
global $conn;
global $sql;
global $arr;
$stmt = $conn->prepare($sql);
$stmt->execute($arr);
while( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) {
foreach ($row as $value) {
echo $value.' <br>';
}
}
}
myType();
I'm trying to keep the sqls and arrays in a separate file and use them when needed. Keeps things clean and easy to maintain. But the variables are declared later, which gives me: Notice: Undefined variable: name in C:\web\apache\htdocs\dev\json.php on line 24
Can you see a way to do this without uglying things?
Well you should use two files
sql.php
fetch.php
Then in fetch.php you will use require_once 'sql.php'
here's the code for fetch.php:
$name = 'peter';
$conn = connect();
require_once 'sql.php';
function myType(){
global $conn;
global $sql;
global $arr;
$stmt = $conn->prepare($sql);
$stmt->execute($arr);
while( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) {
foreach ($row as $value) {
echo $value.' <br>';
}
}
}
myType();
And this is sql.php
$sql = 'select id, name, age, address, pincode from json where name = :name';
$arr = array(":name" => $name);
This should be helpful and you can use sql.php whenever you like.
Storing the queries and there bound parameters in a separate include is a bit strange. How will you change the bound parameter after the include?
My suggestion is to create a model that will handle the database operations. The benefit of this is you can encapsulate the database work and keep it separate from your app logic and also easily reuse it throughout.
Basic example:
class CustomersModel
{
protected $db;
public function __construct($db)
{
$this->db = $db;
}
public function getByName($name)
{
$result = array();
$sql = 'select id, name, age, address, pincode from json where name = :name';
if($stmt = $conn->prepare($sql))
{
$stmt->execute(array(":name" => $name));
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
return $result;
}
}
Usage:
require_once('/path/to/CustomerModel.php');
$conn = connect();
$model = new CustomerModel($conn);
$customers = $model->getByName('peter');
foreach($customers as $c)
{
echo htmlspecialchars($c['name']) . '<br />;
}

using class method to pull database info

Overview: I have a function that is supposed to pull a row of the db based on its id number
Problem: It seems my function is returning, but it isn't returning anything.
Details:
-I have 2 different files used here: db_class.php and character_pull.php
-Also I have a database that contains 1 table (characters) that does contain column "id"
-there are echo lines for debugging. I will give what the output is.
character_pull.php:
<?php
include "db_class.php";
echo "made it out here1";
$classobject = new db_class();
echo "made it out here2";
$results = $classobject->getPlayerStats("1");
print_r($results);
echo "made it out here3";
$id = "id: " . $results['id'];
$name = "name: " . $results['charname'];
$strength = "strength: " . $results['strength'];
$defense = "defense: " . $results['defense'];
$health = "health: " . $results['health'];
$level = "level: " . $results['level'];
$type = "type: " . $results['type'];
$experience = "experience: " . $results['experience'];
echo"<br/>";
echo "made it out here4";
?>
db_class.php:
<?php
include "database_connect.php";
class db_class{
public function getPlayerStats($id){
echo "<br/>" . "making it in class1";
$query = "SELECT * FROM characters WHERE id = $id";
$result = mysqli_query($query);
return $char = mysqli_fetch_array($result);
$result ->close();
}
}
?>
the output I receive when I run the page is this:
made it out here1made it out here2 making it in class1made it out
here3 made it out here4
I have tried several things to fix this, but am having trouble figuring out what is wrong.
I know that this is probably extremely sloppy and primitive, but try not to laugh too hard and maybe you can help me out :P. Thanks in advance.
You have a number of issues here.
It seems your DB class is quite incomplete. To me, if I am creating a class to represent a DB connection and various operations I am going to make that connection in that class, not via some include (where I assume the connection is happening). The here is that the include will only occur conditionally if your code hits that line. In this case, since you have that include outside any actual function in the class (like a constructor) it will never be called.
I would suggest something like this to resolve this:
class db_class {
protected $mysqli;
private $db_host = 'your_db_host';
private $db_user = 'your_db_user';
private $db_password = 'your_db_password';
protected $db_name = 'default_db_name';
public __construct($db_host = NULL, $db_user = NULL, $db_password = NULL, $db_name = NULL) {
if (!empty($db_host)) {
$this->db_host= $db_host;
}
// validate other parameters similarly
$mysqli = new mysqli($this->db_host, $this->db_use, $this->db_password, $this->db_name);
if($mysqli->connect_error) {
throw new Exception('Connect Error: ' . $mysqli->connect_errno . ', ' . $mysqli->connect_error);
} else {
$this->mysqli = $mysqli;
}
}
// other class methods
}
You now have an object representing a mysqli connection store in $this->mysqli.
Your getPlayerStats() method might now look like
public function getPlayerStats($id) {
if(empty($id)) {
throw new Exception ('An empty value was passed for id');
}
// verify this is integer-like value
$id = (string)$id;
$pattern = '/^\d+$/';
if (!preg_match($pattern, $id) !== 1) {
throw new Exception ('A non-integer value was passed for id');
}
$id = (int)$id;
$query = "SELECT id, name, strength, defense, level, health, type, experience FROM characters WHERE id = :id";
$stmt = $this->mysqli->prepare($query);
$stmt->bind_param('i', $id);
$result = $stmt->execute();
if (false === $result) {
throw new Exception('Query error: ' . $stmt->error);
} else {
$obj = new stdClass();
$stmt->bind_result($obj->id, $obj->name, $obj->strength, $obj->defense, $obj->level, $obj, health, $obj->type, $obj->experience);
$stmt->fetch();
$stmt->close();
return $obj;
}
}
Note I used prepared statements here, which, you should get used to using as it is really best practice for querying databases. Note also I have added in handling of error cases all throughout the code. You should get in the habit of doing this, as it will making debugging much easier.
Just a guess but I would move this above the class name:
<?php
include "database_connect.php";
class db_class{

Categories