How to do queries with pdo db connection function? - mysqli

I read too many questions and answers around but couldn't be sure.
I have 2 questions
1.I turned my db connection into a function and I am not sure if its
safe ?
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'demo');
function DB()
{
try {
$pdo = new PDO('mysql:host='.DB_SERVER.';dbname='.DB_NAME.'', DB_USERNAME, DB_PASSWORD);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
} catch (PDOException $e) {
return "Error!: " . $e->getMessage();
die();
}
}
2.is my query done right way ?
query:
try {
$pdo = DB();
$stmt = $pdo->prepare("SELECT * FROM settings");
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$c = htmlspecialchars($row['site_url']);
$e = filterString($row['contact']);
}
unset($stmt);
} catch (PDOException $e) {
exit($e->getMessage());
}
Thanks for any help

Perhaps keep one connection, rather than opening multiple connections to the Database. You can look into a project PDOEasy that I created to make MVC easy with PDO or use the below static example.
class DB
{
private $_connection;
private static $_instance;
public static function getInstance() {
if(self::$_instance) return self::$_instance;
self::$_instance = new self();
return self::$_instance;
}
private function __construct() {
$this->_connection = new PDO('mysql:host='.DB_SERVER.';dbname='.DB_NAME.'', DB_USERNAME, DB_PASSWORD, array(
PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false
));
}
public function getConnection() { return $this->_connection; }
}
Which can be used like so:
$stmt = DB::getInstance()
->getConnection()
->Prepare('SELECT * FROM settings');
$stmt->execute();
foreach($stmt->fetchAll() as $row) {
// ...
}

Related

Fatal error: Call to a member function selectCollection() on a non-object in \lib\dbconnection.php on line 55

<?php
class DBConnection {
const HOST = 'localhost';
const PORT = 27017;
const DBNAME = 'lib';
private static $instance;
public $connection;
public $database;
private function _construct()
{
$connectionString = sprintf('mongodb://%s:%d', DBConnection::HOST, DBConnection::PORT);
try {
$this->connection = new Mongo($connectionString); $this->database = $this->connection-> selectDB(DBConnection::DBNAME);
} catch (MongoConnectionException $e) {
throw $e;
}
}
static public function instantiate()
{
if (!isset(self::$instance)) {
$class = __CLASS__;
self::$instance = new $class;
}
return self::$instance;
}
public function getCollection($name)
{
return $this->database->selectCollection($name);
}
}
help pleaseee
You have a typo: __construct has two _'s, and you only have one.

PHP PDO PGPOOL PGSQL - SQLSTATE[HY000]: General error: 7 no connection to the server

I try to explain the problem I have!!!
I use PDO extension to connect to PostgreSQL through pgpool-II. It works fine within Apache, but from PHP CLI (on the same machine) I receive this PDO error:
SQLSTATE[HY000]: General error: 7 no connection to the server
I have already searched on Google and here, but it seems that no one has ever tried to do this. Does anyone have any idea?
EDIT:
This is the code I use to establish a connection:
include 'manage_db.php';
include_once 'properties.php';
global $properties;
$dsn = 'pgsql:dbname=' . $properties['db_pgpool'] . ';host=localhost;port=' . $properties['port_pgpool'];
try{
$mgmtDb = new ManageDb($dsn, $properties['username_pgpool'], $properties['password_pgpool']);
} catch (Exception $e) {
echo 'PDO - Caught exception: ', $e->getMessage(), "\n";
}
ManageDB is my own class that implements some utility functions as well as create the database connection:
class ManageDb {
var $db;
function ManageDb($dsn, $username, $password){
$this->db = new PDO($dsn, $username, $password);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
....
Try this
config.database.php
<?php
class DatabaseConfig {
const DBNAME = 'dbname';
const HOST = '123.1.233.123';
const USER = 'mysuperuser';
const PASSWORD = 'mysupperparrword';
const PORT = 5432;
}
?>
class.database.php
<?php
include('config.database.php');
class Database {
protected static $instance = null;
final private function __construct() {}
final private function __destruct() {
self::$instance = null;
}
final private function __clone() {}
public static function getInstance() {
if (self::$instance === null) {
try {
self::$instance = new PDO(
'pgsql:host=' . DatabaseConfig::HOST .
';port=' . DatabaseConfig::PORT .
';dbname=' . DatabaseConfig::DBNAME .
';user=' . DatabaseConfig::USER .
';password=' . DatabaseConfig::PASSWORD
);
self::$instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
self::$instance->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
} catch (PDOException $e) {
die('Database connection could not be established.');
}
}
return self::$instance;
}
public static function __callStatic($method, $args) {
return call_user_func_array(array(self::instance(), $method), $args);
}
}
?>

How to create a complete custom form

how have I to create a custom Magento form? I don't need any extension or sample that mention the contact form. I mean that I need to understand how Magento with the modified Zend form handler works.
So the question is:
Does anybody have a code example for Magento created in a controller ?
<?php
class Mage_Contacts_IndexController extends Mage_Core_Controller_Front_Action
{
const XML_PATH_EMAIL_RECIPIENT = 'contacts/email/recipient_email';
const XML_PATH_EMAIL_SENDER = 'contacts/email/sender_email_identity';
const XML_PATH_EMAIL_TEMPLATE = 'contacts/email/email_template';
const XML_PATH_ENABLED = 'contacts/contacts/enabled';
public function preDispatch()
{
parent::preDispatch();
if( !Mage::getStoreConfigFlag(self::XML_PATH_ENABLED) ) {
$this->norouteAction();
}
}
public function indexAction()
{
$this->loadLayout();
$this->getLayout()->getBlock('contactForm')
->setFormAction( Mage::getUrl('*/*/post') );
$this->_initLayoutMessages('customer/session');
$this->_initLayoutMessages('catalog/session');
$this->renderLayout();
}
public function postAction()
{
$post = $this->getRequest()->getPost();
if ( $post ) {
$translate = Mage::getSingleton('core/translate');
/* #var $translate Mage_Core_Model_Translate */
$translate->setTranslateInline(false);
try {
$postObject = new Varien_Object();
$postObject->setData($post);
$error = false;
if (!Zend_Validate::is(trim($post['name']) , 'NotEmpty')) {
$error = true;
}
if (!Zend_Validate::is(trim($post['comment']) , 'NotEmpty')) {
$error = true;
}
if (!Zend_Validate::is(trim($post['email']), 'EmailAddress')) {
$error = true;
}
if (Zend_Validate::is(trim($post['hideit']), 'NotEmpty')) {
$error = true;
}
if ($error) {
throw new Exception();
}
$mailTemplate = Mage::getModel('core/email_template');
/* #var $mailTemplate Mage_Core_Model_Email_Template */
$mailTemplate->setDesignConfig(array('area' => 'frontend'))
->setReplyTo($post['email'])
->sendTransactional(
Mage::getStoreConfig(self::XML_PATH_EMAIL_TEMPLATE),
Mage::getStoreConfig(self::XML_PATH_EMAIL_SENDER),
Mage::getStoreConfig(self::XML_PATH_EMAIL_RECIPIENT),
null,
array('data' => $postObject)
);
if (!$mailTemplate->getSentSuccess()) {
throw new Exception();
}
$translate->setTranslateInline(true);
Mage::getSingleton('customer/session')->addSuccess(Mage::helper('contacts')->__('Your inquiry was submitted and will be responded to as soon as possible. Thank you for contacting us.'));
$this->_redirect('*/*/');
return;
} catch (Exception $e) {
$translate->setTranslateInline(true);
Mage::getSingleton('customer/session')->addError(Mage::helper('contacts')->__('Unable to submit your request. Please, try again later'));
$this->_redirect('*/*/');
return;
}
} else {
$this->_redirect('*/*/');
}
}
}

Parse error: syntax error, unexpected $end, expecting T_FUNCTION in ClmsRegistrationModel.php

<?php
/**
* clmsRegistration
*
* #author MGUCS-07
* #version
*/
require_once 'Zend/Db/Table/Abstract.php';
class ClmsRegistrationModel extends Zend_Db_Table_Abstract
{
/**
* The default table name
*/
protected $_name = "clms_registration";
protected $_primary = "user_name";
public static function changePassword($username, $newpassword)
{ //changes the password
try {
$chps= new ClmsRegistrationModel();
$row = $chps->find($username);
$row1 = $row->current();
$row1->password=$newpassword;
$row1->save();
}
catch (Zend_Db_Exception $e)
{
$e->getMessage();
}
}
public static function checkUsed($username)
{ //check whether used or not
try {
$table = new ClmsRegistrationModel();
$row=$table->find($username);
if($row)
{
return 1;
}}
catch (Zend_Db_Exception $e)
{
$e->getMessage();
}
}
public static function deleteUser($user_name)
{ //deletes a user
try {
$deluser=new ClmsRegistrationModel();
$row = $deluser->find($user_name);
$row1=$row->current();
$result = $row1->delete();
}
catch (Zend_Db_Exception $e)
{
$e->getMessage();
}
}
public static function updateUser($user_name,$district,$email_id,$phone_number)
{
//updates the details of the user
try {
$upUser = new ClmsRegistrationModel();
$row = $upUser->find($user_name);
$row1=$row->current();
$row1->district= $district;
$row1->email_id= $email_id;
$row1->phone_number= $phone_number;
$row1->save();
}
catch (Zend_Db_Exception $e)
{
$e->getMessage();
}
}
public static function getRole($user_name)
{ //gets the role of the user
try {
$roq= new ClmsRegistrationModel();
$u= $roq->fetchRow($roq->select()->where('user_name=?',$user_name));
return $u->toArray();
}
catch (Zend_Db_Exception $e)
{
$e->getMessage();
}
}
public function isActive($user_name)
{ //select active user
try {
$roq = new ClmsRegistrationModel();
$u= $roq->fetchRow($roq->select()->where('user_name=?',$user_name));
return $u->toArray();
}
catch (Zend_Db_Exception $e)
{
$e->getMessage();
}
}
public function setActive($user_nam)
{ //sets user active
try {
$roq = new ClmsRegistrationModel();
$row= $roq->find($user_nam);
$row1=$row->current();
$row1->user_name= $user_nam;
$row1->status1 = 1;
$row1->save();
}
catch (Zend_Db_Exception $e)
{
$e->getMessage();
}
}
public static function setRole($user_name,$role)
{ //sets the role of the user
try {
$reg=new ClmsRegistrationModel();
$row = $reg->find($user_name);
$row1= $row->current();
$row1->role_organization=$role;
$row1->save();
}
catch (Zend_Db_Exception $e)
{
$e->getMessage();
}
}
public function register($uname,$pass,$role,$en,$status,$email,$ph,$date,$dis)
{// function for registration purposes
try{
$reg = new ClmsRegistrationModel();
$row =$reg->fetchNew();
//$row= $row->current();
$row->user_name = '$uname';
$row->password = '$pass';
$row->role = $role;
$row->employee_name=$en;
$row->status1=$status;
$row->email_id =$email;
$row->phone_number =$ph;
$row->date =$date;
$row->District=$dis;
$row->employe_id =$row->employe_id +1;
$row->save();
//$reg->save();
}
catch (Zend_Db_Exception $e){
$e->getMessage();
}
}
}
This is my model class and getting that error.
Please tell why this error and how to debug it.
well neither of those are correct answers. there are 2 braces in if statement
if($row)
{
return 1;
}}
try this
$reg = new ClmsRegistrationModel();
$row1 =$reg->createRow();
$row1->user_name = $uname;
$row1->password= $pass;
$row1->role = $role;
$row1->employee_name=$en;
$row1->status1=$status;
$row1->email_id =$email;
$row1->phone_number =$ph;
$row1->date =$date;
$row1->District=$dis;
$row1->save();
remove public from line 1 then try again

Zend Paginator with Gdata Youtube

How Zend_Paginator can work according to the exchange of the variable query?
In line 8 performs a single fetch and does not change even by changing the query variable.
How to do paging function in accordance with the start-index from gdata feed?
The code: http://pastebin.com/rmxSP1Us
$yt = new Zend_Gdata_YouTube();
$limit = 12;
$offset = ($page - 1) * $limit + 1;
$query = "http://gdata.youtube.com/feeds/api/users/aculinario/favorites?start-index=$offset";
$paginator = Zend_Paginator::factory($yt->getVideoFeed($query));
$paginator->setCurrentPageNumber($page);
$paginator->setItemCountPerPage($limit);
$paginator->setPageRange(6);
$this->view->paginator = $paginator;
echo $query // query changes but paginator no, every time Zend_Paginator factory should check the returned array of getVideoFeed, but not this checking
Sry, my poor english, i'm Trying
I got something similar working using a quick & dirty paginator adapter.
It's worth noting there's probably nicer, more generic ways to achieve this. But this will get you going if you're in a hurry.
<?php
class Lib_Paginator_Adapter_YoutubeUser implements Zend_Paginator_Adapter_Interface
{
protected $_username;
protected $_results;
public function __construct($username)
{
$this->_username = $username;
}
public function getItems($offset, $itemCountPerPage)
{
$url = sprintf(
'%s/%s/%s',
Zend_Gdata_YouTube::USER_URI,
$this->_username,
Zend_Gdata_YouTube::UPLOADS_URI_SUFFIX
);
try
{
$query = new Zend_Gdata_Query($url);
$query->setMaxResults($itemCountPerPage)
->setStartIndex($offset);
$youtube = new Zend_Gdata_YouTube();
$this->_results = $youtube->getUserUploads(null, $query);
return $this->_results;
}
catch (Exception $ex)
{
echo $ex->getMessage();
exit;
}
}
public function count()
{
try
{
$youtube = new Zend_Gdata_YouTube();
return $youtube->getUserUploads($this->_username)->getTotalResults()->getText();
}
catch (Exception $ex)
{
echo $ex->getMessage();
exit;
}
}
}
Then in your controller
$page = $this->getRequest()->getParam("page");
$limit = 10;
$username = 'aculinario';
$paginator = new Zend_Paginator(new Lib_Paginator_Adapter_YoutubeUser($username));
$paginator->setItemCountPerPage($limit);
$paginator->setPageRange(10);
$paginator->setCurrentPageNumber($page);
$this->view->youtubeFeed = $paginator;