Duplicate of this question
I'm trying to create a web service with Zend_Soap_Server in wsdl autodiscovery mode, but I obtain very strange effects... here the code:
server:
<?php
require_once('Zend/Soap/AutoDiscover.php');
require_once('Zend/Soap/Server.php');
require_once('Zend/Soap/Wsdl.php');
require_once('library/SoapActions.php');
$wsdl = new Zend_Soap_Autodiscover();
$wsdl->setClass('SoapActions');
if (isset($_GET['wsdl'])) {
$wsdl->handle();
} else {
$server = new Zend_Soap_Server('http://localhost:8083/server.php?wsdl');
$server->setClass('SoapActions');
$server->setEncoding('ISO-8859-1');
$server->handle();
}
SoapActions class:
class SoapActions {
/**
* Test function
*
* #param String $a
* #param String $b
* #return String
*/
public function test1($a, $b) {
return "you passed me ".$a." ".$b;
}
/**
* Test function 2
*
* #param String $a
* #param String $b
* #return String
*/
public function test2($a, $b) {
return "you passed me ".$a." ".$b;
}
}
I tried to use the function test1 and test2 using the Zend_Soap_Client class, here the code:
require_once('Zend/Soap/Client.php');
$client = new Zend_Soap_Client("http://localhost:8083/server.php?wsdl");
try {
echo $client->test2("foo","bar"); //this works!
} catch (Exception $e) {
echo $e;
}
try {
echo $client->test1("foo","bar"); //this doesn't work!
} catch (Exception $e) {
echo $e;
}
I cannot understand because the test2 function works as expected, the test1 function return the following exception:
SoapFault exception: [Sender] Function
("test1") is not a valid method for
this service in
/usr/local/zend/share/ZendFramework/library/Zend/Soap/Client.php:1121
Stack trace:
0 /usr/local/zend/share/ZendFramework/library/Zend/Soap/Client.php(1121):
SoapClient->__soapCall('test1', Array,
NULL, NULL, Array)
1 /usr/local/zend/apache2/htdocs/webservice/client.php(6):
Zend_Soap_Client->__call('test1',
Array)
2 /usr/local/zend/apache2/htdocs/webservice/client.php(6):
Zend_Soap_Client->test1('foo', 'bar')
3 {main}
I tried to invert the functions name... the result is incredible, works only test2! I'm getting crazy, it seems that somewhere on server side it save the function name...
Can someone help me?
SOLVED! The problem was this setting in the php.ini file:
soap.wsdl_cache_enabled=1
I set this to 0 and now it works fine!
If you don't want change your php.ini:
// WSDL_CACHE_NONE; /* 0 Pas de cache */
// WSDL_CACHE_DISK; /* 1 Sur le disque supprimer le fichier pour le réinitialiser */
// WSDL_CACHE_MEMORY; /* 2 En mémoire => redémarrer Apache pour le réinitialiser */
// WSDL_CACHE_BOTH; /* 3 En mémoire et sur le disque */
$options = array();
$options['cache_wsdl'] = WSDL_CACHE_NONE;
$client = new Zend_Soap_Client("http://localhost:8083/server.php?wsdl", $options);
Related
I have Created a save quote extension for one of my clients every thing is working fine
But when a customer print a pdf Quote its show the POUND symbol instead of showing the quote currency code EURO My code is given below I have tried many ways to add currency code but it is not working
public function __construct(
\Magento\Payment\Helper\Data $paymentData,
\Magento\Framework\Stdlib\StringUtils $string,
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
\Magento\Framework\Filesystem $filesystem,
Config $pdfConfig,
\Magento\Sales\Model\Order\Pdf\Total\Factory $pdfTotalFactory,
\Magento\Sales\Model\Order\Pdf\ItemsFactory $pdfItemsFactory,
\Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate,
\Magento\Framework\Translate\Inline\StateInterface $inlineTranslation,
\Magento\Sales\Model\Order\Address\Renderer $addressRenderer,
AddressQuoteRenderer $addressQuoteRenderer,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Store\Model\App\Emulation $appEmulation,
\Magento\Framework\Pricing\Helper\Data $helper,
OrderFactory $orderFactory,
array $data = []
) {
$this->orderFactory = $orderFactory;
$this->addressQuoteRenderer = $addressQuoteRenderer;
$this->helper = $helper;
$this->_appEmulation = $appEmulation;
parent::__construct(
$paymentData,
$string,
$scopeConfig,
$filesystem,
$pdfConfig,
$pdfTotalFactory,
$pdfItemsFactory,
$localeDate,
$inlineTranslation,
$addressRenderer,
$storeManager,
$appEmulation,
$data
);
}
/**
* Return PDF document
*
* #param Collection $quotes
*
* #return \Zend_Pdf
* #throws \Magento\Framework\Exception\LocalizedException
* #throws \Zend_Pdf_Exception
*/
public function getPdf($quotes = [])
{
$this->_beforeGetPdf();
$this->_initRenderer('order');
$pdf = new \Zend_Pdf();
$this->_setPdf($pdf);
$order = $this->orderFactory->create();
foreach ($quotes as $quote) {
if ($quote->getStoreId()) {
$this->_appEmulation->startEnvironmentEmulation($quote->getStoreId());
$this->_storeManager->setCurrentStore($quote->getStoreId());
}
$page = $this->newPage();
$this->_setFontBold($page, 10);
$quote->setQuote($quote);
/* Add image */
$this->insertLogo($page, $quote->getStore());
/* Add address */
$this->insertAddress($page, $quote->getStore());
/* Add head */
$this->insertOrder($page, $quote, false);
/* Add table */
$this->_drawHeader($page);
$this->_initRenderer('default');
/* Add body */
$taxTotal = 0;
foreach ($quote->getAllItems() as $item) {
if ($item->getParentItem()) {
continue;
}
/* Keep it compatible with the invoice */
$item->setQty($item->getQty());
$item->setProductType($item->getProduct()->getTypeId());
$this->_initRenderer($item->getProduct()->getTypeId());
$item->setOrderItem($item);
$taxTotal += $item->getTaxAmount();
/* Draw item */
$this->_drawItem($item, $page, $order);
$page = end($pdf->pages);
}
/* Add totals */
$order->setStoreId($quote->getStoreId());
$order->setSubtotal($quote->getSubtotal());
$order->setGrandTotal($quote->getSubtotal() + $taxTotal);
$order->setShippingAmount($quote->getShippingAddress()->getShippingAmount());
$order->setTaxAmount($taxTotal);
$order->setOrder($order);
$this->insertTotals($page, $order);
if ($quote->getStoreId()) {
$this->_appEmulation->stopEnvironmentEmulation();
}
Please Help and suggest to me where I am wrong I am stuck in this problem
Thanks for your help in advance
I just upgraded my TYPO3 v9 to v10.04.27 and now i get an error in the Upgrade Wizard
(1/1) Error
Class 'TYPO3\CMS\Core\Cache\Frontend\StringFrontend' not found in /srv/typo3_src-10.4.20/typo3/sysext/core/Classes/Cache/CacheManager.php line 351
As you can see in the path i also tried already with an older TYPO3 10 Version.
I disabled all extensions before the upgrade. Except the ones that cant be disabled.
So this should be a completely clean TYPO3 10 install (except the Config Files).
I dont know what i can do about this.
Here is the Full Trace:
Something went wrong. Please use Check for broken extensions to see if a loaded extension breaks this part of the install tool and unload it.
The box below may additionally reveal further details on what went wrong depending on your debug settings. It may help to temporarily switch to debug mode using Settings > Configuration Presets > Debug settings.
If this error happens at an early state and no full exception back trace is shown, it may also help to manually increase debugging output in typo3conf/LocalConfiguration.php:['BE']['debug'] => true, ['SYS']['devIPmask'] => '*', ['SYS']['displayErrors'] => 1,['SYS']['exceptionalErrors'] => 12290
Ajax error
Whoops, looks like something went wrong.
(1/1) Error
Class 'TYPO3\CMS\Core\Cache\Frontend\StringFrontend' not found
in /srv/typo3_src-10.4.20/typo3/sysext/core/Classes/Cache/CacheManager.php line 351
$backendInstance->initializeObject();
}
// New used on purpose, see comment above
$frontendInstance = new $frontend($identifier, $backendInstance);
if (!$frontendInstance instanceof FrontendInterface) {
throw new InvalidCacheException('"' . $frontend . '" is not a valid cache frontend object.', 1464550984);
}
if (is_callable([$frontendInstance, 'initializeObject'])) {
at TYPO3\CMS\Core\Cache\CacheManager->createCache()
in /srv/typo3_src-10.4.20/typo3/sysext/core/Classes/Cache/CacheManager.php line 157
if ($this->hasCache($identifier) === false) {
throw new NoSuchCacheException('A cache with identifier "' . $identifier . '" does not exist.', 1203699034);
}
if (!isset($this->caches[$identifier])) {
$this->createCache($identifier);
}
return $this->caches[$identifier];
}
at TYPO3\CMS\Core\Cache\CacheManager->getCache()
in /srv/typo3_src-10.4.20/typo3/sysext/core/Classes/Cache/DatabaseSchemaService.php line 51
$cacheManager->setCacheConfigurations($GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']);
$tableDefinitions = '';
foreach ($GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations'] as $cacheName => $_) {
$backend = $cacheManager->getCache($cacheName)->getBackend();
if (method_exists($backend, 'getTableDefinitions')) {
$tableDefinitions .= LF . $backend->getTableDefinitions();
}
}
at TYPO3\CMS\Core\Cache\DatabaseSchemaService->getCachingFrameworkRequiredDatabaseSchema()
in /srv/typo3_src-10.4.20/typo3/sysext/core/Classes/Cache/DatabaseSchemaService.php line 33
* #param AlterTableDefinitionStatementsEvent $event
*/
public function addCachingFrameworkDatabaseSchema(AlterTableDefinitionStatementsEvent $event): void
{
$event->addSqlData($this->getCachingFrameworkRequiredDatabaseSchema());
}
/**
* Get schema SQL of required cache framework tables.
at TYPO3\CMS\Core\Cache\DatabaseSchemaService->addCachingFrameworkDatabaseSchema()
in /srv/typo3_src-10.4.20/typo3/sysext/core/Classes/EventDispatcher/EventDispatcher.php line 51
if ($event instanceof StoppableEventInterface && $event->isPropagationStopped()) {
return $event;
}
foreach ($this->listenerProvider->getListenersForEvent($event) as $listener) {
$listener($event);
if ($event instanceof StoppableEventInterface && $event->isPropagationStopped()) {
break;
}
}
at TYPO3\CMS\Core\EventDispatcher\EventDispatcher->dispatch()
in /srv/typo3_src-10.4.20/typo3/sysext/core/Classes/Database/Schema/SqlReader.php line 75
}
}
/** #var AlterTableDefinitionStatementsEvent $event */
$event = $this->eventDispatcher->dispatch(new AlterTableDefinitionStatementsEvent($sqlString));
$sqlString = $event->getSqlData();
return implode(LF . LF, $sqlString);
}
at TYPO3\CMS\Core\Database\Schema\SqlReader->getTablesDefinitionString()
in /srv/typo3_src-10.4.20/typo3/sysext/install/Classes/Service/UpgradeWizardsService.php line 156
*/
public function getBlockingDatabaseAdds(): array
{
$sqlReader = GeneralUtility::makeInstance(SqlReader::class);
$databaseDefinitions = $sqlReader->getCreateTableStatementArray($sqlReader->getTablesDefinitionString());
$schemaMigrator = GeneralUtility::makeInstance(SchemaMigrator::class);
$databaseDifferences = $schemaMigrator->getSchemaDiffs($databaseDefinitions);
at TYPO3\CMS\Install\Service\UpgradeWizardsService->getBlockingDatabaseAdds()
in /srv/typo3_src-10.4.20/typo3/sysext/install/Classes/Controller/UpgradeController.php line 1042
$this->lateBootService->loadExtLocalconfDatabaseAndExtTables(false);
$adds = [];
$needsUpdate = false;
try {
$adds = $this->upgradeWizardsService->getBlockingDatabaseAdds();
$this->lateBootService->resetGlobalContainer();
if (!empty($adds)) {
$needsUpdate = true;
}
at TYPO3\CMS\Install\Controller\UpgradeController->upgradeWizardsBlockingDatabaseAddsAction()
in /srv/typo3_src-10.4.20/typo3/sysext/install/Classes/Middleware/Maintenance.php line 246
'Unknown action method ' . $action . ' in controller ' . $controllerName,
1505216027
);
}
$response = $controller->$action($request);
}
return $response;
}
at TYPO3\CMS\Install\Middleware\Maintenance->process()
in /srv/typo3_src-10.4.20/typo3/sysext/core/Classes/Http/MiddlewareDispatcher.php line 121
}
public function handle(ServerRequestInterface $request): ResponseInterface
{
return $this->middleware->process($request, $this->next);
}
};
}
at class#anonymous/srv/typo3_src-10.4.20/typo3/sysext/core/Classes/Http/MiddlewareDispatcher.php:103$bc->handle()
in /srv/typo3_src-10.4.20/typo3/sysext/core/Classes/Middleware/NormalizedParamsAttribute.php line 45
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$request = $request->withAttribute('normalizedParams', NormalizedParams::createFromRequest($request));
return $handler->handle($request);
}
}
at TYPO3\CMS\Core\Middleware\NormalizedParamsAttribute->process()
in /srv/typo3_src-10.4.20/typo3/sysext/core/Classes/Http/MiddlewareDispatcher.php line 172
if (!$middleware instanceof MiddlewareInterface) {
throw new \InvalidArgumentException(get_class($middleware) . ' does not implement ' . MiddlewareInterface::class, 1516821342);
}
return $middleware->process($request, $this->next);
}
};
}
}
at class#anonymous/srv/typo3_src-10.4.20/typo3/sysext/core/Classes/Http/MiddlewareDispatcher.php:138$bd->handle()
in /srv/typo3_src-10.4.20/typo3/sysext/core/Classes/Http/MiddlewareDispatcher.php line 78
* #return ResponseInterface
*/
public function handle(ServerRequestInterface $request): ResponseInterface
{
return $this->tip->handle($request);
}
/**
* Seed the middleware stack with the inner request handler
at TYPO3\CMS\Core\Http\MiddlewareDispatcher->handle()
in /srv/typo3_src-10.4.20/typo3/sysext/core/Classes/Http/AbstractApplication.php line 85
* #return ResponseInterface
*/
protected function handle(ServerRequestInterface $request): ResponseInterface
{
return $this->requestHandler->handle($request);
}
/**
* Set up the application and shut it down afterwards
at TYPO3\CMS\Core\Http\AbstractApplication->handle()
in /srv/typo3_src-10.4.20/typo3/sysext/install/Classes/Http/Application.php line 52
protected function handle(ServerRequestInterface $request): ResponseInterface
{
$this->initializeContext();
$request = $request->withAttribute('applicationType', SystemEnvironmentBuilder::REQUESTTYPE_INSTALL);
return parent::handle($request)
->withHeader('X-Frame-Options', 'SAMEORIGIN');
}
/**
at TYPO3\CMS\Install\Http\Application->handle()
in /srv/typo3_src-10.4.20/typo3/sysext/core/Classes/Http/AbstractApplication.php line 97
final public function run(callable $execute = null)
{
try {
$response = $this->handle(
ServerRequestFactory::fromGlobals()
);
if ($execute !== null) {
call_user_func($execute);
}
at TYPO3\CMS\Core\Http\AbstractApplication->run()
in /srv/typo3_src-10.4.20/typo3/install.php line 105
call_user_func(function () {
$classLoader = require dirname(__DIR__).'/vendor/autoload.php';
\TYPO3\CMS\Core\Core\SystemEnvironmentBuilder::run(1, \TYPO3\CMS\Core\Core\SystemEnvironmentBuilder::REQUESTTYPE_INSTALL);
\TYPO3\CMS\Core\Core\Bootstrap::init($classLoader, true)->get(\TYPO3\CMS\Install\Http\Application::class)->run();
});
at {closure}()
in /srv/typo3_src-10.4.20/typo3/install.php line 106
call_user_func(function () {
$classLoader = require dirname(__DIR__).'/vendor/autoload.php';
\TYPO3\CMS\Core\Core\SystemEnvironmentBuilder::run(1, \TYPO3\CMS\Core\Core\SystemEnvironmentBuilder::REQUESTTYPE_INSTALL);
\TYPO3\CMS\Core\Core\Bootstrap::init($classLoader, true)->get(\TYPO3\CMS\Install\Http\Application::class)->run();
});
Any ideas?
Thank you in advance
Delete all extensions except the ones from TYPO3 core. Then cache will be rebuild without not needed classes.
I had some errors in my installations if extension are only deactivated but not deleted.
My guess is that you're using the StringFrontend somewhere, which was deprecated in TYPO3 9.2.
Can you check your LocalConfiguration.php and AdditionalConfiguration.php if you find "StringFrontend" anywhere and replace it with VariableFrontend or remove it completely? (as suggested in the migration path)
I have a problem when I run compile
I get this error
Errors during compilation:
Ortho\Theme\Block\Html\Custommenu
Incorrect dependency in class Ortho\Theme\Block\Html\Custommenu in /var/www/vhosts/domux.eu/dmx/app/code/Ortho/Theme/Block/Html/Custommenu.php
\Magento\Store\Model\StoreManagerInterface already exists in context object
Total Errors Count: 1
Can someone please tell me what code I have to remove or modify from this php file ?
public function __construct(
Template\Context $context,
NodeFactory $nodeFactory,
TreeFactory $treeFactory,
CategoryFactory $categoryFactory,
\Magento\Cms\Model\Template\FilterProvider $filterProvider,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Cms\Model\BlockFactory $blockFactory,
Registry $registry,
\Ortho\Theme\Helper\Data $dataHelper,
array $data = []
) {
parent::__construct($context,$nodeFactory,$treeFactory, $data);
$this->categoryFactory = $categoryFactory;
$this->_filterProvider = $filterProvider;
$this->_storeManager = $storeManager;
$this->_blockFactory = $blockFactory;
$this->coreRegistry = $registry;
// $this->dataHelper = $dataHelper;
//$this->_menu = $this->getMenu();
$this->nodeFactory = $nodeFactory;
$this->treeFactory = $treeFactory;
}
/**
* Get block cache life time
*
* #return int
*/
protected function getCacheLifetime()
{
return parent::getCacheLifetime() ?: 3600;
}
Thank you a lot.
best regards
Please see https://magento.stackexchange.com/questions/172655/magento-2-1-errors-during-compilation-incorrect-dependency-in-class.
You have here all explanation and how to solve it.
This question already has answers here:
Call to a member function on a non-object [duplicate]
(8 answers)
Closed 10 years ago.
I'm hesitant to post this, as I'd really prefer to figure this out myself, but I don't think I will. I'm just trying to set a class for mysqli stuff, to make it as dynamic as possible, and yes I'm newer to OOP, but have been using PHP and Mysql as a hobby, and more heavily lately, for quite some time. I figured it was time to switch, but there just isn't that much on oop classes with mysqli and prepared statements with a possibility of multiple results (yes I've check documentation, guess I'm just not getting it or something). After quite a few hours, this is what I have. I'm not necessarily looking for a "quick fix". I really want to understand this and learn, so please explain thoroughly.
I'm using a dbconfig.php file to store my database info at root/config/dbconfig.php
in root/classes/mysqlicon.php
<?php
/*
* class MYSQLIDB
* #param Host
* #param User
* #param Password
* #param Name
*/
class MYSQLIDB
{
private $host; //MySQL Host
private $user; //MySQL User
private $pass; //MySQL Password
private $name; //MySQL Name
private $mysqli; //MySQLi Object
private $last_query; //Last Query Run
/*
* Class Constructor
* Creates a new MySQLi Object
*/
public function __construct()
{
include('./config/dbconfig.php');
$this->host = $db_host;
$this->user = $db_user;
$this->pass = $db_pass;
$this->name = $db_name;
$this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->name);
if ($mysqli->connect_errno) {
return "Failed to connect to MySQLi: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
}
private function __destruct()
{
$mysqli->close();
}
public function select($fields, $from, $where, $whereVal, $type, $orderByVal, $ASDESC, $limitVal)
{
if (is_int($whereVal))
{
$bindVal = 'i';
} else {
$bindVal = 's';
}
switch($type)
{
case "regular":
$queryPre = "SELECT " . $fields;
$querySuff = " WHERE " . $where . " = ?";
break;
case "orderByLimit":
$queryPre = "SELECT " . $fields;
$querySuff = " ORDER BY " . $orderByVal . " " . $ASDESC . " LIMIT " . $limitVal;
break;
}
//$query = "SELECT * FROM news ORDER BY id DESC LIMIT 4";
if ($stmt = $mysqli->prepare('$queryPre . " FROM " . $from . " " . $querySuff'))
{
if ($type == 'regular') {
$stmt->bind_param($bindVal, $whereVal);
}
$stmt->execute();
$stmt->bind_result($values);
$stmt->store_result();
$sr = new Statement_Result($stmt);
$stmt->fetch();
// call by this style printf("ID: %d\n", $sr->Get('id') );
//$stmt->fetch();
//$stmt->close();
//return $value;
printf("ID: %d\n", $sr->Get_Array() );
} else return null;
}
//use to call $db = new MYSQLI('localhost', 'root', '', 'blog');
/*
* Function Select
* #param fields
* #param from
* #param where
* #returns Query Result Set
function select($fields, $from, $where, $orderBy, $ASDESC, $limit, varNamesSent)
{
if ($orderBy == null &&)
$query = "SELECT " . $fields . " FROM `" . $from . "` WHERE " . $where;
$result = $this->mysqli->query($query) or exit("Error code ({$sql->errno}): {$sql->error}");
$this->last_query = $query;
return $result;
}
/*
* Function Insert
* #param into
* #param values
* #returns boolean
*/
public function insert($into, $values)
{
$query = "INSERT INTO " . $into . " VALUES(" . $values . ")";
$this->last_query = $query;
if($this->mysqli->query($query))
{
return true;
} else {
return false;
}
}
/*
* Function Delete
* #param from
* #param where
* #returns boolean
*/
public function delete($from, $where)
{
$query = "DELETE FROM " . $from . " WHERE " . $where;
$this->last_query = $query;
if($this->mysqli->query($query))
{
return true;
} else {
return false;
}
}
}
//Hand arrays for multiple returned items from database
class Statement_Result
{
private $_bindVarsArray = array();
private $_results = array();
public function __construct(&$stmt)
{
$meta = $stmt->result_metadata();
while ($columnName = $meta->fetch_field())
$this->_bindVarsArray[] = &$this->_results[$columnName->name];
call_user_func_array(array($stmt, 'bind_result'), $this->_bindVarsArray);
$meta->close();
}
public function Get_Array()
{
return $this->_results;
}
public function Get($column_name)
{
return $this->_results[$column_name];
}
}
?>
And just as a test, I'm trying to pull all the news in my db by:
<?php
require_once('classes/mysqlicon.php');
$testing = new MYSQLIDB;
$testing->select('*','news',null,null,'orderByLimit','id','DESC',4);
?>
But what I really want is stuff that can do the equivalent of this:
<?php
/*
require('config/dbconfig.php');
$query = "SELECT * FROM news ORDER BY id DESC LIMIT 4";
if ($stmt = $mysqli->prepare($query)) {
// execute statement
$stmt->execute();
// bind result variables
$stmt->bind_result($idn, $titlen, $categoryn, $descn, $postdaten, $authorn);
// fetch values
while ($stmt->fetch()) {*/
//echo 'id: '. $id .' title: '. $title;
echo "<table border='0'>";
$shortDescLengthn = strlen($descn);
if ($shortDescLengthn > 106) {
$sDCutn = 106 - $shortDescLengthn;
$shortDescn = substr($descn, 0, $sDCutn);
} else {
$shortDescn = $descn;
}
echo "<h1>$titlen</h1>";
echo "<tr><td>$shortDescn...</td></tr>";
echo '<tr><td><a href="javascript:void(0);" onclick="'
. 'readMore(' . $idn . ',' . htmlspecialchars(json_encode($titlen)) . ','
. htmlspecialchars(json_encode($categoryn)) . ','
. htmlspecialchars(json_encode($descn)) . ',' . htmlspecialchars(json_encode($postdaten)) . ','
. htmlspecialchars(json_encode($authorn)) . ')">Read More</a></td></tr>';
echo "<tr><td>Written by: $authorn</td></tr>";
echo '<tr><td><img src="images/hardcore-games-newsbar-border.png" width="468px" /></td></tr>';
}
echo "</table><br />";
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>
Again, please, please explain in detail. I'm a blockhead sometimes.
I'm assuming the error is coming from this line:
if ($stmt = $mysqli->prepare('$queryPre . " FROM " . $from . " " . $querySuff'))
$mysqli is not defined in the context of this function. You should be accessing $this->mysqli instead. The same applies to other references you have made such as here:
if ($mysqli->connect_errno)
I am using this to retrieve the database connection atm.
$db = Zend_Db_Table::getDefaultAdapter();
I do set this up in my config like this:
resources.db.adapter = pdo_mysql
resources.db.isDefaultTableAdapter = true
resources.db.params.host = localhost
resources.db.params.username = root
resources.db.params.password = password
resources.db.params.dbname = db
resources.db.params.profiler.enabled = true
resources.db.params.profiler.class = Zend_Db_Profiler
I would like to output everything to a sql.log for example. Is this possible to apply on the default adapter? for example through the settings, so I can ignore it in production environment?
Much appriciated.
I did look at: How to enable SQL output to log file with Zend_Db? but it didn't seem to cover my issue.
/Marcus
There is an example of extending Zend_Db_Profiler so you can write the queries to /logs/db-queries.log file.
So you have to do the following:
Create My_Db_Profiler_Log class in the library folder
Add the following lines to the application.ini
resources.db.params.profiler.enabled = true
resources.db.params.profiler.class = My_Db_Profiler_Log
Note: be aware, that the log file will become very big, very soon! So it is a good idea to log only the queries you are interested in. And this example should be considered only as a starting point in implementation of such a logging system.
Here is the code for the custom profiler class:
<?php
class My_Db_Profiler_Log extends Zend_Db_Profiler {
/**
* Zend_Log instance
* #var Zend_Log
*/
protected $_log;
/**
* counter of the total elapsed time
* #var double
*/
protected $_totalElapsedTime;
public function __construct($enabled = false) {
parent::__construct($enabled);
$this->_log = new Zend_Log();
$writer = new Zend_Log_Writer_Stream(APPLICATION_PATH . '/logs/db-queries.log');
$this->_log->addWriter($writer);
}
/**
* Intercept the query end and log the profiling data.
*
* #param integer $queryId
* #throws Zend_Db_Profiler_Exception
* #return void
*/
public function queryEnd($queryId) {
$state = parent::queryEnd($queryId);
if (!$this->getEnabled() || $state == self::IGNORED) {
return;
}
// get profile of the current query
$profile = $this->getQueryProfile($queryId);
// update totalElapsedTime counter
$this->_totalElapsedTime += $profile->getElapsedSecs();
// create the message to be logged
$message = "\r\nElapsed Secs: " . round($profile->getElapsedSecs(), 5) . "\r\n";
$message .= "Query: " . $profile->getQuery() . "\r\n";
// log the message as INFO message
$this->_log->info($message);
}
}
?>
Extend the Zend_Db_Profiler to write to an SQL.log and attach the profiler to your db adapter
<?php
class File_Profiler extends Zend_Db_Profiler {
/**
* The filename to save the queries
*
* #var string
*/
protected $_filename;
/**
* The file handle
*
* #var resource
*/
protected $_handle = null;
/**
* Class constructor
*
* #param string $filename
*/
public function __construct( $filename ) {
$this->_filename = $filename;
}
/**
* Change the profiler status. If the profiler is not enabled no
* query will be written to the destination file
*
* #param boolean $enabled
*/
public function setEnabled( $enabled ) {
parent::setEnabled($enabled);
if( $this->getEnabled() ) {
if( !$this->_handle ) {
if( !($this->_handle = #fopen($this->_filename, "a")) ) {
throw new Exception("Unable to open filename {$this->_filename} for query profiling");
}
}
}
else {
if( $this->_handle ) {
#fclose($this->_handle);
}
}
}
/**
* Intercept parent::queryEnd to catch the query and write it to a file
*
* #param int $queryId
*/
public function queryEnd($queryId) {
$state = parent::queryEnd($queryId);
if(!$this->getEnabled() || $state == self::IGNORED) {
return;
}
$profile = $this->getQueryProfile($queryId);
#fwrite($this->_handle, round($profile->getElapsedSecs(),5) . " " . $profile->getQuery() . " " . ($params=$profile->getQueryParams())?$params:null);
}
}
Haven't test it, but it should do the trick. Give it a try and let me know.
Btw you do know that you can log all queries on the mysql as well?
this will let you see sql queries to the web page , IT MIGHT BE OFF TOPIC but it helpful
I am highly recommend you to use ZF debug bar , it will give you very handy information
i am using it to see my doctrine queries , and it had support for zend db too
https://github.com/jokkedk/ZFDebug