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;
}
Related
Good I'm starting with php and codeigniter, I have the following problem I'm running an array from my model, which is the result of a query, how can I read one by one my records in the controller?
function getCustomers() {
$sql = "SELECT * FROM customers";
$query = $this->db->query($sql);
if ($query->num_rows() > 0) {
$i = 0;
foreach($query->result() as $row) {
$img[$i]['id'] = $row->id;
$img[$i]['name'] = $row->name;
$img[$i]['Location'] = $row->Location;
$img[$i]['telephone'] = $row->telephone;
$i++;
}
return $img;
}
}
You can return array to the controller by loading the model into the controller like this.
$this->load->model('yourmodel');
$array = $this->yourmodel->yourmodelsmethod();
First you have to return this array to your controller like
$this->load->model('yourmodel');
$array['test'] = $this->yourmodel->yourmodelsmethod();
foreach($test as $key=>$value)
{
echo $value;
}
By doing this you can easily print your data from model in controller
Succesfully solved: Working code is noted at the bottom of this Post.
I'm currently trying to run a SQL command to grab all the data out of a database table and send it over a API call using the variable names.
The problem I'm having is assigning the values of the fields under "$row" to separate variables so I can then place them in my foreach loop and send them all over to the API call. Can anyone enlighten me to what I'm doing wrong
I'm sure the line that I'm going wrong is my commandbuilder and then assigning the variables to the data inside row.
I feel like the problem line could be
while ($row = mysql_fetch_assoc()) {
$emails = $row['email_address'];
$names = $row['forename'];
}
the full code is below.
public function actionImportSubscribers($cm_list_id){
//need to pass through cm_list_id instead
$cm_list_id = Yii::app()->getRequest()->getQuery('cm_list_id');
$model =$this->loadModelList($cm_list_id);
$listID = $model->cm_list->cm_list_id;
$row = Yii::app()->db->createCommand()
->select('email_address, forename')
->from('tbl_cm_subscribers')
->where('cm_list_id=:id', array(':id' => $cm_list_id))
->queryAll();
while ($row = mysql_fetch_assoc()) {
$emails = $row['email_address'];
$names = $row['forename'];
}
$customFieldArray = array();
$addFieldsToList = array();
foreach (array_combine($emails, $names) as $name => $email) {
$addFieldsToList[] = array('EmailAddress' => $email,'Name' => $name,'CustomFields' => $customFieldArray);
}
$auth = array('api_key' => '');
$wrap = new CS_REST_Subscribers($listID, $auth);
$result = $wrap->import(array($addFieldsToList), false);
Working code is below
public function actionImportSubscribers($cm_list_id){
//need to pass through cm_list_id instead
$cm_list_id = Yii::app()->getRequest()->getQuery('cm_list_id');
$model =$this->loadModelList($cm_list_id);
$listID = $model->cm_list->cm_list_id;
$result = Yii::app()->db->createCommand()
->select('email_address, forename')
->from('tbl_cm_subscribers')
->where('cm_list_id=:id', array(':id' => $cm_list_id))
->queryAll();
$emails=array();
$names=array();
foreach ($result as $row) {
$emails[] = $row['email_address'];
$names[] = $row['forename'];
}
require_once 'protected/extensions/createsend-php-5.0.1/csrest_subscribers.php';
$auth = array('api_key' => '');
foreach (array_combine($emails, $names) as $email => $name) {
$wrap = new CS_REST_Subscribers($listID, $auth);
$result = $wrap->import(array(
array(
'EmailAddress' => $email,
'Name' => $name,
),
), false);
}
echo "Result of POST /api/v3.1/subscribers/{list id}/import.{format}\n<br />";
if($result->was_successful()) {
echo "Subscribed with results <pre>";
var_dump($result->response);
} else {
echo 'Failed with code '.$result->http_status_code."\n<br /><pre>";
var_dump($result->response);
echo '</pre>';
if($result->response->ResultData->TotalExistingSubscribers > 0) {
echo 'Updated '.$result->response->ResultData->TotalExistingSubscribers.' existing subscribers in the list';
} else if($result->response->ResultData->TotalNewSubscribers > 0) {
echo 'Added '.$result->response->ResultData->TotalNewSubscribers.' to the list';
} else if(count($result->response->ResultData->DuplicateEmailsInSubmission) > 0) {
echo $result->response->ResultData->DuplicateEmailsInSubmission.' were duplicated in the provided array.';
}
echo 'The following emails failed to import correctly.<pre>';
var_dump($result->response->ResultData->FailureDetails);
}
echo '</pre>';
// }
}
I don't know if this solving your problem but you have few errors there.
mysql_fetch_assoc() requires param , resource returned from mysql_query function.
In part where you creating $emails and $names variables you doing that like if you trying to create array but you will get always single value in that way how you have done it. This is example if you will use mysql_fetch_assoc, you can't combine queryAll() with mysql_fetch_assoc
$emails=array();
$names=array();
$result=mysql_query("SELECT email_address, forename FROM tbl_cm_subscribers where cm_list_id='$cm_list_id'");
while ($row = mysql_fetch_assoc($result)) {
$emails[] = $row['email_address'];
$names[] = $row['forename'];
}
queryAll() method returns array, I don't know Yii but I suppose this is what you need to do
$result = Yii::app()->db->createCommand()
->select('email_address, forename')
->from('tbl_cm_subscribers')
->where('cm_list_id=:id', array(':id' => $cm_list_id))
->queryAll();
$emails=array();
$names=array();
foreach ($result as $row) {
$emails[] = $row['email_address'];
$names[] = $row['forename'];
}
Or if you don't need array of results then use $emails and $names without []
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];
}
What is the proper way to create a function to get array values from a query? I am getting "Undefined index: page_title" error.
However I can get the value without function like: echo $row->page_title;
Or echo $query[0]->title;
function get_page($id) {
$db = new DB();
$query = $db->get_rows("SELECT * FROM pages WHERE id = :id ", array('id' => $_GET['id']) );
foreach ($query as $row) {
$page_id = $row->id;
$page_title = $row->title;
}
return $query;
}
$page = get_page(1);
echo $page['page_title'];
here is my database class:
function get_rows($query, $values=array(), $fetchType = FETCH_OBJ)
{
$sth = $this->dbh->prepare($query);
if(is_array($values) && (sizeof($values) > 0))
{
foreach($values as $key=>$val)
{
$key = is_numeric($key) ? ($key + 1) : $key;
$sth->bindValue($key,$val);
}
}
if($sth->execute())
return $sth->fetchAll($fetchType);
}
To make the function reusable, I would rewrite it the following way
function get_page($id, $col) {
$db = new DB();
$query = $db->prepare('SELECT * FROM pages WHERE id = :id');
$query->execute(array(':id' => $id));
$results = $query->fetch(PDO::FETCH_NUM);
return $results[0][$col];
}
$page = get_page(1, 'page_title');
echo $page;
I skipped the foreach as you said that all id's are unique so you should only ever have 1 result
Also it may not be a bad idea to add some error checking to make sure you do get back what you expect from the query and to make sure it is not empty.
Edit: Sorry if the syntax is a little off, dont have anything to test the code against quickly.
I can't understand and I seek for help=(
Here is my code:
$add_article = $this->M_articles->Add($_POST['title'], $_POST['content']);
echo "sd;flksdf;lksdfl;";
$add_article2 = true;
if ($add_article)
{
echo 'Article Added!';
header("Location:index.php");
die();
}
else
die('Error adding article');
this is function "Add" from M_Articles:
public function Add($title, $content)
{
/*
$title = trim($title);
$content = trim($content);
if ($title == '')
return false;
//запрос
$object = array();
$object['title'] = $title;
$object['content'] = $content;
$this->msql->Insert('articles', $object);
*/
return true;
}
The thing is...even if I comment everything from function "Add" and leave only "return true"... it wouldn't redirect me to index.php. Moreover, it doesn't even echo anything (even those "sd;fkfdsf.." string). The script just dies for some reason. I can't get where is the problem, can some1 explain to newbie what's the problem and how it should be fixed? If you need additional info, i'll provide it.
update: Maybe it's important...but if I delete those comment "/* */" things, it'd correctly add article to a DataBase. But then the script dies=/
update:
ok, now it says: "Notice: Undefined variable: result in Z:\home\myblog\www\c\M_MSQL.php on line 86"
here's my code for M_MSQL on line 86:
public function Insert($table, $object)
{
$columns = array();
$values = array();
foreach ($object as $key => $value)
{
$key = mysql_real_escape_string($key . '');
$columns[] = $key;
if ($value === null)
{
$values[] = "'$value'";
}
else
{
$value = mysql_real_escape_string($value . '');
$values[] = "'$value'";
}
}
$columns_s = implode(',', $columns);
$values_s = implode(',', $values);
$query = "INSERT INTO $table ($columns_s) VALUES ($values_s)";
$result = mysql_query($query);
if (!$result)
die(mysql_error());
return mysql_insert_id();
}
Reason is you are outputing things, so you have a notice : "Headers already sent".
If you remove the "echo" stuff, you'll be alright :
if ($add_article)
{
header('Location: /index.php?article_added=1');
}