How to change a class variable in PHP? - undefined

I'm sure there is an easy answer to this question, but for the life of me, I can't find it. I'm using PHP5 and I'm trying to change the value of a class variable, but it doesn't appear to change. For example, I have something like this:
<?php
include_once "../includes/global.php";
loadDAOs('yweightGroups','yweightCourses','yweightUsers','user','yweightData');
class yweight {
private $header_includes;
private $user;
private $yweightUser;
//Description:
// Constructor.
//Parameters:
// -none-
//Returns:
// -nothing-
function __construct() {
global $r_action;
global $r_page;
$this->user = login_required();
if(!$this->user || empty($this->user)){
die();
goHome();
}
$this->header_includes = "";
if(isset($r_action)) {
$this->$r_action();
}
else if (isset($r_page)) {
$this->$r_page();
}
else {
$this->draw();
}
}
//Description:
// Draws the YWeight page
//Parameters:
// -none-
//Returns:
// -nothing-
function draw() {
global $r_page;
global $colorDAO;
global $yweightUsersDAO;
ob_start();
?>
<script type='text/javascript' src="./yweight.js"></script>
<link rel="stylesheet" type="text/css" href="yweight.css" />
<?php
$this->header_includes .= ob_get_clean();
$col = $colorDAO->read(17);
print_top("",$this->header_includes,"resources","",$col->value,$col->fontcolor);
$users = $yweightUsersDAO->GetByUserID($this->user->id);
if(!$users){
echo "<div class='msg_failed'>You are not authorized to view this page.</div>";
die();
}
$this->yweightUser = $users;
echo serialize($this->yweightUser[0]);
?>
<div id="yweight_area"></div>
<script type='text/javascript'>
<?php
if($users[0]->yweightUsers_intern == 0)
echo "drawPage('main_participant');";
else
echo "drawPage('main_intern');";
?>
</script>
<?php
print_bottom();
echo ob_get_clean();
}
//Description:
// Draws the main intern page.
//Parameters:
// -none-
//Returns:
// -nothing-
function main_intern() {
ob_start();
echo "hello intern";
echo ob_get_clean();
}
//Description:
// Draws the main participant page.
//Parameters:
// -none-
//Returns:
// -nothing-
function main_participant() {
global $yweightDataDAO;
ob_start();
$this->yweightUser = $this->yweightUser[0];
echo serialize($this->yweightUser);
?>
<div id="banner_div">
<img class="banner" width="927" src="images/ParticipantsMain.jpg" />
<img id="tracker_btn" class="std_btn" src="images/trackerButton.png" />
<img id="summary_btn" class="std_btn" src="images/summaryButton.png" />
<img id="requirements_btn" class="std_btn" src="images/reqButton.png" />
</div>
<div id="discussion_board_input_div">
<textarea id="discussion_board_input" />
<?php
echo build_btn("green",100,25,"Submit","","","","",
'submit_post()',"margin-top:5px; margin-bottom:5px; float:right;");
?>
<div class="clear_floats" />
</div>
<div id="discussion_board_div">
</div>
<?php
echo ob_get_clean();
}
function submit_post(){
global $yweightDataDAO;
global $userDAO;
global $r_post;
echo serialize($this->yweightUser);
$userDataID = $yweightDataDAO->GetByUserID($this->yweightUser->user_id);
if($userDataID){
$userData = $yweightDataDAO->read($userDataID);
$userDiscussion = unserialize($userData->yweightData_discussionBoard);
}
$userDiscussion[$this->user->firstName . time()] = $r_post;
$userData->yweightData_discussionBoard = serialize($userDiscussion);
$yweightDataDAO->save($userData);
}
}
$recs = new yweight();
?>
submit_post() is an ajax called function. The error I'm getting is that it says $this->yweightUser is undefined. I didn't orignally include all of the code because I thought that I was just misunderstanding how class variables are declared.

You have a typo. Use __construct. Two (_ _) underscores. Your fooVariable is never getting set. After it gets set it works fine.
Update: You only set $this->yweightUser in your function draw() method. If you don't call draw() before ajax_post() or w/e, it will not be defined.

As mentioned above, fix the syntax errrors and it works, 2 underscores for the constructor and opening brace for the constructor and also brackets for arguments:
class foo {
protected $fooVariable;
function __construct () {
$this->fooVariable = "hello world";
$this->changeVariable();
}
function changeVariable(){
$this->fooVariable = "goodbye world";
$this->echoVariable();
}
function echoVariable(){
echo $this->fooVariable;
}
}
$foo = new foo();

Related

autocomplete get data from database didn't work

hye,I want to do the autocomplete for a system. I review a tutorial from here -> [http://cahbagusnongkrong.blogspot.my/2016/11/membuat-autocomplete-dari-database.html.]
the problem is my autocomplete still didn't works eventho I do the same as the tutorial did (just change the name)
so here is my controller:
public function __construct()
{
parent::__construct();
$this->load->model('Kepakaran_m');
$this->load->helper('url', 'form');
}
public function index()
{ $this->load->helper('form');
$autocomp_bidang = $this->Kepakaran_m->get_bidang();
$this->template->set('autocomp_bdg', $autocomp_bidang);
$this->template->set('kepakaran',$kepakaran_staff);
$this->template->render('profil/profilpersonal');
}
public function get_bidang() {
$keyword = $this->uri->segment(3);
$data = $this->dbsmk->from('kexpt103kodbidang')->like('bidang',$keyword)->get();
foreach($data->result() as $row)
{
$arr['query'] = $keyword;
$arr['suggestions'][] = array(
'value' =>$row->bidang
);
}
echo json_encode($arr);
}
and my model is as written below :
function get_bidang(){
$sql= "SELECT bidang FROM kexpt103kodbidang ORDER BY bidang";
$query = $this->dbsmk->query($sql);
return $query->result();}
my view is here :
<div class="col-sm-4 col-sm-offset-1">
<div class="form-group">
<div class="col-md-12">
<input type="text" class="form-control autocomplete" name="bidang" id="bidang" autofocus/>
</div>
</div>
</div>
<script type="text/javascript">
var site = "<?php echo site_url();?>";
$(function(){
$('#bidang').autocomplete({
serviceUrl: site+'expert/get_bidang',
});
});
</script>
You need to debug your functionality. First check is your controller working.
You can try below code :
<script type="text/javascript">
var site = "<?php echo site_url();?>";
$(function(){
$('#bidang').autocomplete({
serviceUrl: site+'expert/get_bidang/'+$(this).val()
});
});
</script>
You need to pass value for keyword. Also try to check using firebug which URL actually being called.
Try to debug by printing results before sending from controller. You can also try with static array from controller.
Let me know if any issue in debugging.

yii2 register js code in a view

What is the best way to register js code in yii2 view?
1
<?php
$this->registerJs(
'$("document").ready(function(){ alert("hi"); });'
);
?>
2
<?php
$this->registerJs('alert("hi");', View::POS_READY);
?>
3
<?php
$script = "function test() { alert('hi');}";
$this->registerJs($script, View::POS_END, 'my-options');
?>
Yii2, write code in views
<h2>Content</h2>
<?php
$script = <<< JS
alert("Hi");
JS;
$this->registerJs($script);
?>
<?php
$this->registerJs( <<< EOT_JS_CODE
// JS code here
EOT_JS_CODE
);
?>
So you have not to escape js code
https://www.yiiframework.com/doc/guide/2.0/en/output-client-scripts
I prefer use richardfan's widget:
use richardfan\widget\JSRegister;
<?php JSRegister::begin(['position' => static::POS_BEGIN]); ?>
<script>
alert('Hello world');
</script>
<?php JSRegister::end(); ?>
I have created a trivial widget that allows me to keep the code clean and allow proper parsing by the IDE.
common/widget/InlineScript.php
<?php namespace common\widgets;
/**
* Easily add JS to the end of the document.
*/
class InlineScript {
/**
* Open output buffer.
*/
public static function listen() {
ob_start();
}
/**
* Capture the output buffer and register the JS.
*
* #param yii\web\View $view The view that should register the JS.
*/
public static function capture($view) {
$view->registerJs(preg_replace('~^\s*<script.*>|</script>\s*$~ U', '', ob_get_clean()));
}
}
usage example (within view)
<?php ob_start(); ?>
<script>
alert('asd');
</script>
<?php $this->registerJs(preg_replace('~^\s*<script.*>|</script>\s*$~ U', '', ob_get_clean())) ?>
As you see, this does use output buffers, so one needs to be carefull about using this. If every listen() isn't followed by exaclty one capture() you might get into debugging nightmare :)
Multiple ways to do this
Way 1:
$script = "
$('.summary').append('<div class=\'pull-right\'><button class=\'btn btn-xs\' style=\'background:#ffb3b3;border-color:#ffb3b3;pointer-events:none;height:15px;width:15px\'></button> No BOM Available</div>');
";
$this->registerJs($script);
Way 2:
$js = <<< 'SCRIPT'
$(document).on('ready pjax:success', function(){
$('.select-on-check-all').change(function () {
if ($('.select-on-check-all').is(":checked")) {
$('#myTable tr').find("input[type='checkbox']:checked").each(function () {
keysArr.push($(this).val());
});
} else {
$('#myTable tr').find("input[type='checkbox']:not(:checked)").each(function () {
var index = keysArr.indexOf($(this).val());
if (index != -1) {
keysArr.splice(index, 1);
}
});
}
sessionStorage.setItem("keysArr", keysArr);
});
});
SCRIPT;
$this->registerJs($js, \yii\web\View::POS_READY);
I hope this helps

Zend error Connection

I have a problem with my code, the first code is like
<?php
require_once('zend/json.php');
require_once('zend/db.php');
//require_once 'Zend/Db/Adapter/Pdo/pgsql.php';
class jsonvi
{
protected $_db;
public function _koneksi ()
{
try
{
$this->_db = zend_db::factory('PDO_PGSQL',array(
'host'=>'localhost',
'username'=>'stet',
'password'=>'test',
'dbname'=>'test'
));
return $this->_db;
}
catch(zend_db_exception $e)
{
return $e->getmessage();
}
}
public function getdata()
{
$db = $this->_koneksi();
try
{
$sql = "select * from info ";
$da = $db->fetchall($sql);
$num = count($da);
for ($a=0;$a<$num;$a++)
{
$data = $db->fetchall($sql);
return $data;
}
}
catch (zend_db_exception $e)
{
return $e->getmessage();
}
}
}
$view = new jsonvi();
$view = $view->getdata();
echo zend_json::encode($view);
?>
and it works well, but I want to make it like
<?php
include ('table.php');
include ('config.php');
require_once('zend/json.php');
require_once('zend/db.php');
require_once 'Zend/Db/Adapter/Pdo/pgsql.php';
class jsonvi
{
protected $_db;
public function _koneksi ()
{
try
{
$this->_db = zend_db::factory('PDO_PGSQL',array(
'host'=>$dbhost,
'username'=>$dbuser,
'password'=>$dbpass,
'dbname'=>$dbdb
));
return $this->_db;
}
catch(zend_db_exception $e)
{
return $e->getmessage();
}
}
public function getdata()
{
$db = $this->_koneksi();
try
{
$sql = "select * from ".$table;
$da = $db->fetchall($sql);
$num = count($da);
for ($a=0;$a<$num;$a++)
{
$data = $db->fetchall($sql);
return $data;
}
}
catch (zend_db_exception $e)
{
return $e->getmessage();
}
}
}
$view = new jsonvi();
$view = $view->getdata();
echo zend_json::encode($view);
?>
I don't know whats wrong with this code, I need help.
the error message Notice: Undefined variable: dbdb in C:\wamp....
The config.php is only have code like $dbpass = 'test'; and like that, I'm creating a simple web and I want to make my code to other database and aplikasi, so I only changed the config.php and the table.php
for the table.php maybe will work if the config.php work.
Thanks.
You are using a class and not paying attention to variable scope.
I understand you have variables with values for the DB connection in that config.php file. Although these variables are available inside the script file with the include they are NOT available and accessible inside your class. The only difference would be any constants with define (or variables inside a global which is not a good idea).
You could create a config class inside the config.php and set the values as properties then instantiate that class inside your _koneksi method. And then you would use a require_once instead of the include.
UPDATE
So here's an example that is similar to your file where your include ('config.php'); is essentially the same as declaring your variables directly before the class begins.
// variable defined outside the class
$foo = 'foo';
class demo
{
public $bar = 'bar';
function test()
{
$foobar = 'foobar';
echo 'Class property $bar is:' . $this->bar . PHP_EOL;
echo 'Local variable $foobar is:' . $foobar . PHP_EOL;
}
function run()
{
if (isset($foo)) {
echo 'Global variable $foo is:' . $foo . PHP_EOL;
} else {
// This is where you have your problem.
// Variables from outside the class are not available.
echo 'Global variable $foo not found' . PHP_EOL;
}
}
}
$demo = new demo();
$demo->test(); // Class property $bar is:bar
// Local variable $foobar is:foobar
$demo->run(); // Global variable $foo not found
echo 'Variable $foo is: ' . $foo . PHP_EOL; // Class property $bar is:bar

Global variables of function inside function of a class

class Someclass{
function topFunction()
{
function makeMeGlobal($var)
{
global $a, $b;
$a = "a".$var;
$b = "b".$var;
}
makeMeGlobal(1);
echo "$a <br>";
echo "$b <br>";
makeMeGlobal(2);
echo "$a <br>";
echo "$b <br>";
}
}
I am using that test code on codeigniter but nothings happen.
I suppose to print a result like this
a1
b1
a2
b2
How to handle those functions inside a class?
You declare globals inside function scope.
Try to declare them at class scope:
class Someclass{
function topFunction()
{
function makeMeGlobal($var)
{
global $a, $b;
$this->a = "a".$var;
$this->b = "b".$var;
}
makeMeGlobal(1);
echo $this->a . "<br>";
echo $this->b . " <br>";
makeMeGlobal(2);
echo $this->a . "<br>";
echo $this->b . "<br>";
}
}
you are creating the global variables inside the function, try creating them in the class scope rather than the function. that should work.

Query to database and display

I use CodeIgniter 2.1.3, PHP and MySQL.
Hello, I want to display data from database. Always I display by foreach($results as $data), but now I want do display all data in few step. Display first record and when user click next then display next row from database. I now that I must use mysql_fetch_row() but I don't know how I can do it...
This is my model:
public function play($limit, $start) {
$this->db->limit($limit, $start);
$query = $this->db->get("quiz");
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
controler:
public function index()
{
$config = array();
$config["base_url"] = base_url() . "index.php/main_menu/Quiz/index";
$config["total_rows"] = $this->quiz_model->record_count();
$config["per_page"] = 11;
$config["uri_segment"] = 4;
$this->pagination->initialize($config);
$page = ($this->uri->segment(4)) ? $this->uri->segment(4) : 0;
$data["results"] = $this->quiz_model->play($config["per_page"], $page);
$data["links"] = $this->pagination->create_links();
$this->load->view('left_column/quiz_open', $data);
}
Pagination is not important.
and view:
<form>
<?php
if (empty($results)) {
}
else {
foreach($results as $data) { ?>
<label style='width:450px;'> <b> &nbsp <?php echo $data->pytanie?> </b> </label>
<label style='width:300px;'> <input type="radio" name="Wiek" value=<?php echo $data->odp1 ?> /> <?php echo $data->odp1 ?> </label>
<label style='width:300px;'> <input type="radio" name="Wiek" value=<?php echo $data->odp2 ?> /> <?php echo $data->odp2 ?> </label>
<label style='width:300px;'> <input type="radio" name="Wiek" value=<?php echo $data->odp3 ?> /> <?php echo $data->odp3 ?> </label>
<?php }
}?>
<label style='width:300px;'> <input type="submit" name="Wyslij" id="Wyslij" value="&nbsp Wyƛlij &nbsp"/> </label>
</form>
There is an inbuilt Pagination class provided by codeIgniter. You can find it in user guide.
Define a start index variable in the function where u want to use pagination as zero.
public function pagination($start_index = 0)
{
$result = $this->model->get_results($data); //this $data is the argument which you are passing to your model function. If you are using database to get results array.
$items_per_page = 10; //this is constant variable which you need to define
$filtered_result = array_splice($result, $start_index, ITEM_PER_PAGE_USERS);
$model['$filtered_result'] = $filtered_result;
$total_rows = count($result);
$model['page_links'] = create_page_links (base_url()."/controlelr_name/pagination",ITEM_PER_PAGE_USERS, $total_rows);
$this->load->view('controller_name/view_file_name', $model);
}
This is a generalised function for pagination. You can keep this function in one helper file where you keep all generalised functions.
function create_page_links($base_url, $per_page, $total_rows)
{
$CI = & get_instance();
$CI->load->library('pagination');
$config['base_url'] = $base_url;
$config['total_rows'] = $total_rows;
$config['per_page'] = $per_page;
$CI->pagination->initialize($config);
return $CI->pagination->create_links();
}
This create page links function is a generic function.............for more explanation check pagination class from user guide......