I have a array i want its value to be "public $somevariable". Here is my function how it looks like.
public function __construct(){
global $database;
$result = $database->query("SHOW COLUMNS FROM ".self::$tabel_name."");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
if (mysql_num_rows($result) > 0) {
$attributes_var = array();
while ($row = $database->fetch_array($result)) {
$attributes_var[] = $row[0];
}
}
foreach($attributes_var as $key)
{
public $$key;
}
}
But its showing syntax error on "public $$key". I want to use the dynamic generated variable as public variable and want to use them outside the class.
Any suggestion?
Thank you!
You can do like below, the default value is null.
foreach($attributes_var as $key)
{
$this->{$key} = null;
}
Related
I have a database phpmyadmin, I created a class :
<?php
class Ticket
{
private $NumDossier = 0;
private $NomTicket ="";
private $Service = "" ;
private $Impact = 0;
private $Urgence = "";
private $DateOuverture = "";
public function __construct($p_NumDossier, $p_NomTicket,$p_Service,$p_Impact,$p_Urgence,$p_DateOuverture)
{
$this->NumDossier = $p_NumDossier;
$this->NomTicket = $p_NomTicket;
$this->Service = $p_Service;
$this->Impact = $p_Impact;
$this->Urgence = $p_Urgence;
$this->DateOuverture = $p_DateOuverture;
}
public function getNumDossier()
{
return $this->NumDossier;
}
public function getNomTicket()
{
return $this->NomTicket;
}
public function getService()
{
return $this->Service;
}
public function getImpact()
{
return $this->Impact;
}public function getUrgence()
{
return $this->Urgence;
}
public function getDateOuverture()
{
return $this->DateOuverture;
}
}
?>
For all row that my query return I want to create an object and add it to a collection.
My code :
$connexion = cnx();
if($connexion) {
$requete="SELECT * FROM ticket '";
$result = mysqli_query($connexion, $requete);
$result = mysqli_query($connexion, $requete);
$row = mysqli_fetch_assoc($result);
}
$test = new Ticket(0,"","",0,"","");
while($row) {
//create object for each line and add it to an collection
}
If you have a solution/lead me to this issue.
Thanks for read !
I have to assume that the beginning part of your code is correct, so I copied that. But I changed it further on. You want to retrieve multiple rows, so I put the mysqli_fetch_assoc inside the while loop. With each new row I create a new ticket and put it in a 'collection' array.
$connection = cnx();
if ($connexion) {
$query ="SELECT * FROM ticket";
$result = mysqli_query($connection, $query);
if ($result === false) die("The query [$query] could not be executed.");
$collection = [];
while($row = mysqli_fetch_assoc($result)) {
$collection[] = new Ticket($row["NumDossier"],
$row["NomTicket"],
$row["Service"],
$row["Impact"],
$row["Urgence"],
$row["DateOuverture"]);
}
echo "<pre>";
print_r($collection);
echo "</pre>";
}
So I used a simple array for the collection. I used the default numeric array indexing because I wouldn't know what to replace it with. $row["NomTicket"] seems a logical choice.
I have three functions that returns all parents for specific child with user_id with recursive query.
All these functions works good ..but the problem begins when I start use foreach loop to return multiple user parent names in function
merge_comments_data..
note : t_relation means = parent_id
class News extends front_end {
public $parents_names;
function merge_comments_data($related_comments) {
foreach ($related_comments as $comment) {
$full_name = $this->get_parents_names($comment['cn_visitor_id']);
}
echo "<pre>";
print_r($names);
echo "</pre>";
exit;
}
//// all these function to get full parent names by user id
function get_parents_names($user_id = 0) {
$this->user_parent_name($user_id);
echo $this->parents_names;
}
function user_parent_name($user_id = 0) {
// clear the variable at first
$result = $this->get_parents($user_id);
if (is_object($result)) {
$this->parents_names .= ' ' . $result->t_name . ' ';
if ($result->t_relation != 0) {
$this->user_parent_name($result->t_relation);
}
}
}
public function get_parents($user_id = 0) {
$result = $this->db->query("SELECT * FROM d_tree where t_id = '$user_id'");
if (is_object($result->row())) {
$result = $result->row();
} else {
$result = '';
}
return $result;
}
I have made a template system but the {var} doesnt output the worth.
It just output {var}.
Here is my template class:
<?php
class Template {
public $assignedValues = array();
public $tpl;
function __construct($_path = '')
{
if(!empty($_path))
{
if(file_exists($_path))
{
$this->tpl = file_get_contents($_path);
}
else
{
echo 'Error: No template found. (code 25)';
}
}
}
function assign($_searchString, $_replaceString)
{
if(!empty($_searchString))
{
$this->assignedValues[strtoupper($_searchString)] = $_replaceString;
}
}
function show()
{
if(count($this->assignedValues) > 0)
{
foreach ($this->assignedValues as $key => $value)
{
$this->tpl = str_replace('{'.$key.'}', $value, $this->tpl);
}
}
echo $this->tpl;
}
}
?>
And here is what I execute on the index:
<?php
require_once('inc/classes/class.template.php');
define('PATH', 'tpl');
//new object
$template = new Template(PATH.'/test.tpl.html');
//assign values
$template->assign('title', 'Yupa');
$template->assign('about', 'Hello!');
//show the page
$template->show();
?>
I really need some help, if you can help I'd would be very grateful.
Instead of line:
$this->assignedValues[strtoupper($_searchString)] = $_replaceString;
You should have:
$this->assignedValues[$_searchString] = $_replaceString;
and it will work.
Of course I assume that inside your template file you have content:
{title} {about}
You should change
$this->assignedValues[strtoupper($_searchString)] = $_replaceString;
to this:
$this->assignedValues["{".$_searchString . "}"] = $_replaceString ;
this will only replace your keywords with values.
Getting an illegal offset type error on this line in the second foreach loop.
$userlist[$user]->addPeriod($period);
Made some changes from past info given in past threads and this is the new version of the code. There is also a warning but I think that might be resolved if the error is resolved:
Call to a member function addPeriod() on a non-object
$periods_arr = array(1, 2, 3, 4, 5);
$subPeriods_arr = array(1, 2);
$questionslist = array("q_1_1", "q_1_2", "q_2_1", "q_2_2", "q_3_1", "q_4_1", "q_5_1");
class User {
public $userId;
public $periods = array();
public function __construct($number)
{
$this->userId = $number;
}
public function addPeriod($pno)
{
$this->periods[] = new Period($pno);
}
}
class Period {
public $periodNo;
public $subPeriods = array();
public function __construct($number)
{
$this->periodNo = $number;
}
public function addSubPeriod($spno)
{
$this->subPeriods[] = new SubPeriod($spno);
}
}
class SubPeriod {
public $SubPeriodNo;
public $answers = array();
public function __construct($number)
{
$this->SubPeriodNo = $number;
}
public function addAnswer($answer)
{
$this->answers[] = new Question($answer);
}
}
class Question {
public $answer;
public function __construct($ans)
{
$this->answer = $ans;
}
public function getAnswer()
{
echo $answer;
}
}
$userlist = array();
$sql = 'SELECT user_ref FROM _survey_1_as GROUP BY user_ref ORDER BY user_ref ASC';
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result))
{
$userlist[] = new User($row['user_ref']);
}
foreach ($userlist as &$user)
{
foreach ($periods_arr as &$period)
{
$userlist[$user]->addPeriod($period);
foreach ($subPeriods_arr as &$subPeriod)
{
$userlist[$user]->periods[$period]->addSubPeriod($subPeriod);
foreach($questionslist as &$aquestion)
{
$sql = 'SELECT ' . $aquestion . ' FROM _survey_1_as WHERE user_ref = ' .
$user . ' AND answer_sub_period = ' . $subPeriod . ' AND answer_period = ' . $period .'';
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result))
{
$userlist[$user]->periods[$period]->subPeriods[$subPeriod]->addAnswer($row[$questionNumber]);
}
}
}
}
}
$userlist[3]->periods[3]->subPeriods[1]->getAnswer();
You're using $user as a key into your $userlist array, but you're fetching it as a value. Try something like this:
foreach ($userlist as $user => $userVal)
{
...
$userlist[$user]->addPeriod($period);
}
This makes $user the key into your $userlist array.
It would be even clearer to do something like this:
foreach ($userlist as $user)
{
}
And then don't use $user as a key into your array, but just use $user as the value. For example:
$user->addPeriod($period);
...
$user->periods[$period]->addSubPeriod($subPeriod);
I'm am unsure on how to move part of my code into a class.
<?php
class InfoTest {
private $info_results;
public function __construct() {
$dbc = get_dbc();
$info = $dbc->query ("SELECT info_id, info_title FROM text");
if ($dbc->error) {
printf("Error: %s\n", $dbc->error);
}
while ($info_row = $info->fetch_array())
{
$info_results[]= $info_row;
}
$info->free();
$this->info_results = $info_results;
}
public function setInfo() {
$this->info_results = $info_results;
}
public function getInfo() {
return $this->info_results;
}
public function __destruct() {
}
}
?>
<?php
$display = new InfoTest();
foreach ($display->getInfo() as $info_row) {
?>
<!-- html -->
<?php echo $info_row['info_title']."</a><br />"; ?>
<!-- html -->
Sub-Info:
<?php
$dbc = get_dbc();
$si_title = $dbc->query ("SELECT info_title FROM text WHERE info_id = ".$info_row['info_id']."");
if ($dbc->error) {
printf("Error: %s\n", $dbc->error);
}
$num =$si_title->num_rows;
$count = 0;
while ($sub_info = $si_title->fetch_array())
{
$sub_info_title = $sub_info['info_title'];
if ($count!=$num-1)
{
echo $sub_info_title." , ";
$count++;
}
else echo $sub_info_title;
}
?>
<!-- html -->
<?php } ?>
I'm unsure how to move the Sub-Info(code after Sub-Info:) into a class. Does it go in the same class as InfoTest, a class of its own, or doesn't go into a class at all?
Sub-Info Code:
<?php
$dbc = get_dbc();
$si_title = $dbc->query ("SELECT info_title FROM text WHERE info_id = ".$info_row['info_id']."");
if ($dbc->error) {
printf("Error: %s\n", $dbc->error);
}
$num =$si_title->num_rows;
$count = 0;
while ($sub_info = $si_title->fetch_array())
{
$sub_info_title = $sub_info['info_title'];
if ($count!=$num-1)
{
echo $sub_info_title." , ";
$count++;
}
else echo $sub_info_title;
}
?>
In your class you have already all information. So an alternative to a sql-query could be an additional method, which searches all titles with a special id in the private field info_results. E.g.:
public function getInfoTitles($info_id) {
$titles = array();
foreach ($this->info_results as $info_row) {
if ($info_row['info_id'] == $info_id)
$titles[] = $info_row['info_title'];
}
}
return $titles;
}
Your Sub-Info Code is then:
echo implode(', ', $display->getInfoTitles($info_row['info_id']));
The general idea of OOP is to couple data with methods that process that data. So, if you feel that some piece of your data are processed in the same way multiple times, it's a good idea to introduce a class that will incapsulate that data and logic.
Of course it emerges a lot of other questions: how many classes should one have, how should they interact with each other, which part of business logic should go in which class etc. There is no universal, always-true answer to that questions, but some general approaches to address that questions were developed: the design patterns. There are some books on the topic, one of the most known is Gang-of-Four (GoF) Design Patterns.
That's general thoughts on the topic. In your particular case, I would suggest you creating new class ItemInfo, so InfoTest class is responsible only for quering the DB and creating Instances of this new class.
class InfoTest {
private $items;
public function __construct() {
$this->items = new Array();
}
private function queryItems($itemId){
$dbc = get_dbc();
$info = $dbc->query("SELECT info_id, info_title FROM text");
if ($dbc->error) {
printf("Error: %s\n", $dbc->error);
}
while ($info_row = $info->fetch_array())
{
$item = new ItemInfo($info_row);
$this->items[] = $item;
}
$info->free();
}
public function getItems($itemId){
if (empty($this->items)){
$this->queryItems($itemId);
}
return $this->items;
}
/* Other functions. */
public function __destruct() {
}
}
Class ItemInfo{
private $id, $title;
function __construct(Array $params){
$this->id = $params['item_id'];
$this->title = $params['item_title'];
}
function getTitle(){
return $this->title;
}
function toString(){
retirn "I'm item {$this->id}, my title is {$this->title}";
}
}
And your code will be as simple as
$item_test = new ItemTest();
$items = $item_test->getItems($item_id);
$titles = array();
foreach ($items as $item){
//you may process your items in any way you need
$titles[] = $item->getTitle();
}
echo implode(',', $titles);