In my customer repository, I've defined a function findMapAllByIds(), like so:
/**
* #apiParam $materialIdList [049c5355-6311-c251-16b7-9c923f8de2a4,0589775e-dcd3-c015-bd81-bba26df33c77,0bf7f653-c01a-d6e2-8cdc-1691c437e4eb]
*/
public function findMapAllByIds($materialIdList, $orderBy = 'createTime', $order = 'desc')
{
$ids = array();
$query = $this->createQueryBuilder('Material')
->field('_id')->in($materialIdList)
->sort($orderBy, $order)
->getQuery();
$resultList = $query->execute();
$resultMap = array();
if (!empty($resultList)) {
foreach ($resultList as $material) {
$resultMap[(string) $material->getId()] = $material;
}
}
return $resultMap;
}
Then, I get this error:
[Symfony\Component\Debug\Exception\ContextErrorException]
Notice: Array to string conversion
Related
I can get the not-bind query on with this way :
\DB::enableQueryLog();
$items = OrderItem::where('name', '=', 'test')->get();
$log = \DB::getQueryLog();
print_r($log);
Output is :
(
[0] => Array
(
[query] => select * from "order_items" where "order_items"."name" = ? and "order_items"."deleted_at" is null
[bindings] => Array
(
[0] => test
)
[time] => 0.07
)
)
But what I really need is bind query like this :
select * from "order_items" where "order_items"."name" = 'test' and "order_items"."deleted_at" is null
I know I can do this with raw PHP but is there any solution in laravel core?
Actually I've created one function within helpers.php for same. You can also use same function within your helpers.php file
if (! function_exists('ql'))
{
/**
* Get Query Log
*
* #return array of queries
*/
function ql()
{
$log = \DB::getQueryLog();
$pdo = \DB::connection()->getPdo();
foreach ($log as &$l)
{
$bindings = $l['bindings'];
if (!empty($bindings))
{
foreach ($bindings as $key => $binding)
{
// This regex matches placeholders only, not the question marks,
// nested in quotes, while we iterate through the bindings
// and substitute placeholders by suitable values.
$regex = is_numeric($key)
? "/\?(?=(?:[^'\\\']*'[^'\\\']*')*[^'\\\']*$)/"
: "/:{$key}(?=(?:[^'\\\']*'[^'\\\']*')*[^'\\\']*$)/";
$l['query'] = preg_replace($regex, $pdo->quote($binding), $l['query'], 1);
}
}
}
return $log;
}
}
if (! function_exists('qldd'))
{
/**
* Get Query Log then Dump and Die
*
* #return array of queries
*/
function qldd()
{
dd(ql());
}
}
if (! function_exists('qld'))
{
/**
* Get Query Log then Dump
*
* #return array of queries
*/
function qld()
{
dump(ql());
}
}
Simply place these three functions within your helpers.php file and you can use same as follows:
$items = OrderItem::where('name', '=', 'test')->get();
qldd(); //for dump and die
or you can use
qld(); // for dump only
Here I extended the answer of #blaz
In app\Providers\AppServiceProvider.php
Add this on boot() method
if (env('APP_DEBUG')) {
DB::listen(function($query) {
File::append(
storage_path('/logs/query.log'),
self::queryLog($query->sql, $query->bindings) . "\n\n"
);
});
}
and also added a private method
private function queryLog($sql, $binds)
{
$result = "";
$sql_chunks = explode('?', $sql);
foreach ($sql_chunks as $key => $sql_chunk) {
if (isset($binds[$key])) {
$result .= $sql_chunk . '"' . $binds[$key] . '"';
}
}
$result .= $sql_chunks[count($sql_chunks) -1];
return $result;
}
Yeah, you're right :/
This is a highly requested feature, and i have no idea why its not a part of the framework yet...
This is not the most elegant solution, but you can do something like this:
function getPureSql($sql, $binds) {
$result = "";
$sql_chunks = explode('?', $sql);
foreach ($sql_chunks as $key => $sql_chunk) {
if (isset($binds[$key])) {
$result .= $sql_chunk . '"' . $binds[$key] . '"';
}
}
return $result;
}
$query = OrderItem::where('name', '=', 'test');
$pure_sql_query = getPureSql($query->toSql(), $query->getBindings());
// Or like this:
$data = OrderItem::where('name', '=', 'test')->get();
$log = DB::getQueryLog();
$log = end($log);
$pure_sql_query = getPureSql($log['query'], $log['bindings']);
You can do that with:
OrderItem::where('name', '=', 'test')->toSql();
Can someone help me with this please I'm getting this error message Notice: Undefined variable: choices, I understand the error but i'm not seeing the issue.
public function getEmployeesArray($conn)
{
// $conn =
// $conn = $this->get('database_connection');
$employees = $conn->fetchall('Select * from vEmployee order by emp_lastname');
foreach ($employees as $emp_row) {
$choices[$emp_row['employee_id']] = $emp_row['emp_lastname'] . ', ' . $emp_row['emp_firstname'];
}
return $choices;
}
Yes $choices undefined before foreach try this :
public function getEmployeesArray($conn) {
// $conn =
// $conn = $this->get('database_connection');
$employees = $conn->fetchall('Select * from vEmployee order by emp_lastname');
$choices = [];
foreach ($employees as $emp_row) {
$choices[$emp_row['employee_id']] = $emp_row['emp_lastname'] . ', ' . $emp_row['emp_firstname'];
}
return $choices;
}
try this:
public function getEmployeesArray($conn) {
$choices = []; //or what you want
$employees = $conn->fetchall('Select * from vEmployee order by emp_lastname');
foreach ($employees as $emp_row) {
$choices[$emp_row['employee_id']] = $emp_row['emp_lastname'] . ', ' . $emp_row['emp_firstname'];
}
return $choices;
}
You need to initialize $choices because if there isn't $employees It never been set.
The problem now is your query that doesn't return any value so your code doesn't enter inside your foreach loop
I am trying to create constructor which creates an multidimensional array. My result should be like this:-
Checkout my array $result_array
For now I have error: Illegal offset type. Note that I have als use __toString() becose I work on xml data.
class Property {
public $xmlClass;
public $elemClass = '';
public $first_array = array();
public $result_array = array();
public $data = '';
public $data2 = '';
public function __construct($xml, $elem) {
$this->xmlClass = $xml;
$this->elemClass = $elem;
foreach ($xml->xpath('//*[#baza]') as $val) {
$this->first_array[] = $val;
foreach ($val->ksiazka as $value) {
$data = $value->$elem->__toString();
$this->result_array[$this->first_array][] = $data;
}
}
}
public function getResult() {
return $this->result_array;
}
}
$result_autor = new Property($xml, 'autor');
$autor = $result_autor->getResult();
You need to change your two foreach() like below:-
foreach($xml->xpath('//*[#baza]') as $val) {
//$this->first_array[] = $val; not needed
foreach($val->ksiazka as $key=> $value){ //check $key here
$data = $value->$elem->__toString();
$this->result_array[$key][] = $data; // add $key hear
}
}
If the above not worked then check this too:-
foreach($xml->xpath('//*[#baza]') as $key=> $val) { //check $key here
//$this->first_array[] = $val; not needed
foreach($val->ksiazka as $value){
$data = $value->$elem->__toString();
$this->result_array[$key][] = $data; // add $key hear
}
}
I'm developing a code that's supposed to go through all records in a database and run 'save()' on each of them.
The thing is, it's giving me a 'Fatal error: Allowed memory size exhausted' error (see below)
current memory usage: 19592272
current memory usage: 20944968
current memory usage: 22361824
current memory usage: 23649968
.
.
.
current memory usage: 274071160
current memory usage: 275354880
Fatal error: Allowed memory size of 276824064 bytes exhausted (tried to allocate 71 bytes) in/home/lestest/public_html/garratt/phproad/modules/phpr/classes/phpr_extensible.php on line 94
I read this was an issue with any PHP version that's below 5.3 (I'm using PHP 5.3.2). I follow advices from articles like http://paul-m-jones.com/archives/262#comment-940 and https://bugs.php.net/bug.php?id=48781I, and made sure to destruct() and unset() the object after each loop to free the memory, but I don't know why it's still keeping memory. Can anyone point out what should be changed with the code?
Below is my code:
<?php
class ProductSave_Products extends Backend_Controller {
public $implement = 'Db_FormBehavior, Db_ListBehavior';
public $form_model_class = 'ProductSave_Model';
public function index()
{
$this->app_module_name = 'Products';
$this->app_page_title = 'Save';
$obj = new ProductSave_Model();
$ids = Db_DbHelper::queryArray('select id from shop_product');
foreach($ids as $row)
{
$product = Shop_Product::create()->find($row['id']);
$product->save();
$product->__destruct();
unset($product);
print "current memory usage: ". memory_get_usage() . '<br/><br/>';
}
}
}
?>
Here is my Db_Helper class code:
<?php
class Db_DbHelper
{
protected static $driver = false;
public static function listTables()
{
return Db_Sql::create()->fetchCol('show tables');
}
public static function tableExists($tableName)
{
$tables = self::listTables();
return in_array($tableName, $tables);
}
public static function executeSqlScript($filePath, $separator = ';')
{
$fileContents = file_get_contents($filePath);
$fileContents = str_replace( "\r\n", "\n", $fileContents );
$statements = explode( $separator."\n", $fileContents );
$sql = Db_Sql::create();
foreach ( $statements as $statement )
{
if ( strlen(trim($statement)) )
$sql->execute($statement);
}
}
public static function scalar($sql, $bind = array())
{
return Db_Sql::create()->fetchOne($sql, $bind);
}
public static function scalarArray($sql, $bind = array())
{
$values = self::queryArray($sql, $bind);
$result = array();
foreach ($values as $value)
{
$keys = array_keys($value);
if ($keys)
$result[] = $value[$keys[0]];
}
return $result;
}
public static function query($sql, $bind = array())
{
$obj = Db_Sql::create();
return $obj->query($obj->prepare($sql, $bind));
}
public static function fetch_next($resource)
{
return self::driver()->fetch($resource);
}
public static function free_result($resource)
{
self::driver()->free_query_result($resource);
}
public static function queryArray($sql, $bind = array())
{
return Db_Sql::create()->fetchAll($sql, $bind);
}
public static function objectArray($sql, $bind = array())
{
$recordSet = self::queryArray($sql, $bind);
$result = array();
foreach ($recordSet as $record)
$result[] = (object)$record;
return $result;
}
public static function object($sql, $bind = array())
{
$result = self::objectArray($sql, $bind);
if (!count($result))
return null;
return $result[0];
}
public static function getTableStruct( $tableName )
{
$sql = Db_Sql::create();
$result = $sql->query($sql->prepare("SHOW CREATE TABLE `$tableName`"));
return $sql->driver()->fetch($result, 1);
}
public static function getTableDump( $tableName, $fp = null, $separator = ';' )
{
$sql = Db_Sql::create();
$qr = $sql->query("SELECT * FROM `$tableName`");
$result = null;
$columnNames = null;
while ($row = $sql->driver()->fetch($qr))
{
if ( $columnNames === null )
$columnNames = '`'.implode( '`,`', array_keys($row) ).'`';
if (!$fp)
{
$result .= "INSERT INTO `$tableName`(".$columnNames.") VALUES (";
$result .= $sql->quote( array_values($row) );
$result .= ")".$separator."\n";
} else
{
fwrite($fp, "INSERT INTO `$tableName`(".$columnNames.") VALUES (");
fwrite($fp, $sql->quote( array_values($row) ));
fwrite($fp, ")".$separator."\n");
}
}
return $result;
}
public static function createDbDump($path, $options = array())
{
#set_time_limit(600);
$tables_to_ignore = array_key_exists('ignore', $options) ? $options['ignore'] : array();
$separator = array_key_exists('separator', $options) ? $options['separator'] : ';';
$fp = #fopen($path, "w");
if (!$fp)
throw new Phpr_SystemException('Error opening file for writing: '.$path);
$sql = Db_Sql::create();
try
{
fwrite($fp, "SET NAMES utf8".$separator."\n\n");
$tables = self::listTables();
foreach ($tables as $index=>$table)
{
if (in_array($table, $tables_to_ignore))
continue;
fwrite($fp, '# TABLE '.$table."\n#\n");
fwrite($fp, 'DROP TABLE IF EXISTS `'.$table."`".$separator."\n");
fwrite($fp, self::getTableStruct($table).$separator."\n\n" );
self::getTableDump($table, $fp, $separator);
$sql->driver()->reconnect();
}
#fclose($fp);
#chmod($path, Phpr_Files::getFilePermissions());
}
catch (Exception $ex)
{
#fclose($fp);
throw $ex;
}
}
/**
* Generates an unique column value
* #param Db_ActiveRecord $model A model to generate value for
* #param string $column_name A name of a column
* #param string $base_value A base value of the column. The unique value will be generated
* by appending the 'copy_1', 'copy_N' string to the base value.
* #param bool $case_sensitive Specifies whether function should perform a case-sensitive search
* #return string
*/
public static function getUniqueColumnValue($model, $column_name, $base_value, $case_sensitive = false)
{
$base_value = trim($base_value);
$base_value = preg_replace('/_copy_[0-9]+$/', '', $base_value);
$column_value = $base_value;
$counter = 1;
$table_name = $model->table_name;
$query = $case_sensitive ?
"select count(*) from $table_name where $column_name=:test_value" :
"select count(*) from $table_name where lower($column_name)=lower(:test_value)";
while (self::scalar("select count(*) from $table_name where $column_name=:test_value", array(
'test_value'=>$column_value
)))
{
$column_value = $base_value.'_copy_'.$counter;
$counter++;
}
return $column_value;
}
/**
* Creates a SQL query string for searching specified fields for specified words or phrases
* #param string $query Search query
* #param array|array $fields A list of fields to search in. A single field can be specified as a string
* #param int $min_word_length Allows to ignore words with length less than the specified
* #return string Returns a string
*/
public static function formatSearchQuery($query, $fields, $min_word_length = null)
{
if (!is_array($fields))
$fields = array($fields);
$words = Core_String::split_to_words($query);
$word_queries = array();
foreach ($words as $word)
{
if (!strlen($word))
continue;
if ($min_word_length && mb_strlen($word) < $min_word_length)
continue;
$word = trim(mb_strtolower($word));
$word_queries[] = '%1$s like \'%2$s'.self::driver()->escape($word).'%2$s\'';
}
$field_queries = array();
foreach ($fields as $field)
{
if ($word_queries)
$field_queries[] = '('.sprintf(implode(' and ', $word_queries), $field, '%').')';
}
if (!$field_queries)
return '1=1';
return '('.implode(' or ', $field_queries).')';
}
public static function reset_driver()
{
self::$driver = false;
}
public static function driver()
{
if (!self::$driver)
{
$sql = Db_Sql::create();
return self::$driver = $sql->driver();
}
return self::$driver;
}
public static function escape($str)
{
return self::driver()->escape($str);
}
}
?>
Thank you
Below is my class.
class MaterialType {
public $id;
public $name;
function getAllMaterialType() {
$query = "SELECT * FROM material_types";
$result = mysql_query($query);
$arr = array();
while ($row = mysql_fetch_array($result)) {
$arr[] = new MaterialType();
$arr[]->id = $row['m_type_id'];
$arr[]->name = $row['m_type_name'];
}
return $arr;
}
}
The problem is when I create object in an array like above, and display it using foreach,
there are errors that say Undefined property stdClass. I already defined the property that being used, so why these errors appear? Below is the code that I use to
display data.
$materialTypeObj = new MaterialType();
foreach($materialTypeObj->getAllMaterialType() as $mat) {
echo $mat->name;
}
Every time you do $array[] = it inserts a new element in the end of an array. What you need to do is:
class MaterialType {
public $id;
public $name;
function getAllMaterialType() {
$query = "SELECT * FROM material_types";
$result = mysql_query($query);
$arr = array();
while($row = mysql_fetch_array($result)) {
$mat = new MaterialType();
$mat->id = $row['m_type_id'];
$mat->name = $row['m_type_name'];
$arr[] = $mat;
}
return $arr;
}
}