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
Related
I'm having an error when calling stored procedure inside foreach
It says "Commands out of sync you can't run this command now" .
I already looking for solution, but the result is not like i'm expecting.
This is my code
$query = "CALL PROCEDURE_HEAD()";
$sql = $this->db->query($query)->result_array();
foreach($sql as $key) {
$name = $key['name'];
$array['name'] = $name;
$array['data'] = $key['data'];
$query2 = "CALL PROCEDURE_CHILD('$name')";
$sql2 = $this->db->query($query2)->result_array();
foreach($sql2 as $value) {
$array['child'] = array(
'child_name' => $value['child_name'],
'child_data' => $value['child_data']
);
}
}
i have tried run codeigniter : Commands out of sync; you can't run this command now, and because i'm using Procedure after Procedure,it doesn't run.
Any kind of help is really appreciated
Use Model with associate this
In Controller
$head = $this->Model_name->call_head();
foreach($head as $item) {
$name = $item['name'];
$array['name'] = $name;
$array['data'] = $item['data'];
$child = $this->Model_name->call_child($name);
foreach($child as $value) {
$array['child'] = array(
'child_name' => $value['child_name'],
'child_data' => $value['child_data']
);
}
}
In model
public function call_head()
{
$query = "CALL PROCEDURE_HEAD()";
$result = $this->db->query($query)->result_array();
$query->next_result();
$query->free_result();
return $result;
}
public function call_child($name)
{
$query = "CALL PROCEDURE_CHILD($name)";
$result = $this->db->query($query)->result_array();
$query->next_result();
$query->free_result();
return $result;
}
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();
this below code work fine without any problem, but after move that into function i get error and doesnt work
Route::get('test', ['as' => 'test', function () {
$data = 'MYURL';
$table = [];
$html = new \Htmldom($data);
foreach($html->find('tr') as $row) {
$col_1 = $row->find('td',0)->plaintext;
$col_2 = "";
try{
$col_2= $row->find('td',1)->plaintext;
}catch (Exception $ignore){}
$table[] = $col_2;
}
$values = array_values($table);
unset($values[0]);
unset($values[1]);
unset($values[5]);
$values = array_values($values);
print_r($values);
/*print_r(\App\Customs\Helpers::get_online_currencies());*/
}]);
My Class:
class Helpers
{
public static function get_online_currencies(){
$data = 'MYURL';
$table = [];
$html = new \Htmldom($data);
foreach($html->find('tr') as $row) {
$col_2 = "";
try{
$col_2= $row->find('td',1)->plaintext;
}catch (Exception $ignore){}
$table[] = $col_2;
}
$values = array_values($table);
unset($values[0]);
unset($values[1]);
unset($values[5]);
return array_values($values);
}
}
Error:
ErrorException in Helpers.php line 23:
Trying to get property of non-object
line 23:
$col_2= $row->find('td',1)->plaintext;
You can test my code.
The first and the last row have only 1 column. Assert results of find before fetch data:
foreach($html->find('tr') as $row) {
$col_2 = "";
try{
$col_2= $row->find('td',1);
}catch (Exception $ignore){}
$table[] = $col_2 ? $col_2->plaintext : "";
}
I'm new to yii framework. I'm just trying to implement Restful APIs. In the simple case scenario (after following some tutorial) I've succeeded with this:
$result = [];
foreach($this->getData() as $record) {
$result[] = $record->getAttributes();
}
return $result;
Note that getData() is a built-in method. Where when trying to use queries for more advanced scenarios, it's done this way:
$attributeNames = 'udid,model,appverionid';
$connection = Yii::app()->db;
$command = $connection->createCommand('select ' . $attributeNames . ' from device');
$models = $command->queryAll();
$attributeNames = explode(',', $attributeNames);
$rows = array();
foreach ($models as $model) {
$row = array();
foreach ($attributeNames as $name) {
$row[$name] = CHtml::value($model, $name);
}
$rows[] = $row;
}
return $rows;
Is that the best practice to return get JSON from queries results, or maybe it can be done in a better way?
Update:
The final response is returned from the following method:
private function sendAjaxResponse(AjaxResponseInterface $interface)
{
$success = count($interface->getErrors()) === 0;
$responseCode = $success ? 200 : 404;
header("content-type: application/json", true, $responseCode);
echo json_encode([
'success' => $success,
'data' => $interface -> getResponseData(),
'errors' => $interface -> getErrors()
]);
Yii::app()->end();
}
And I found out that only these lines are sufficient:
$attributeNames = 'udid,model,appverionid';
$connection = Yii::app()->db;
$command = $connection->createCommand('select ' . $attributeNames . ' from device');
$models = $command->queryAll();
return $models;
The other part (the nested loop) seems for encoding with relations (see here) Then my question is what is encoding with relations and when it is helpful?
The Yii way of creating JSOn data is using CJson library
$query = "'select ' . $attributeNames . ' from device'";
$command = Yii::app()->db->createCommand($query);
$result = $command->queryAll();
$ret = array_values($result);
/* or ...
$ret = array();
foreach ($models as $model) {
$ret = array();
foreach ($attributeNames as $name) {
$row[$name] = CHtml::value($model, $name);
}
$ret[] = $row;
}
*/
echo CJSON::encode($ret);
Yii::app()->end();
I think you simply need to encode the value before return
foreach ($models as $model) {
$row = array();
foreach ($attributeNames as $name) {
$row[$name] = CHtml::value($model, $name);
}
$rows[] = $row;
}
return json_encode($rows);
Very Simple! Just add this line - \Yii::$app->response->format = \yii\web\Response:: FORMAT_JSON; in your method at start and do other code
normally.
for example,
public function actionHospitals()
{
\Yii::$app->response->format = \yii\web\Response:: FORMAT_JSON;
$hospitals = Hospitals::find()->select('speciality')->distinct()->all();
return ['hospitals' => $hospitals];
}
i want to fetch titles and title's tags.
public function titles()
{
$query=mysql_query("SELECT * FROM title");
while($row = mysql_fetch_object($query)){
$data->title[] = $row;
$data->tag[] = $this->tags($row->id);
}
return $data;
}
public function tags($title_id)
{
$query=mysql_query("SELECT * FROM tag WHERE title_id = '$title_id'");
while($row = mysql_fetch_object($query)){
$tag[] = $row;
}
return $tag;
}
I'm trying to print in this way
$data = titles();
foreach($data->title as $title)
{
echo $title->topic;
foreach($data->tag as $tag)
{
echo $tag->name;
}
}
but it doesnt work. How can I do?
thank you for help.
You should have something like this in your titles method
$data = new stdClass();
$data->title = array();
$data->tag = array();
You also need to add files like this
$data->title[$row->id][] = $row;
$data->tag[$row->id][] = $this->tags($row->id);
Then you can loop like this
foreach($data->title as $id => $title)
{
echo $title->topic;
foreach($data->tag[$id] as $tag)
{
echo $tag->name;
}
}
Also Enable error so that you can see PHP Errors .. at on top of your page
error_reporting(E_ALL);
ini_set("display_errors","On");
PHP DOC ON mysql_***
Use of this extension is discouraged. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include
What i think your code should look like
class Somthing {
private $db;
function __construct() {
$this->db = new mysqli("localhost", "user", "password", "db");
}
function titles() {
$data = new stdClass();
$data->title = array();
$data->tag = array();
$result = $this->db->query("SELECT * FROM title");
while ( $row = $result->fetch_object() ) {
$data->title[$row->id] = $row;
$data->tag[$row->id] = $this->tags($row->id);
}
return $data;
}
function tags($title_id) {
$tag = array();
$result = $this->db->query("SELECT * FROM tag WHERE title_id = '$title_id'");
while ( $row = $result->fetch_object() ) {
$tag[] = $row;
}
return $tag;
}
}
$somthing = new Somthing();
foreach ($somthing->titles() as $id => $title ) {
echo $title->topic;
foreach ( $data->tag[$id] as $tag ) {
echo $tag->name;
}
}