Issues with returning Array from Connection Class - php

I am having an issue returning the array.
This is part of my connection class.
public function CreateDataSet($IncomingSql) {
$this->stmt = sqlsrv_query($this->conn, $IncomingSql);
if ($this->stmt) {
$this->Rows = sqlsrv_has_rows($this->stmt);
if ($this->Rows) {
while($this->Row = sqlsrv_fetch_array($this->stmt, SQLSRV_FETCH_NUMERIC))
{
$this->MyArray[] = $this->Row;
}
}
return $this->MyArray;
//$this->Result = $this->Row;
//return $this->Result;
}
}
And this is how I am calling it on my page...
$conn3 = new ConnectionClass;
$MyDataSet = $conn3->CreateDataSet('Select top (100) city, state, postalcode from store');
echo $MyDataSet[0];
I am using the echo just as a test.
The $MYDataSet is echoing nothing. I can see the $MyArray fill up with all 100 records when I debug, but it does not return it..

Related

foreach or while only displays last result

This structure will have several pages only foreach or while is only showing the last result, this problem occurred after I made this function, I've seen several questions and is something related to matriz
class Layout {
private $sql, $row;
private function set_layout($cond, $cond_r) {
$this->sql = $this->select("*", "table", "".$cond."", array($cond_r));
foreach ($this->sql as $this->row) :
return $this->row['name'];
endforeach;
}
public function get_layout($cond, $cond_r) {
return $this->set_layout($cond, $cond_r);
}
}
echo $midia->get_layout("WHERE status != ? ORDER BY id DESC", 0);
I'm not sure but I think you're looking for something like:
class Layout {
private $sql, $row;
private function set_layout($cond, $cond_r) {
$this->sql = $this->select("*", "table", "".$cond."", array($cond_r));
$rows = array();
foreach ($this->sql as $this->row) :
$rows[] = $this->row['name'];
endforeach;
return implode($rows); //Return array of rows AFTER loop
}
public function get_layout($cond, $cond_r) {
return $this->set_layout($cond, $cond_r);
}
}
echo $midia->get_layout("WHERE status != ? ORDER BY id DESC", 0);

recursive function is not working as expected.

public function subchapt()
{
$result = $this->recursive_subchapter_id($level_title);
}
public function recursive_subchapter_id($level_title)
{
$level_data = $this->db->query("SELECT * FROM presto_project_level WHERE level_title ='". $level_title."'")->result_array();
if(count($level_data)>0){
$parentid1 = '';
$leveltitle1 = '';
$parentid1 = trim($level_data[0]['parent_id']);
$leveltitle1 = trim($level_data[0]['level_title']);
if($parentid1 == '0') {
return $leveltitle1;die;
}
else
{
$res = $this->recursive_subchapter_id($parentid1);
return $res;die;
}
}
else{
return $level_title;die;
}
}
every time getting result array is null. i tried directly in url so it was give result array and its count. but while call from other function it was give count of zero.
instead of checking the parentid in the recursive_subchapter_id(), check in subchapt() and then call again recursive_subchapter_id() if it not satisfy the condition.

Cant return from a function to my html

this is my html file index.php
<?php
require_once(realpath(dirname(__FILE__)).'/../environments/include/ShowDataClass.php');
$Show = new ShowDataClass();
foreach ($Show->getAllUserPayments() as $key => $v) {
if($v->date_reg != 0){
$date_reg = $v->date_reg;
}else{
$date_reg = $Show->getInsertDate($v->metadata);
}
echo $date_reg;/*here the problem*/
}
this is my ShowDataClass.php
class ShowDataClass extends DbClass{
public function getInsertDate($id){
$query = "SELECT * FROM metadata WHERE id = $id";
$this->rs = $this->loadObjectList($query);
if($this->rs[0]->prev_metadata == 0){
$date = $this->rs[0]->date.' '.$this->rs[0]->time;
}else{
$this->getInsertDate($this->rs[0]->prev_metadata);
}
return strval($date);
}
}
expected result 2017-09-18 19:22:49 but i got empty, getInsertData($v->metadata) all times send an id.
if i do an echo inside ShowDataClass in line 6 it return me the desired data.
could you please help me with this, need to use return but not working?
You have to return in the recursive call:
return $this->getInsertDate($this->rs[0]->prev_metadata);
Full code:
class ShowDataClass extends DbClass{
public function getInsertDate($id){
$query = "SELECT * FROM metadata WHERE id = $id";
$this->rs = $this->loadObjectList($query);
if($this->rs[0]->prev_metadata == 0){
$date = $this->rs[0]->date.' '.$this->rs[0]->time;
}else{
return $this->getInsertDate($this->rs[0]->prev_metadata);
}
return strval($date);
}
}

how to implode and insert values into db in codeigniter?

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.

How to change the number of specifiers with count of providing array in php

My code is given bellow
Controller code:
class statController extends baseController {
public function index() {
$this->registry->template->projectsWise = $this->selectProjectWise();
$this->registry->template->show("stat");
}
private static function selectStat($query, $values) {
$statMapper = new statMapper();
$select = new common();
$select->setItems($query);
$select->setValues($values);
return $statMapper->select($select);
}
private function selectProjectWise() {
$date = date("Y-m-d");
$values = array($date, $date);
return self::selectStat("project_wise", $values);
}
private function selectLocationWise(){
$date = date("Y-m-d");
$values = array($date, $date, 1);
return self::selectStat("location_wise", $values);
}
Mapper code:
class statMapper extends baseMapper {
private $query = array(
"project_wise" => "SELECT p.proj_Name, p.proj_Type, p.proj_Category, COUNT(ra.emp_Id) as allocation FROM project AS p, resource_assignment AS ra WHERE p.proj_Start_Date <= '%s' AND p.proj_End_Date >= '%s' AND p.proj_Status = 1 AND ra.proj_Id = p.proj_Id GROUP BY p.proj_Name ",
"location_wise" => "SELECT e.user_Location, p.proj_Name, p.proj_Type, p.proj_Category, COUNT(ra.emp_Id) as allocation FROM project AS p, resource_assignment AS ra, employee as e WHERE p.proj_Start_Date <= '%s' AND p.proj_End_Date >= '%s' AND p.proj_Status = %d AND ra.proj_Id = p.proj_Id GROUP BY p.proj_Name "
);
public function select($select) {
$connect = parent::connect();
$query = sprintf($this->query[$select->getItems()], $select->getValues()[0], $select->getValues()[1]);
try {
$result = $connect->query($query);
if ($result) {
$table = array();
while ($row = $result->fetch_object()) {
$table[] = $row;
}
return $table;
parent::disconnect();
} else {
throw (new Exception($connect->error . "<br/>" . $query . "<br/>"));
}
} catch (Exception $exp) {
require_once 'views/error.php';
exit();
}
}
}
I have added 3 specifiers ($query->"location_wise") In statController->selectLocationWise() function.
When I use it how do I add $select->getValues()[2] value in statMapper->select(), instead of add it manually.
You can use http://www.php.net/manual/ru/function.vsprintf.php instead of sprintf to pass whole array as argument.
But anyway your code looks bad. From the outside view of StatMapper there is no way to identify neither types of arguments, nor their count. Code will be hard to be maintained.
I advise to use Data Access Objects pattern or learn framework.

Categories