obtaining the results from one function and inputing it into another? - php

I have a class and a function and what I want to do is to "return" the value and input into another function.
Class test1 {
public function a($x) {
$runquery = "Select * FROM testdb where color_id = '{$x}'";
$result = mysql_query($runquery) or die(mysql_error());
$base_results = mysql_fetch_array($result);
$red = $base_results['red'];
}
public function c($red) {
$runsecond_query = "SELECT * test2db where $color = '{$red}'";
// write additional code
}
OK, so really what I would LIKE to do is to get the results from function "a" and input the result in function "c". I hope that makes sense. Thanks to anyone in advance.

Since both functions are members of the same class, you can create a class property to store them:
Class test1 {
// Private property to hold results
private $last_result;
public function a($x) {
$runquery = "Select * FROM testdb where color_id = '{$x}'";
$result = mysql_query($runquery) or die(mysql_error());
$base_results = mysql_fetch_array($result);
// Store your result into $this->last_result
$this->last_result = $base_results['red'];
}
public function c() {
$runsecond_query = "SELECT * test2db where $color = '{$this->last_result}'";
// write additional code
}
}

function a($x) {
....
return $red;
}
c(a($x));
or, if you want it to be a little more legible:
$red = a($x);
c($red);

Related

PHP method can't return two dimensional array?

Hello I stuck on really strange thing.
I'm writing simple PHP MVC WebApp for school project and I can't return two dimensional array.
I solve this problem this way:
class Post{
public $author;
public $cat;
public $table;
function getPosts($cat = ""){
dbstart();
global $dbconn;
empty($cat) ? $query = mysqli_query($dbconn, "SELECT * FROM pytania") : $query = mysqli_query($dbconn, "SELECT * FROM pytania WHERE cat = $cat");
while($row = mysqli_fetch_assoc($query)){
$output[] = $row;
$this -> table = $output;
dbstop();
}
}
}
It works perfectly when I'm calling property in controller
"poststable" => $post -> table
Gives me all four posts (two dimensional array with 4 rows) but I want to remove public $table property so I can directly call method like this way:
"poststable" => $post -> getPosts($cat)
Unfortunately, when I change my method code with this:
return $output;
$data "poststable" Gives me only first post (array stores only one post)
Anyone has idea what I'm doing wrong? Thanks in advance for help!
You need to build up the entire output in the while loop, after which you can return it. In addition, you should do your DB clean up outside the loop.
<?php
class Post{
public $author;
public $cat;
function getPosts($cat = ""){
dbstart();
global $dbconn;
empty($cat)
? $query = mysqli_query($dbconn, "SELECT * FROM pytania")
: $query = mysqli_query($dbconn, "SELECT * FROM pytania WHERE cat = $cat");
// Use an array as your return value
$output = [];
while($row = mysqli_fetch_assoc($query)){
// Build up the array
$output[] = $row;
}
// Do your clean up out here
dbstop();
// Now return the result
return $output;
}
}

Accessing class properties in PHP OOP

I am new in PHP OOP and was wondering if someone could help me with this.
I have a basic class with one method which returns data from database. Currently I am calling the method which displays everything inside the function.
Here is my class Definition:
class Products{
//properties
public $familyName = "";
public $familyProduct = "";
//Methods
public function getFamily($catId){
global $conn;
$sql = "SELECT * FROM product_family WHERE catID = '$catId'";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo "<li>".$row['familyName']."</li>";
echo "<li>".$row['familyProduct']."</li>";
}
}
}
}
Here is how I call the method:
$Products = new Products;
$Products->getFamily( 4 );
This works however, how can I assign each data coming from database ( ex familyName, familyProduct ) into variables inside class implementation and then access them individually where ever I need to. Something like this:
$Products = new Products;
$Products->familyName;
$Products->familyProduct;
I have empty properties but I am not sure how can I assign values to them coming from the loop and then return them each.
Thanks,
There are view things I would change in your Code.
Don't make Properties public use use Getters and Setters.
This will protect you Object from being used the wrong way e.g. now you can't change the familyName from outside: $products->familyName = "some value" because this would make the data of the object corrupt.
global $conn; is a no go in OOP use the construct of the Object,
in your case $products = new Products($conn);
Now you can set a Cat ID $products->setCatId(4); and read the result
$familyName = $products->getFamilyName(); or $familyProduct = $products->getFamilyProduct();
If you have more than one result you will get an array, if catId will always result one row you can delete this part. If you learn more about OOP you will find out that the hole SQL stuff can be done with a separate Object, but this is off Topic.
class Products
{
// Properties
protected $conn;
protected $catId;
protected $familyName;
protected $familyProduct;
public function __construct($conn)
{
$this->conn = $conn;
}
// set Cat ID and get date
public function setCatId($catId)
{
$this->catId = (int) $catId;
$this->getDate();
}
public function getCatId()
{
return $this->catId;
}
// get Family Name
public function getFamilyName()
{
return $this->familyName;
}
// get Family Product
public function getFamilyProduct()
{
return $this->familyProduct;
}
// get date
protected function getDate()
{
$sql = "SELECT * FROM product_family WHERE catID = '$this->catId'";
$result = $this->conn->query($sql);
// Default if no result
$this->familyName = null;
$this->familyProduct = null;
// if one Result
if ($result->num_rows == 1)
{
$row = $result->fetch_assoc();
$this->familyName = $row['familyName'];
$this->familyProduct = $row['familyProduct'];
}
if ($result->num_rows > 1)
{
$this->familyName = [];
$this->familyProduct = [];
while ($row = $result->fetch_assoc())
{
$this->familyName[] = $row['familyName'];
$this->familyProduct[] = $row['familyProduct'];
}
}
}
}

call a function where there is existing on the table

I use codeigniter mvc for my project, im making a unique id logger that if there id exist it will call the unique generator function again. how to call the function inside model
heres my model:
function getGenLogsId() {
$matches = '12345';
$sql = "SELECT * FROM tbllogs WHERE logsid LIKE '%".$this->db->escape_like_str($matches)."%'";
$q = $this->db->query($sql);
if($q->num_rows() > 0) {
// call function again
} else {
// if not exist save!!
}
}
you can call $this->getGenLogsId();
function getGenLogsId() {
$matches = '12345';
$sql = "SELECT * FROM tbllogs WHERE logsid LIKE '%".$this->db->escape_like_str($matches)."%'";
$q = $this->db->query($sql);
if($q->num_rows() > 0) {
$this->getGenLogsId();
} else {
// if not exist save!!
}
}
if it's in the same controller use :
$this->function();
if it's in the model:
$this->load->model('ModelName');
$this->ModelName->function();
NOTE
if it's in the controller it's a good practice to make it a private function so no direct call is allowed to that function by starting the function name with _
Example:
function _test(){
}

PHP OOP query is not executing

I am using PHP with OOP to select rows from the database (MySQL).
When I execute the query, it returns an empty row.
Here is the classe I am using:
<?php
class EmploiManager
{
private $_db;
public function __construct($db)
{
$this->setDb($db);
}
public function category($category)
{
$q = $this->_db->prepare('SELECT * FROM DemandeEmploi WHERE category = :category');
$q->execute(array('category' =>$category));
$donnees = $q->fetch(PDO::FETCH_ASSOC);
return new Emploi($donnees);
}
public function setDb(PDO $db)
{
$this->_db = $db;
}
}
$type = $_GET['category'];
$manager = new EmploiManager($db);
$row = $manager->category($type);
foreach ($row as $demandeE)
{
?>
<div class="list"><h4><? echo $demandeE->title();?></h4> </div>
<?php
}
?>
Can any one tell me what's wrong with that code?
Thanks!
It's my bad, I didn't use a loop to select all the rows.
I corrected the code and it works fine now, here is what it looks like:
public function category($category)
{
$datas = array();
$q = $this->_db->prepare('SELECT * FROM DemandeEmploi WHERE category = :category');
$q->execute(array('category' =>$category));
while ($donnees = $q->fetch(PDO::FETCH_ASSOC))
{
$datas[] = new Emploi($donnees);
}
return $datas;
}
$q->fetch() just returns one row of the results. If you want all the results, you must use $q->fetchAll().
Since you specified PDO::FETCH_ASSOC, the elements of $row will be associative arrays, not objects; aren't you getting errors saying that you're trying to call a method on a non-object? So $demandeE->id() should be $demandeE['id'], and $demandeE->title() should be $demandeE['title'].
Alternatively, you could specify PDO::FETCH_OBJ. Then, the values will be properties, not methods, so it should be $demandeE->id and $demandeE->title (no parentheses).

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