Zend error Connection - json

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

Related

AmfPHP 2.0 running on PHP 7 & PDO

AmfPHP 2.0 running on Nginx and PHP 7.0 (FPM), PDO is used as database.
As many users log in to the game, the CPU increases immediately to 100% on all 4 cores due to MySQL. If there are fewer players, the process calms down again and the CPU drops.
Code snippet of PDO connection:
class Database extends PDO {
public static function getConnection() {
$connectionString = sprintf("mysql:dbname=%s;host=%s;charset=utf8", MYSQL_DB, MYSQL_HOST);
try {
$pdo = new PDO($connectionString, MYSQL_USER, MYSQL_PASS);
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
return $pdo;
} catch(PDOException $e) {
$error = date("Y-m-d g:i:s a T") . "\Database::getConnection\tError: (" . $e->getCode . ") " . $e->getMessage;
throw new Exception($error);
}
}
// Example
public static function Test($arg) {
try {
$pdo = Database::getConnection();
$stmt = $pdo->prepare("select * from xx where xx = :xx");
$stmt->bindParam(":xx", $arg, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if ($stmt->rowCount() > 0) {
// execute my code
}
} catch(PDOException $e) {
$error = date("Y-m-d g:i:s a T") . "\Database::Test\tError: (" . $e->getCode . ") " . $e->getMessage;
throw new Exception($error);
}
}
}
For further questions I am at any time available.

Severity: Notice Message: Trying to get property of non-object

I am receiving an error when attempting to pull several rows of data from my MySQL database and display their content on my web page. Since I am very new to Code Igniter, i am not sure how to fix this error:
Severity: Notice
Message: Trying to get property of non-object
Here is the code associated with the error.
Model:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class news_model extends CI_Model
{
function __construct()
{
parent::__construct();
}
function get_news()
{
$query = $this->db->query("SELECT * FROM news WHERE active = 1");
if ($query->num_rows() > 0)
{
foreach($query->result() AS $row)
{
$array[] = get_object_vars($row);
}
return $array;
}
}
}?>
Controller:
<?php
class profile extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper(array('url','html'));
$this->load->library('session');
$this->load->database();
$this->load->model('user_model');
$this->load->model('news_model');
}
function index()
{
$details = $this->user_model->get_user_by_id($this->session->userdata('uid'));
$data['uname'] = $details[0]->fname . " " . $details[0]->lname;
$data['uemail'] = $details[0]->email;
$data['ustorenumber'] = $details[0]-> storenumber;
$data['urank'] = $details[0]-> rank;
$data['news'] = $this->news_model->get_news();
$this->load->view('profile_view', $data);//Error reported on this line.
}
}
View:
<?php
foreach($news AS $row) {
echo '<p>' . $row->content . '</p>';//Error reported on this line
}
?>
Full Error:
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: views/profile_view.php
Line Number: 82
Backtrace:
File: C:\xampp\htdocs\cig\application\views\profile_view.php
Line: 82
Function: _error_handler
File: C:\xampp\htdocs\cig\application\controllers\profile.php
Line: 22
Function: view
File: C:\xampp\htdocs\cig\index.php
Line: 315
Function: require_once
In model return result in object format.Like this..
function get_news()
{
$query = $this->db->query("SELECT * FROM news WHERE active = 1");
if ($query->num_rows() > 0)
{
return $query->result();//returns result in object format
}
}
OR
IN view: use $row['content'] insetad of $row->content;
<?php
foreach($news AS $row) {
echo '<p>' . $row['content']. '</p>';//Error reported on this line
}
?>

Yii2 Optional textbox with Checkbox from database

I am using following code to generate checkboxes from database. I need to add optional textbox for some options. Can anybody give me clue to add it ?
$form->field($model_detail, 'DOCUMENT_TYPE_ID')
->checkboxList(
$listData,array('separator'=>'<BR />')
)->label('Select Document(s)');
You should extends ActiveField and write your custom checkboxList method. It may looks like this:
class ProjectActiveField extends ActiveField
{
/**
* #inheritdoc
*/
public function checkboxList($items, $options = [])
{
$inputs = '';
foreach ($items as $id => $value) {
$input = Html::activeCheckbox($this->model, $this->$id, $options);
$description = $options['itemDescriptions'][$id];
if ($description) {
$input = '<div class="checkbox">' . $description . $input . '</div>';
}
$inputs .= $input;
}
$this->adjustLabelFor($options);
$this->parts['{input}'] = $inputs;
return $this;
}
}

Mysql Clone user account from database

I have a database with aproximately 200 tables. I want to clone a certain user-account in this database. Is this possible in mysql?
With cloning I mean to create a new user with the same 'settings' as the user with id 14.
A quick google search reveals that you in fact can do this. There is a utility called " "mysql user clone", that lets you surprisingly clone a user for mysql.
If you check out the manual I'm sure it provides you with great tips about how to use it, for instance, this quote:
EXAMPLES
To clone joe as sam and sally with passwords and logging in as root on the local machine, use this command:
$ mysqluserclone --source=root#localhost \
--destination=root#localhost \
joe#localhost sam:secret1#localhost sally:secret2#localhost
# Source on localhost: ... connected.
# Destination on localhost: ... connected.
# Cloning 2 users...
# Cloning joe#localhost to user sam:secret1#localhost
# Cloning joe#localhost to user sally:secret2#localhost
# ...done.
since it appears #Nanne's approach, mysqluserclone is EOL / not supported by Oracle, i wrote a similar utility in PHP, usage:
<?php
$db = new \PDO("mysql:host={$db_creds->dbhost};dbname={$db_creds->dbname};charset=utf8mb4;port=" . $db_creds->dbport, $db_creds->superuser_user, $db_creds->superuser_pass, array(
\PDO::ATTR_EMULATE_PREPARES => false,
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC
));
Mysqluserclone::clone_account($db, "original username", "cloned username");
and this part of the code may be of particular interest:
if (0) {
echo "the following SQLs will clone this account:\n";
echo implode("\n\n", $sqls_for_cloning) . "\n\n";
die();
}
<?php
class Mysqluserclone{
private function __construct(){
// by making this private, we ensure nobody try to instantiate us.
}
public static function clone_account(\PDO $db_connected_as_superuser, string $original_name, string $clone_name): void
{
$db = $db_connected_as_superuser;
$sqls_for_cloning = [];
$sql = "SELECT COUNT(*) FROM mysql.user WHERE User = " . $db->quote($clone_name);
if (0 !== $db->query($sql)->fetch(\PDO::FETCH_NUM)[0]) {
throw new \InvalidArgumentException("clone name already exists!");
}
$sql = "SELECT * FROM mysql.user WHERE User = " . $db->quote($original_name);
$current_user_one_for_each_host = $db->query($sql)->fetchAll(\PDO::FETCH_ASSOC);
foreach ($current_user_one_for_each_host as $user_record) {
$user_record["User"] = $clone_name;
$sql = "INSERT INTO mysql.user SET \n";
foreach ($user_record as $name => $val) {
$sql .= self::mysql_quote_identifier($name) . " = " . self::mysql_quote_better($db, $val) . ",\n";
}
if (! empty($user_record)) {
$sql = substr($sql, 0, - strlen(",\n"));
}
$sql .= ";";
$sqls_for_cloning[] = $sql;
$sqls_for_cloning[] = "FLUSH PRIVILEGES;"; // YES this is required, otherwise you might get "grant not allowed to create accounts" errors
$grants_raw_sql = 'SHOW GRANTS FOR ' . $db->quote($original_name) . '#' . $db->quote($user_record['Host']) . ";";
try {
$grants_raw = $db->query($grants_raw_sql)->fetchAll(\PDO::FETCH_NUM);
} catch (\Throwable $ex) {
// somehow an empty grant table is a mysql error, not an empty rowset.. ignore it.
$grants_raw = [];
}
$grants_raw = array_map(function (array $arr): string {
if (count($arr) !== 1) {
throw new \LogicException("mysql layout for SHOW GRANTS has changed? investigate");
}
return $arr[0];
}, $grants_raw);
$original_name_as_identifier = self::mysql_quote_identifier($original_name);
$clone_name_as_identifier = self::mysql_quote_identifier($clone_name);
foreach ($grants_raw as $grant) {
if (false === strpos($grant, $original_name_as_identifier)) {
throw new \LogicException("original grant without original name as identifier? investigate");
}
$grant = self::str_replace_last($original_name_as_identifier, $clone_name_as_identifier, $grant);
$grant .= ";";
$sqls_for_cloning[] = $grant;
}
}
if (! empty($sqls_for_cloning)) {
$sqls_for_cloning[] = "FLUSH PRIVILEGES;";
}
if (0) {
echo "the following SQLs will clone this account:\n";
echo implode("\n\n", $sqls_for_cloning) . "\n\n";
die();
}
foreach ($sqls_for_cloning as $clone_sql) {
$db->exec($clone_sql);
}
}
private static function mysql_quote_identifier(string $identifier): string
{
return '`' . strtr($identifier, [
'`' => '``'
]) . '`';
}
private static function mysql_quote_better(\PDO $db, $value): string
{
if (is_null($value)) {
return "NULL";
}
if (is_int($value)) {
return (string) $value;
}
if (is_float($value)) {
return number_format($value, 10, '.', '');
}
if (is_bool($value)) {
return ($value ? "1" : "0");
}
return $db->quote($value);
}
private static function str_replace_last(string $search, string $replace, string $subject): string
{
$pos = strrpos($subject, $search);
if ($pos !== false) {
$subject = substr_replace($subject, $replace, $pos, strlen($search));
}
return $subject;
}
}

simple codeigniter query + results display won't display

I'm trying to display data from my database in a Codeigniter view. Seems like it should be simple, but it's just not working.
I'm getting 2 errors: undefined variable ($movielist, in the view) and invalid argument for php foreach, also in the view.
Any idea how I can get this to work? Code below.
Controller
function displayMovies() {
$this->load->model('movie_list_model');
$data['movielist'] = $this->movie_list_model->getList();
$this->load->view('movielist_view', $data);
}
Model
function getList() {
$query = $this->db->query('SELECT firstname, lastname, favorite_movie FROM movies');
return $query->result();
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row)
{
echo $row['firstname'];
echo $row['lastname'];
echo $row['favorite_movie'];
}
}
View
<?php foreach($movielist as $mlist)
{
echo $mlist->firstname . '<br />';
echo $mlist->lastname . '<br />';
echo $mlist->favorite_movie;
}
?>
If( the query doesn't find any rows, it will return null, resulting in the undefined error in your view. The invalid argument error is because you can't iterate through null.
A safety would be including something like this in your view:
if($movielist)
{
/* foreach() {} */
}
Also, your model should only return data (not echo it).
function getList() {
$query = $this->db->query('SELECT firstname, lastname, favorite_movie FROM movies');
return $query->result(); /* returns an object */
// Alternatively:
// return $query->result_array(); /* returns an array */
}
I also recommend using Active record:
function getList() {
$this->db->select('firstname');
$this->db->select('lastname');
$this->db->select('favorite_movie');
$query = $this->get('movies');
return $query->result();
}
Good luck!