assign result of function call to variable in oop php - php

I have made a function for fetching data from a DB. It was working fine. Now I want to do it using OOP, as I am new to OOP I am not getting whats going Wrong. Help me out guys I'm not able to assign the value of function call to variable.
class user_functions
{
function select_data($sql)
{
global $conn;
$result_final = array();
$result=mysqli_query($conn,$sql);
while($row=mysqli_fetch_assoc($result))
{
$result_final[] = $row;
}
return $this->result_final;
}
}
$test = new user_functions;
$sql= "some Query";
$result =$test->select_data($sql,$conn);

class user_functions
{
function select_data($sql)
{
global $conn;
$result_final = array();
$result=mysqli_query($conn,$sql);
while($row=mysqli_fetch_assoc($result))
{
$result_final[] = $row;
}
return $result_final;
}
}

Related

Functions with `$this` don't work in Base class PHP

I have recently started working with OO PHP and I've come across an error.
I have a base class BaseController.php
and a class DatabaseController.php which extends BaseController.php
At the moment these classes are pretty basic but I want a few reusable functions in Base and overall this has been successful.
However, I am trying to use functions in the Base Controller together and it seems functions with $this->functionName(); don't return anything.
Here is my code to further explain:
Base Controller
public function connectDB() {
$conn = mysqli_connect("localhost", "root", "", "db_name");
return $conn;
}
public function getSource($id) {
$conn = $this->connectDB();
$sql = "SELECT * FROM sources WHERE id = '$id'";
$query = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($query)) {
$name = $row['slug'];
}
return $name;
}
public function mapColumnsToFunctions($row) {
foreach($row as $key => $value) {
if($key == "source") {
$result = $this->getSource($value);
$row["source_slug"] = $result;
}
return $row;
}
}
Database Controller
class DatabaseController extends BaseController {
public function getDataItem($type, $id) {
$conn = $this->connectDB();
$id = $this->checkField($id, "");
$sql = "SELECT * FROM $type WHERE id = '$id'";
$query = mysqli_query($conn, $sql);
$response = array();
while($row = mysqli_fetch_assoc($query)) {
$response[$type][] = $this->mapColumnsToFunctions($row);
}
$response = json_encode($response);
return $response;
}
}
I should be seeing a JSON response with source_slug as a field but this isn't coming through to the feed.
{
"id": "213023",
"name": "Source Name",
"url": "http://sample.url",
"source": "1"
// NO source_slug: "english equiv of 1"
},
mapColumnsToFunctions has a return statement inside the foreach loop. So it returns immediately during the first iteration, even if it hasn't updated anything in $row.
The return statement should be after the loop.
public function mapColumnsToFunctions($row) {
foreach($row as $key => $value) {
if($key == "source") {
$result = $this->getSource($value);
$row["source_slug"] = $result;
}
}
return $row;
}
The loop seems unnecessary (unless it's an abbreviation of what you're really doing). It could be rewritten as:
public function mapColumnsToFunctions($row) {
if (isset($row["source"])) {
$row["slug_source"] = $this->getSource($row["source"]);
}
return $row;
}

sql querying by class and function

So i'm new to classes and functions and I'm trying to do one sql query for the entire class for every function to use. I'm a little confused on how it works. From other examples that I've seen the call the query every single function which seems like a lot of usage. (why not call it once and set them all) I know there is an easier way by just querying and making variables including a db file or whatever. This is just practice.
<?php
//User System
class usrsys
{
$results = mysqli_query($con, "SELECT * FROM users WHERE id = '".$_SESSION['coid']."'");
while($row = mysqli_fetch_array($results)) {
$fname = $row['fname'];
}
function username()
{
echo $_SESSION['Username'];
}
function fname()
{
echo $fname;
}
}
//Setting Variable
$user = new usrsys();
?>
Then I call the functions in the next file by:
<?php $user->fname(); ?>
class usrsys
{
public $fname;
public $con;
public function __construct() {
//load your conection class function here and pass it to the $this->con variable.
$results = mysqli_query($this->con, "SELECT * FROM users WHERE id = '".$_SESSION['coid']."'");
while($row = mysqli_fetch_array($results)) {
$this->fname = $row['fname'];
}
}
function username()
{
echo $_SESSION['Username'];
}
function fname()
{
echo $this->fname;
}
}
//Setting Variable
$user = new usrsys();
$user->fname();

Assigning SQL Statement to Class Variable

I stated to build up my Database Class.
Here is a part of my database class.
public function query($sql)
{
return $this->getPdo()->query($sql);
}
My Class is working but i want to improve it.
This is external part of class:
$db = new Database();
$q = $db->query('SELECT * FROM table');
while($r = $q->fetch(PDO::FETCH_ASSOC)){
$results[] = $r;
}
echo "<pre>";
print_r($results);
echo "</pre>";
I want to get while part inside database class like
public function query($sql)
{
return $this->getPdo()->query($sql);
}
public function getAll() {
while($r = $this->query($sql)->fetch(PDO::FETCH_ASSOC)){
$results[] = $r;
}
return $results;
}
But i know this part is wrong : $this->query($sql)->fetch(PDO::FETCH_ASSOC); How can i fix it ? I have to declare a class varible like $sql, and i have to assign sql statement to $sql varible.
But i couldn't. How can i do that ?
$q = $db->query('SELECT * FROM table');
$results = $q->fetchAll();
echo "<pre>";
print_r($results);
echo "</pre>";
One of your biggest problems is that when you write
public function getAll() {
while($r = $this->query($sql)->fetch(PDO::FETCH_ASSOC)){
$results[] = $r;
}
return $results;
}
you are causing the database to run the query with each iteration of the loop.
To correct the code as it is defined simply run the query outside of the loop then use fetch as the loop condition:
public function getAll() {
$stmt = $this->query($sql);
while($r = $stmt->fetch(PDO::FETCH_ASSOC)){
$results[] = $r;
}
return $results;
}
Another problem that is probably probably causing you grief is that the $sql value appears to be coming from out of thin air. You should pass it into your getAll function to have access to it.
To avoid all this noise you might want to just follow #YourCommonSense's suggestion and use the available PDO getAll method.
public function getAll($sql){
return $this->query($sql)->fetchAll(PDO::FETCH_ASSOC);
}
You need to pass the $sql parameter to your getAll() method, and then use return to get the result back out. So this method becomes:
public function getAll($sql) {
while($r = $this->query($sql)->fetch(PDO::FETCH_ASSOC)){
$results[] = $r;
}
return $results;
}
Then you use it externally like:
$db = new Database();
$results = $db->getAll('SELECT * FROM table');
echo "<pre>";
print_r($results);
echo "</pre>";

How to convert Mysqli results into an array in OO Php

I want to retrieve data from a table in database and display the result in an array in the form below.
array("1"=>"Value 1", "2"=>"value2")
Here is the function I tried using but I get error when I try to display the array. Please I need help on this. I'm new to OO Php.
<?php
class query {
public function listfields (){
$result = $this->mysqli->query("SELECT id, name FROM fields", MYSQLI_USE_RESULT);
while($row=$result->fetch_assoc()){
$this->fields[$row["id"]] = $row["name"];
}
$result->free();
}
public function fields(){
return $this->fields;
}
}
$list = new query;
$list->listfields();
$field1 = $list->fields();
echo $field1;
?>
Instead of your function fields, you will need a property fields, which you can access.
Furthermore i suggest using getters and setters instead of a public property, im sure you will find out how.
This will return the Data in form array("1"=>"Value 1", "2"=>"value2").
class query {
public $fields;
public function fillfields ()
{
$result = $this->mysqli->query("SELECT id, name FROM fields", MYSQLI_USE_RESULT);
while($row=$result->fetch_assoc()){
$this->fields[] = $row["name"];
}
$result->free();
}
$list = new query;
$list->fillfields();
$field1 = $list->fields[1];
echo $field1;
Try This.
<?php
class query {
public function listfields (){
$fields = array();
$rowcnt =1;
$result = $this->mysqli->query("SELECT id, name FROM fields", MYSQLI_USE_RESULT);
while($row=$result->fetch_assoc()){
$this->fields[$row["id"]] = $row["name"];
//$this->fields[$rowcnt] = $row["name"]; // if you want different indexing.
$rowcnt++;
}
$result->free();
}
public function fields(){
return $this->fields;
}
}
$list = new query();
$list->listfields();
$field1 = $list->fields();
var_dump($field1);
?>

PHP OOP: How to get database rows as objects?

I can do this when selecting a single row fine but cant quite get my head around doing this for multiple rows of data.
For the single row I simply instantiate a new object that does a number of operations behind the scenes that bascially produces a row from the database as our object.
Example:
$object = new Classname($param);
foreach($object->row as $key=>$value) {
echo $key.":".$value."\n";
}
//output
id:1
firstname:steve
lastname:took
etc...
Any clever people here able to point me in the right direction please?
NOTE: just want to be able to create an object for each row rather than the one object with nested arrays
EDIT: sorry $object->row is a member of the class that stores selected row from the database
If I got you the answer is pretty simple mysql_fetch_object
Example:
while ($row = mysql_fetch_object($result)) {
echo $row->user_id;
echo $row->fullname;
}
Why don't you consider to use an ORM (Object Relational Mapper), like Doctrine or Propel?
I prefer Doctrine: http://www.doctrine-project.org/
Enjoy! :)
Here is an example
class users extends db {
public $users_id = 0;
public $users_group = 0;
public $users_firstname = 0;
public $users_lastname = 0;
public function open($id) {
if (is_numeric($id)) {
$sql = "SELECT * FROM users WHERE users_id = '$id'";
$res = parent::DB_SELECT($sql);
if (mysql_num_rows($res) <> 1) {
return 0;
}
} else {
$sql = "SELECT * FROM users " . $id;
$res = parent::DB_SELECT($sql);
if (mysql_num_rows($res) <= 0) {
return 0;
}
}
$data = array();
while ($row = mysql_fetch_array($res)) {
$this->users_id = $row['users_id'];
$this->users_group = $row['users_group'];
$this->users_firstname = $row['users_firstname'];
$this->users_lastname = $row['users_lastname'];
$data[] = (array) $this;
}
return $data;
}
public function setUsersId($users_id) { $this->users_id = addslashes($users_id); }
public function getUsersId() { return stripslashes($this->users_id); }
public function setUsersGroup($users_group) { $this->users_group = addslashes($users_group); }
public function getUsersGroup() { return stripslashes($this->users_group); }
public function setUsersFirstname($users_firstname) { $this->users_firstname = addslashes($users_firstname); }
public function getUsersFirstname() { return stripslashes($this->users_firstname); }
public function setUsersLastname($users_lastname) { $this->users_lastname = addslashes($users_lastname); }
public function getUsersLastname() { return stripslashes($this->users_lastname); }
}
You could use MySQLi.
// Connect
$db = new mysqli('host', 'user', 'password', 'db');
// Query
$users = $db->query('SELECT * from users');
// Loop
while($user = $users->fetch_object()) {
echo $users->field;
}
// Close
$users->close();
$db->close();
More info here: http://php.net/manual/en/book.mysqli.php

Categories