I'm trying to connect from Prestashop to external database (ERP) to get the order history from it.
I've cloned the History controller and named it "residui".
I've created ResiduiController.php that contains:
class ResiduiControllerCore extends FrontController {
public $auth = true;
public $php_self = 'residui';
public $authRedirection = 'residui';
public $ssl = true;
public function setMedia() {
parent::setMedia();
$this->addCSS(array(
_THEME_CSS_DIR_.'residui.css',
));
$this->addJS(array(
_THEME_JS_DIR_.'history.js',
_THEME_JS_DIR_.'tools.js' // retro compat themes 1.5
));
$this->addJqueryPlugin('footable');
$this->addJqueryPlugin('footable-sort');
$this->addJqueryPlugin('scrollTo'); }
public function initContent() {
parent::initContent();
$residui = Order::getCustomerResidui($this->context->customer->id);
$this->context->smarty->assign(array(
'residui' => $residui
));
$this->setTemplate(_PS_THEME_DIR_.'residui.tpl'); } }
I've inserted the class getCustomerResidui in Order.php:
public static function getCustomerResidui($id_customer, $showHiddenStatus = false, Context $context = null) {
if (!$context)
$context = Context::getContext();
$evadi = 'S';
$stato = 'GENERATO';
$resi = Db::getFromGazie()->executeS("
SELECT *
FROM "._GAZ_PREFIX_."tesbro
WHERE id_cli_presta = '".(int)$id_customer."' AND status = '".$stato."'
ORDER BY id_tes DESC");
if (!$resi)
return array();
foreach ($resi as $key => $val) {
$resi2 = Db::getFromGazie()->executeS("
SELECT *
FROM "._GAZ_PREFIX_."rigbro
WHERE id_doc = '".$val['numdoc']."' AND evadi <> '".$evadi."'
ORDER BY codart DESC LIMIT 1");
if ($resi2)
$resi[$key] = array_merge($resi[$key], $resi2[0]); }
return $resi; } }
I've added the getFromGazie instance in DB.php and all connection parameters to the external DB in settings.inc.php, such as GAZ_PREFIX, etc.
DB.php:
public static function getFromGazie($master = true) {
static $id = 0;
// This MUST not be declared with the class members because some defines (like _DB_SERVER_) may not exist yet (the constructor can be called directly with params)
if (!self::$_servers)
self::$_servers = array(
array('gaz_server' => _GAZ_SERVER_, 'gaz_user' => _GAZ_USER_, 'gaz_password' => _GAZ_PASSWD_, 'gaz_database' => _GAZ_NAME_), /* MySQL Master server */
);
Db::loadSlaveServers();
$total_servers = count(self::$_servers);
if ($master || $total_servers == 1)
$id_server = 0;
else {
$id++;
$id_server = ($total_servers > 2 && ($id % $total_servers) != 0) ? $id % $total_servers : 1; }
if (!isset(self::$instance[$id_server])) {
$class = Db::getClass();
self::$instance[$id_server] = new $class(
self::$_servers[$id_server]['gaz_server'],
self::$_servers[$id_server]['gaz_user'],
self::$_servers[$id_server]['gaz_password'],
self::$_servers[$id_server]['gaz_database']); }
return self::$instance[$id_server]; }
The template, residui.tpl:
<div class="block-center" id="block-history">
<table id="order-list" class="table table-bordered footab">
<thead>
<tr>
<th class="first_item" data-sort-ignore="true">{l s='Order reference'}</th>
<th class="item">{l s='Date'}</th>
</tr>
</thead>
<tbody>
{foreach from=$residui item=residuo name=myLoop}
<tr class="{if $smarty.foreach.myLoop.first}first_item{elseif $smarty.foreach.myLoop.last}last_item{else}item{/if} {if $smarty.foreach.myLoop.index % 2}alternate_item{/if}">
<td class="history_link bold">
<p class="color-myaccount">
{$residuo['numdoc']}
</p>
</td>
<td class="history_date bold">
{$residuo['datemi']}
</td>
</tr>
{/foreach}
</tbody>
</table>
<div id="block-order-detail" class="unvisible"> </div>
The problem is that I don't get any line displayed (I also tested the query manually in PhpMyAdmin).
I tried for hours but I can't see the mistake (and I'm sure I did one or more).
Can you tell me something? Thanks...
Got it!!!!
First of all thanks to Sergii P that suggests me _PS_MODE_DEV_ that I didn't know...
The problem was that it was always trying to execute the query on the same DB. To solve that, i added _GAZ_NAME_ before _GAZ_PREFIX_, like this:
public static function getCustomerResidui($id_customer, $showHiddenStatus = false, Context $context = null)
{
if (!$context)
$context = Context::getContext();
$evadi = 'S';
$stato = 'GENERATO';
$resi = Db::getFromGazie()->executeS("
SELECT *
FROM "._GAZ_NAME_."."._GAZ_PREFIX_."tesbro
WHERE id_cli_presta = '".(int)$id_customer."' AND status = '".$stato."'
ORDER BY id_tes DESC");
if (!$resi)
return array();
foreach ($resi as $key => $val)
{
$resi2 = Db::getFromGazie()->executeS("
SELECT *
FROM "._GAZ_NAME_."."._GAZ_PREFIX_."rigbro
WHERE id_doc = '".$val['numdoc']."' AND evadi <> '".$evadi."'
ORDER BY codart DESC LIMIT 1");
if ($resi2)
$resi[$key] = array_merge($resi[$key], $resi2[0]);
}
return $resi;
}
Et voilĂ , everything works fine!
Related
How to implode and insert values into the database in CodeIgniter?
I am creating multiple choice quiz script using CodeIgniter framework. I want to store user results like this:
id userid q_id answer_id time_taken
1 1 1,2,3,4,5 2,3,4,5,3 4,5,7,6,7
in my controller:
public function insert_result()
{
$this->load->model('quiz_models');
$user_id=$this->input->post('user_id');
$qq_id=$this->input->post('questionid');
$answer_id=$this->input->post('AnswerID');
$time_taken=$this->input->post('timetaken');
$question_no=$this->input->post('question_no');
$bd = "$question_no";
switch ($bd) {
case"1":
$data=array('user_id'=>$user_id,
'q_id'=>$qq_id,
'answer_id'=>$answer_id,
'time_taken'=>$time_taken);
$this->quiz_models->insert_result($data);
break;
case"2":
quiz_test();
break;
case"3":
quiz_test();
break;
case"4":
quiz_test();
break;
case"5":
quiz_test();
$this->session->unset_userdata('lastids');
break;
default:
echo "something is wrong";
}
}
public function quiz_test()
{
$this->load->model('quiz_models');
$quiz=$this->quiz_models->quiz_test();
foreach($quiz as $row){
$qid=$row->q_id;
$ans=$row->answer_id;
$time=$row->time_taken;
$a = array("$qq_id","$qid");
$b = array("$answer_id","$ans");
$c = array("$time_taken","$time");
$comma = implode(",",$a);
$comma1 = implode(",",$b);
$comma2 = implode(",",$c);
$data=array('q_id'=>$comma,
'answer_id'=>$comma1,
'time_taken'=>$comma2);
$this->quiz_model->update_result($data);
}
}
}
and Model:
function insert_result($data)
{
$this->dbb->insert('results',$data);
$sectio=$this->db->insert_id();
$this->session->set_userdata('lastids',$sectio);
}
function quiz_test()
{
$ses_id = $this->session->userdata('lastids');
$sql = "SELECT q_id, answer_id, time_taken FROM results WHERE id='$ses_id'";
$query = $this->dbb->query($sql);
$result = $query->result();
return $result;
}
function update_result($data){
$ses_id = $this->session->userdata('lastids');
$this->db->where('id',$ses_id);
$this->db->update('results',$data);
}
when i run it nothing happened,not showing any error where do i mistake?
pls help me what am i doing wrong
First of all - i think you've a major problem in your DB structure
Normalize your Data
You should prevent to store your information in the table like that.
It should be possible to normalize your data properly. If you dont know
how to do that the following link could be interesting:
Normalization in MYSQL
However a possible solution would be to structure your data:
In order to do that - create a save Method in your Model to split between update and insert - this model could look like
class Quiz_Models
{
private $arrPostData;
public function save($arrPostData = false)
{
$this->arrPostData = (!$arrPostData) ? $this->input->post() : $arrPostData;
$id = $this->session->userdata("lastids");
if ($id)
{
$query = $this->db
->select("*")
->from("results")
->where("id",$id)
->get();
if ($query->num_rows() == 1)
{
$this->update($query->row(0));
}
else return false;
}
else
{
$this->insert();
}
if ($this->arrPostData['question_no'] == 10) $this->session->unset_userdata("lastids");
}
private function update($objData)
{
$objCollection = new Quiz_Collection();
$objCollection->userId = $objData->userid;
$objCollection->id = $objData->id;
$arrData = explode($objData->q_id);
foreach($arrData AS $key => $quizId)
{
$objQuiz = new stdClass();
$objQuiz->q_id = $quizId;
$objQuiz->answer_id = explode($objData->answer_id)[$key];
$objQuiz->time_taken = explode($objData->answer_id)[$key];
$objCollection->append($objQuiz);
}
$objQuizFromPost = new stdClass();
$objQuizFromPost->q_id = $this->arrPostData["questionid"];
$objQuizFromPost->answer_id = $this->arrPostData['AnswerID'];
$objQuizFromPost->time_taken = $this->arrPostData['timetaken'];
$objCollection->addQuizFromPost($objQuizFromPost);
$this->db
->where("id",$objCollection->id)
->update("results",$objCollection->getDbData());
}
private function insert()
{
$objCollection = new Quiz_Collection();
$objCollection->userId = $this->arrPostData['user_id'];
$objQuizFromPost = new stdClass();
$objQuizFromPost->q_id = $this->arrPostData["questionid"];
$objQuizFromPost->answer_id = $this->arrPostData['AnswerID'];
$objQuizFromPost->time_taken = $this->arrPostData['timetaken'];
$objCollection->addQuizFromPost($objQuizFromPost);
$this->db->insert("results",$objCollection->getDbData());
$this->session->set_userdata("lastids", $this->db->insert_id());
}
}
as an addition you need a Collection Object (put this below your model)
class Quiz_Collection extends Array_Object
{
public $userId = 0;
public $id = 0;
public function addQuizFromPost($objQuiz)
{
if (intval($objQuiz->q_id) > 0)
{
foreach($this AS $key => $obj)
{
if ($obj->q_id == $objQuiz->q_id)
{
$this->offsetSet($key, $objQuiz);
return true;
}
}
$this->append($objQuiz);
return true;
}
return false;
}
public function sortQuizData($objA, $objB)
{
if ($objA->q_id == $objB->q_id) return 0;
return ($objA->q_id < $objB->q_id) ? -1 : 1;
}
public function getDbData()
{
$this->uasort(array($this,"sortQuizData"));
$arrData = $this->getArrayCopy();
$arrDbData = [
"userid" => $this->userId,
"q_id" => implode(array_map(function($obj){ return $obj->q_id;},$arrData),","),
"answer_id" => implode(array_map(function($obj){ return $obj->answer_id;},$arrData),","),
"time_taken" => implode(array_map(function($obj){ return $obj->time_taken;},$arrData),","),
];
return $arrDbData;
}
}
pS: this is just an instruction how you can do that in a proper way. Pls study this code. If you still don't understand whats going on, feel free to ask.
Currently I'm trying to display all the payments I have received that were inserted into my database (payment_history) I want to show them in a html table, but every time I try it, It only shows me 1 user on the html table, but I have more than one user in the SQL table on phpmyadmin.
Php sided code.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class payment_history_model extends MY_Model {
public function __construct(){
parent::__construct();
}
public function getPaymentHistory(){
$accounts = $this->model->fetch("*", PAYMENT_HISTORY, getDatabyUser(0), "id", "asc");
if(!empty($accounts)){
foreach ($accounts as $key => $row) {
$user = $this->model->get("*", USER_MANAGEMENT, "id = '".$row->uid."'");
if(!empty($user)){
$accounts[$key]->user = $user->fullname;
}else{
$accounts[$key]->user = "";
}
}
}
return $accounts;
}
}
My html table code.
<thead>
<tr>
<th><?=l('User')?></th>
<th><?=l('Invoice')?></th>
<th><?=l('First name')?></th>
<th><?=l('Last name')?></th>
<th><?=l('Receiver email')?></th>
<th><?=l('Payer email')?></th>
<th><?=l('Package')?></th>
<th><?=l('Price')?></th>
<th><?=l('Currency')?></th>
<th><?=l('Street')?></th>
<th><?=l('City')?></th>
<th><?=l('Country')?></th>
<th><?=l('Payment date')?></th>
<th><?=l('Payment status')?></th>
<th><?=l('Option')?></th>
</tr>
</thead>
<tbody>
<?php
if(!empty($result)){
foreach ($result as $key => $row) {
?>
<tr class="pending" data-action="<?=cn('ajax_action_item')?>" data-id="<?=$row->id?>">
<td>
<input type="checkbox" name="id[]" id="md_checkbox_<?=$key?>" class="filled-in chk-col-red checkItem" value="<?=$row->id?>">
<label class="p0 m0" for="md_checkbox_<?=$key?>"> </label>
</td>
<td><?=$row->user?></td>
<td><?=$row->invoice?></td>
<td><?=$row->first_name?></td>
<td><?=$row->last_name?></td>
<td><?=$row->receiver_email?></td>
<td><?=$row->payer_email?></td>
<td><?=$row->item_name?></td>
<td><?=$row->mc_gross?></td>
<td><?=$row->mc_currency?></td>
<td><?=$row->address_street?></td>
<td><?=$row->address_city?></td>
<td><?=$row->address_country?></td>
<td><?=$row->payment_date?></td>
<td><?=$row->payment_status?></td>
<td><?=$row->Option?></td>
</tr>
</tbody>
Ok, your class MyModel from http://pastebin.com/Vc8tUvpH contains fetch method:
function fetch($select = "*", $table = "", $where = "", $order = "", $by = "DESC", $start = -1, $limit = 0, $return_array = false)
{
...
}
Now, we can say that the problem can be in $where = getDatabyUser(0).
Most likely getDatabyUser(0) adds where clause which limits your result to one row.
You should try:
output getDatabyUser(0) like var_dump(getDatabyUser(0))
open phpmyadmin and add the same where clause and check result
Now it looks like you're trying to get payment history for user with ID = 0.
You can check it also, by replacing getDatabyUser(0) with ""(empty string).
public function getPaymentHistory(){
$accounts = $this->model->fetch("*", PAYMENT_HISTORY, "", "id", "asc");
if(!empty($accounts)){
foreach ($accounts as $key => $row) {
$user = $this->model->get("*", USER_MANAGEMENT, "id = '".$row->uid."'");
if(!empty($user)){
$accounts[$key]->user = $user->fullname;
}else{
$accounts[$key]->user = "";
}
}
}
return $accounts;
}
I will start from very beginning, I am creating small CMS with code igniter and I faced with few problems. I am junior in working with php frameworks, so please do not be angry at me.
Right now I have vehicles models lists from database and that one is large. So I got Error from CodeIgniter:
A PHP Error was encountered
Severity: Error
Message: Allowed memory size of
At this moment I'm already commented the line of code from code igniter output configuration file, which shows me this error. And I have a clear list of values, that I want to have. But its too many. So I thought about PAGINATION.
What its your opinion, can it help me? maybe you have some better advice/suggestion?
So I tried to turn that error down and create a pagination, but I failed.
This is my controller if "lists":
public function lists(){
//get models
$data['models'] = $this->Model_model->get_models('id', 'DESC');
//get brands
$data['brands'] = $this->Model_model->get_brands('id', 'DESC');
//get brands
$data['brand'] = $this->Model_model->get_brands('id', 'DESC');
//get categories
$data['categories'] = $this->Model_model->get_categories('id', 'DESC');
//get Users
//$data['users'] = $this->User_model->get_users('id', 'DESC', 5);
//View
$data['main_content'] = 'admin/models/lists';
$this->load->view('admin/layouts/main', $data);
}
This is code from model file:
<?php
class Model_model extends CI_Model
{
/*
* Get vehicle models
*
* #param - $order_by (string)
* #param - $sort (string)
* #param - $limit (int)
* #param - $offset (int)
*
* */
public function get_models($order_by = null, $sort = 'DESC', $limit = null, $offset = 0)
{
$this->db->select('vm.*, vb.v_brand_name as v_brand_name, vc.category_name as category_name, u.first_name, u.last_name');
$this->db->from('vehicle_models as vm');
$this->db->join('vehicle_brands as vb', 'vb.id = vm.vehicle_brand_id');
$this->db->join('vehicle_category as vc', 'vc.id = vb.vehicle_category_id', 'vb.vehicle_category_id = vm.vehicle_category_id', 'left');
$this->db->join('users as u', 'u.id = vb.user_id', 'left');
if ($limit != null) {
$this->db->limit($limit, $offset);
}
if ($order_by != null) {
$this->db->order_by($order_by, $sort);
}
$query = $this->db->get();
return $query->result();
}
/*
*
*Get Menu Items
*
* */
/* public function get_models(){
$this->db->where('id', 1);
$this->db->order_by('id');
$query = $this->db->get('vehicle_models');
return $query->result;
}*/
/*
*GET SINGLE ARTICLE
* */
public function get_model($id)
{
$this->db->where('id', $id);
$query = $this->db->get('vehicle_models');
return $query->row();
}
/*
* Get vehicle Categories
*
* #param - $order_by (string)
* #param - $sort (string)
* #param - $limit (int)
* #param - $offset (int)
*
* */
public function get_categories($order_by = null, $sort = 'DESC', $limit = null, $offset = 0)
{
$this->db->select('*');
$this->db->from('vehicle_category');
if ($limit != null) {
$this->db->limit($limit, $offset);
}
if ($order_by != null) {
$this->db->order_by($order_by, $sort);
}
$query = $this->db->get();
return $query->result();
}
/*
* Get vehicle Brands
*
* #param - $order_by (string)
* #param - $sort (string)
* #param - $limit (int)
* #param - $offset (int)
*
* */
public function get_brands($order_by = null, $sort = 'DESC', $limit = null, $offset = 0)
{
$this->db->select('*');
$this->db->from('vehicle_brands');
if ($limit != null) {
$this->db->limit($limit, $offset);
}
if ($order_by != null) {
$this->db->order_by($order_by, $sort);
}
$query = $this->db->get();
return $query->result();
}
/*
*
*Insert Model
*
* */
public function insert($data){
$this->db->insert('vehicle_models', $data);
return true;
}
/*public function insert_models($data){
$models = implode(',',$_POST['v_model_name']);
$this->db->insert('vehicle_models', $data);
$this->db->into('vehicle_models', $data);
$this->db->values($model);
}*/
public function update($data, $id){
$this->db->where('id', $id);
$this->db->update('vehicle_models', $data);
return true;
}
public function did_delete_row($id){
$this -> db -> where('id', $id);
$this -> db -> delete('vehicle_models');
return true;
}
/* --------------------------- PAGINATION ---------------------------------*/
public function __construct() {
parent::__construct();
}
public function record_count() {
return $this->db->count_all("vehicle_models");
}
public function fetch_countries($limit, $start) {
$this->db->limit($limit, $start);
$query = $this->db->get("vehicle_models");
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
/*-------------------------- AND OF PAGINATION ---------------------------------------*/
}
And this is my view file:
<?php foreach($categories as $category) :?>
<?php
$this->load->helper("url"); /
$postid = $this->uri->segment(4);
if ($category->id == $postid):
?>
<!-- ************************* ****************************************-->
<div class="table-responsive col-md-12">
<h2><?php echo $category->category_name; ?></h2>
<table class="table table-striped">
<thead>
<tr>
<th>Model (+View)</th>
<th>Brand</th>
<th>Category</th>
<th></th>
<th>Moves</th>
</tr>
</thead>
<tbody>
<?php foreach ($models as $model) : ?>
<?php if($model->vehicle_category_id == $postid) :?> <!-
<tr>
<td>
<?php echo $model->v_model_name; ?>
</td>
<?php foreach($brands as $brand) :?><?php if($model->vehicle_brand_id == $brand->id) :?>
<td>
<?php echo $brand->v_brand_name; ?>
</td>
<?php endif; ?>
<?php endforeach; ?>
<td>
<?php echo $model->category_name; ?>
</td>
<td>
</td>
<td>
Edit
Delete
</td>
</tr>
<?php endif; ?>
<?php endforeach; ?>
</tbody>
</table>
</div>
<!-- ************************* ****************************************-->
<?php endif;?>
<?php endforeach; ?>
** MORE QUESTIONS**
So maybe somebody can help me to create PAGINATION?
I tried to put this code to "list" controller function but its didnt
work:
public function lists1(){
$this->load->library('pagination');
$config['base_url'] = 'http://localhost/test/admin/Models/lists/';
$config['per_page'] = 5;
$config['num_links'] = 5;
$config['total_rows'] = $this->db->get('vehicle_models')->num_rows();
/*$config['total_rows'] = $this->db->get_models('v_model_name');*/
$this->pagination->initialize($config);
$data['query'] = $this->db->get('vehicle_models', $config['per_page'],$this->uri->segment(4)); /*segment*/
$this->load->view('admin/models/lists', $data); /*nuoroda*/
echo $this->pagination->create_links();
$data['main_content'] = 'admin/models/lists';
$this->load->view('admin/layouts/main', $data);
Will pagination will help me to deal with to many list items?
Maybe somebody can help me with code? Thanks.
Your codeigniter code is storing the entire list in array first. After that you are trying to build the screen. Perhaps you can start with a SQL join and use limit in that join to restrict the number of rows. Also, send your script page number for pagination.
<?php
$current = $_GET['page'];
$rowCount = $_GET['length'];
$sql = "select * from model m
inner join brand b
on m.vehicle_brand_id = b.id
limit ".($current - 1)*($rowCount).",".$rowCount;
$query = $this->db->query($sql);
$content['tableList'] = $query->result();
In this way, you will not pull entire data, which eventually causes memory exhaustion error.
I have the following function that aims to fetch all credits from an artist for a particular song using the ID from the url ($id), and a foreach statement that displays the information on the Web page. At the moment it's displaying the artist names fine, but the IDs aren't being displayed. How would I go about returning the ID information so it's displayed as well?
function getArtistsBySongId($id)
{
$query = "SELECT * FROM `Credit_To_Artist` AS c2a
INNER JOIN `Credits` AS cr ON cr.credit_id = c2a.credit_id
INNER JOIN `Artist` AS a ON a.artist_id = c2a.artist_id
LEFT OUTER JOIN `Song` AS s ON s.song_id = c2a.song_id
LEFT OUTER JOIN `Project` AS p ON p.project_id = s.project_id
WHERE c2a.song_id = $id";
$res = mysql_query($query);
$artists = Array();
$artisttoid = Array();
$songtoid = Array();
while( $row = mysql_fetch_array($res) ) {
$artist = $row[artist_name];
$credit = $row[credit_name];
$songcr = $row[song_id];
if(!array_key_exists($artist, $artists) ) {
$artists[$artist] = Array();
$artisttoid[$artist] = $row[artist_id];
$songtoid[$songcr] = $row[song_id];
}
$artists[$artist][] = $credit;
}
return $artists;
return $songtoid;
return $artisttoid;
}
I've used include's in the code because I'm still green to PHP and find it easier to understand.
<table border="0" cellspacing="5" cellpadding="5" class="cdinfo" width="100%;">
<tr>
<?php
if (getArtistsBySongId($id) == NULL) {
echo "<th style='font-size: 13px'>Credits:</th>";
echo "<td style='font-size: 13px'>There are currently no artists linked to this song.</td>";
} else {
include 'songs/getsongcredits.php';
}
?>
</tr>
</table>
songs/getsongcredits.php
<?php foreach (getArtistsBySongId($id) as $artist => $creditarr) {
$credits = implode( ", ", $creditarr );
echo "<a href='star.php?id={$artisttoid[$artist]}'>{$artist}</a> ({$credits})<br />";
} ?>
Objects or arrays are the way to do it
return array('artists' => $artists, 'songtoid' => $songtoid, 'artisttoid' => $artisttoid);
I recomend you to return an object with each item you want in attributes.
To return an object, firstly you need a class:
class MyClass {
private $artists;
private $songtoid;
private $artisttoid;
public function __construct($arg1, $arg2, $arg3){
$this->artists = $arg1;
$this->songtoid = $arg2;
$this->artisttoid = $arg3;
}
public function getArtists(){return $this->artists;}
public function getSongtoid(){return $this->songtoid;}
public function getArtisttoid(){return $this->artisttoid;}
}
In your function
function getArtistsBySongId(){
...
return new MyClass($artists, $songtoid, $artisttoid);
}
Also you can return an associative array like this
return array(
"artists"=>$artists,
"songtoid"=>$songtoid,
"artisttoid"=>$artisttoid
);
Or, if you want, you can return an array (as Machavity answered) and read the result using list()
function getArtistsBySongId(){
...
return array($artists, $songtoid, $artisttoid);
}
list($artists, $songtoid, $artisttoid) = getArtistsBySongId();
Could someone give me some assistance on adding reply to my commenting system.
I'm creating a project on Smarty 3 and so far i have done the comments part but i'm having a bit of trouble with the reply part because it won't display the replies could someone check my code to see what i am doing wrong or correct it for me please here is my code below.
PHP Functions from movie class
public function GetMovieComments($con, $movie_id) {
$c = array();
$q = mysqli_query($con,"SELECT * FROM `movie_comments`,`user` WHERE `movie_id` = '".$movie_id."' AND `uid` = `user_id`");
if (mysqli_num_rows($q) > 0) {
while ($r = mysqli_fetch_assoc($q)) {
$c[] = $r;
}
return $c;
}
}
public function GetMovieReplies($con, $comment_id) {
$comment_id = mysqli_real_escape_string($con, $comment_id);
$rp = array();
$q = mysqli_query($con,"SELECT * FROM `movie_replies`,`user` WHERE `comment_id` = '".$comment_id."' AND `uid` = `user_id`");
if (mysqli_num_rows($q) > 0) {
while ($r = mysqli_fetch_assoc($q)) {
$rp[] = $r;
}
return $rp;
}
}
Now calling the functions from movie.php
$comments = $movie->GetMovieComments($con, $movie_id);
if (isset($comments)) {
foreach($comments as $comment) {
$comment_id = $comment['cid'];
$replies = $movie->GetMovieReplies($con, $comment_id);
$smarty->assign('replies',$replies);
}
}
$smarty->assign('comments', $comments);
Now in movie.tpl
{if isset($comments)}
{if $comments neq ''}
{foreach from=$comments key=key item=comment}
<div class="media">
<div class="media-body">{$comment.comment}</div>
</div>
{foreach from=$replies key=key item=reply}
<h4>{$reply.reply}</h4>
{/foreach}
{/foreach}
{else}
<h5>No Comments</h5>
{/if}
{/if}
Could someone please help me i have been trying to solve this for hours lol thanks
For not overwriting the variable replies, I'd do something like this:
// Make GetMovieComments return an array with values or simply an array(), so no check needed
$comments = $movie->GetMovieComments($con, $movie_id);
foreach($comments as $key => $comment) {
$replies = $movie->GetMovieReplies($comment['cid']);
$comments[$key]['replies'] = $replies;
}
$smarty->assign('comments', $comments);
Then you can access the {foreach from=$comment.replies key=key item=reply} to use it within the inner foreach. However that was just one thing, there might be more mistakes in the code...
A couple of things I'd do extra with your code:
public function GetMovieComments($movie_id) {
$comments = array();
// Some data validation to avoid SQL Injections
// You might be better with binding parameters if it's not an int
$id = intval($movie_id);
// You use the connection already stored in this object. You should set it in the constructor
$query = mysqli_query($this->con,"SELECT * FROM `movie_comments`,`user` WHERE `movie_id` = '" . $id . "' AND `uid` = `user_id`");
// No need for the if. This will only enter if there's any result anyway
while ($result = mysqli_fetch_assoc($query)) {
$comments[] = $result;
}
return $comments;
}
// Apply some similar changes to GetMovieReplies() as the ones above.