I have this helper method which job should be to prepare pagination data in order to retrieve it on controller...
Basically this is the code which happens in helper
if (!isset($_GET['page'])) {
$_GET['page'] = 1;
}
if (!isset($_GET['per_page'])) {
$_GET['per_page'] = 5;
}
$results = $ci->$model->get('', $_GET['per_page'], $_GET['page']);
And this is my model which should return data
public function get($tableName = "", $limit = null, $start = null)
{
if ($tableName == "") {
$tableName = $this->table;
}
if ($limit != null && $start != null) {
// problem is here with limit and start which returns wrong data
$this->db->limit($limit, $start);
$query = $this->db->get($tableName);
var_dump($query->result());
die();
}
} else {
$query = $this->db->get($tableName);
}
return $query->result();
}
Problem is that data returned from model isn't correct and i can't figure out how to get properly data based on page number and items per page....
So in my case if i request data with paramas $_GET['page'] = 1 and $_GET['per_page'] = 5 it will return 5 records, but starting with record 2 till record 6. So my question is how to properly request give me let say 5 records on starting page 1 and then give me another 5 records on page 2 ETC....
If you need any additional information please let me know and i will provide. Thank you
The problem lies within your $start variable. You should remember that when using getting the first the 5 records, you should use an offset 0 instead 1. Counting starts from 0 remember :)
The code should be
public function get($tableName = "", $limit = null, $start = null)
{
if ($tableName == "") {
$tableName = $this->table;
}
if ($limit != null && $start != null) {
// problem is here with limit and start which returns wrong data
//$this->db->limit($limit, $start);
// use this instead
$this->db->limit($limit, ( $start - 1 ) * $limit );
$query = $this->db->get($tableName);
var_dump($query->result());
die();
}
} else {
$query = $this->db->get($tableName);
}
return $query->result();
}
This is working example try to do like this: https://www.formget.com/pagination-in-codeigniter/
Related
I have an array() lenght=13 which I am using in foreach
$games = array(1,2,3,4,5,6,7,8,9,10,11,12,13);
foreach($games as $game_id){
$this->insertTrainingData($game_id, 'advance', 5);
$this->insertTrainingData($game_id, 'intermediate', 4);
$this->insertTrainingData($game_id, 'easy', 3);
}
The above foreach loop passes each game_id into insertTrainingData() for game_id insertion based on certain validations.
insertTrainingData() is validating each game_id before inserting the record, if all goes well then function store game_id for particular group (advance, intermediate, easy).
What is problem that I am facing?
It is when foreach loop passes game_id to three times called insertTrainingData() method in single iteration and jump into next iteration then same process. I am thinking on next iteration foreach loop passes game_id before completion of previous iteration job (insertTrainingData()).
So is this possible if I can stop foreach loop iteration until all functions return final result and then let foreach loop on next iteration. That's what I am thinking, not sure if I am wrong.
Here is function which decides to insert game_id for particular group based on validations.
private function insertTrainingData($game_id, $type, $limit){
$error = 0;
$result = true;
$todayTraining = Training::whereRaw("Date(created_at)=Curdate() and type='".$type."'")->get();
if($todayTraining->count() === $limit ){
$error = 1;
$result = false;
}
$todayExist = Training::whereRaw("Date(created_at)=Curdate() and game_id=$game_id")->get();
if($todayExist->count() > 0 || $todayExist->first() !== null){
$error = 1;
$result = false;
}
$recordInTwoRowDays = Training::whereRaw("created_at >= DATE_ADD(CURDATE(), INTERVAL -1 DAY) and game_id=$game_id and type='".$type."'")->get();
if($recordInTwoRowDays->count() > 0 ){
$error = 1;
$result = false;
}
if($error === 0){
$AddTraining = new Training;
$AddTraining->game_id = $game_id;
$AddTraining->type = $type;
$AddTraining->save();
$result = true;
}
return $result;
}
What happened when I executed above script?
Actually the above script added 6 rows for advance group however you can see the limit is 5
Can someone kindly guide me about it, I would really appreciate.
Thank you so much.
Your code is fine and it should not insert the 6th rows, maybe you are looking on wrong place, however, here is the code that you can improve:
It will not go for other if statement when the first statement is
false
Hence it will not call for second SQL statement
->count() is way much better than ->get()->count()
.
private function insertTrainingData($game_id, $type, $limit) {
$todayTraining = Training::whereRaw("Date(created_at)=Curdate() and type='".$type."'")->count();
if ($todayTraining >= $limit ) {
return false;
}
$todayExist = Training::whereRaw("Date(created_at)=Curdate() and game_id=$game_id")->count();
if ($todayExist > 0) {
return false;
}
$recordInTwoRowDays = Training::whereRaw("created_at >= DATE_ADD(CURDATE(), INTERVAL -1 DAY) and game_id=$game_id and type='".$type."'")->count();
if ($recordInTwoRowDays > 0 ) {
return false;
}
$addTraining = new Training();
$addTraining->game_id = $game_id;
$addTraining->type = $type;
$addTraining->save();
return true;
}
Is there a way to check 2 exists values in 1 table ?
It was work just fine when i use only 1 value 'beezName' but when i added another value 'divId' it didn't work, they only check whether the 'beezName' or 'divId' exist in table. I'm trying to get :
if beezName and divId exist then return true else false
How can i make this work? Thanks in advance
Here's my controller : Beez
function checkBeezExists()
{
$beezId = $this->input->post("beezId");
$beezName = $this->input->post("beezName");
$divId = $this->input->post("divId");
if(empty($beezId)){
$result = $this->beez_model->checkBeezExists($beezName, $divId);
} else {
$result = $this->beez_model->checkBeezExists($beezName, $divId, $beezId);
}
if(empty($result)){ echo("true"); }
else { echo("false"); }
}
And this is my model : beez_model
function checkBeezExists($beezName, $divId, $beezId= 0)
{
$this->db->select("beezName, divId");
$this->db->from("tbl_beez");
$this->db->where("beezName", $beezName);
$this->db->where("divId", $divId);
$this->db->where("isDeleted", 0);
if($beezId != 0){
$this->db->where("beezId !=", $beezId);
}
$query = $this->db->get();
return $query->result();
}
You want to check beezName and divId exist but in your model you have wrong condition for beezId
try below code:
function checkBeezExists($beezName, $divId, $beezId= 0)
{
$this->db->select("beezName, divId");
$this->db->from("tbl_beez");
$this->db->where("beezName", $beezName);
$this->db->where("divId", $divId);
$this->db->where("isDeleted", 0);
if($beezId != 0){
$this->db->where("beezId", $beezId); //<--------remove !=
}
$query = $this->db->get();
return $query->result();
}
Let me change my question completely to explain myself better;
I have an order;
An order have multiple order rows. Each order row has two fields; Quantity ordered, and quantity delivered.
If all order rows' quantities delivered are the same as the quantity ordered, the entire order should get a status of '100% delivered'.
If multiple or even one order row's quantities delivered does not match the quantities ordered the entire order should get a status of 'partly delivered'.
If no order row have any deliveries (if all deliveries stands on 0) the status should be '0% delivered'.
What I have so far looks only at the last order row of the entire order because all the previous rows gets overridden by the latest check. This is my code;
public function deliveryAction(Request $request, $id) {
$em = $this->getDoctrine()->getManager();
$order = $em->getRepository('QiBssBaseBundle:PmodOrder')->find($id);
$orderRowsDelivered = $request->request->all();
$delivered = "0%";
foreach ($orderRowsDelivered['order_row_id'] as $orderRowId => $quantityDelivered) {
if($quantityDelivered != '' || $quantityDelivered != null) {
$orderRow = $em->getRepository("QiBssBaseBundle:PmodOrderRow")->find($orderRowId);
$orderDelivered = new PmodDelivery();
$orderDelivered->setOrderRow($orderRow);
$orderDelivered->setQuantity($quantityDelivered);
$orderDelivered->setTimeArrived(new \DateTime());
$em->persist($orderDelivered);
$em->flush();
if($orderRow->getQuantityDelivered() > 0 && $orderRow->getQuantityDelivered() < $orderRow->getQuantity()) {
$delivered = "partly";
} elseif ($orderRow->getQuantityDelivered() == $orderRow->getQuantity()) {
$delivered = "100%";
}
}
}
var_dump($delivered);exit;
return new RedirectResponse ... ;
}
Because as of this moment he looks at the last one with 10 and 8 in the example image, and give a status of 'partly', as soon as the 'quantity delivered' amounts is entered. But he should take all rows together.
I hope this makes more sense.
Based on what Cerad in the comments of his own answer said, this is my answer; (I'll make use of OP's scenario where he uses order rows per order.)
I've added an extra property to my OrderRow entity called $rowStatus.
After that I created a getter function for the $rowStatus called getRowStatus() that gives each row a status individually;
public function getRowStatus()
{
if ($this->getQuantityDelivered() == $this->getQuantity()) {
return $this->rowStatus = 100;
} elseif ($this->getQuantityDelivered() == 0) {
return $this->rowStatus = 0;
} else {
return $this->rowStatus = 50;
}
}
After that in my Order entity I've added a $deliveryStatus property, with a corresponding getter function called getDeliveryStatus() that looks like this;
public function getDeliveryStatus()
{
if (count($this->getOrderRows()) > 0) { //this check is to make sure there are orderRows, because you can't devide by zero if it might happen that there are no order rows. If not the delivery status will just be set on 0.
$sum = 0;
foreach ($this->getOrderRows() as $row) {
$sum += $row->getRowStatus();
}
$average = $sum / count($this->getOrderRows());
if ($average == 100) {
return $this->deliveryStatus = 100;
} elseif ($average == 0) {
return $this->deliveryStatus = 0;
} else {
return $this->deliveryStatus = 50;
}
} else {
return $this->deliveryStatus = 0;
}
}
That's it! After this I just use an enum function to display the 100 as "100% delivered", the 50 as "partly delivered", and the 0 as "0% delivered". I know this isn't really necessary, and you can instead change the status number directly to a string or whatever you want to display.
Just off the top of my head I might do:
$deliveredNone = true;
$deliveredAll = true;
$deliveredSome = false;
foreach ($orderRowsDelivered['order_row_id'] as $orderRowId => $quantityDelivered) {
if ($quantityDelivered) {
$deliveredNone = false; // Know that something has been delivered
}
...
if ($orderRow->getQuantityDelivered() != $orderRow->getQuantity()) {
$deliveredSome = true;
$deliveredAll = false;
}
}
$delivered = null;
if ($deliveredNone) $delivered = '0%';
if ($deliveredAll) $delivered = '100%';
if ($deliveredSome) $delivered = 'partly';
Though I would probably just update the order with the quantities delivered then use a different function to calculate the percentage delivered. As you can see, mixing the two processes can result in confusion.
I seem to be having a problem with the below code. I cannot get the insert query to run when the query returns nothing. But when there is a row in the db, the else statement runs correctly. Does anybody know why this could be happening?
$query5 = $this->db->get_where('loggedstatus', array('userid_loggedstatus' => $userid));
if ($query5->num_rows() < 0) {
$data1 = array('isLoggedIn_loggedstatus' => 'yes', 'userid_loggedstatus' => $userid);
$this->db->insert('loggedstatus', $data1);
} else {
$data = array('isLoggedIn_loggedstatus' => 'yes');
$this->db->where('userid_loggedstatus', $userid);
$this->db->update('loggedstatus', $data);
}
Have you tried changing this if ($query5->num_rows() < 0) { to something like if ($query5->num_rows() <= 0) {, just a thought. It would make a difference because your telling it to only execute if its less than zero however it might be equal to zero and you would skip to the else statement.
And just for CodeIgniter num_rows() reference:
/**
* Number of rows in the result set
*
* #return int
*/
public function num_rows()
{
if (is_int($this->num_rows))
{
return $this->num_rows;
}
elseif (count($this->result_array) > 0)
{
return $this->num_rows = count($this->result_array);
}
elseif (count($this->result_object) > 0)
{
return $this->num_rows = count($this->result_object);
}
return $this->num_rows = count($this->result_array());
}
Changing if condition shown below should fix the problem.
if ($query5->num_rows() == 0)
my code-
function create_id()
{
//global $myusername;
$part1 = substr("Piyush", 0, -4);
$part2 = rand (99,99999);
$part3 = date("s");
return $part1.$part2.$part3;
}
echo create_id(); //this is printing fine.
function isUniqueUserID($userIDToCheck)
{
$sqlcheck = "Select * FROM ruser WHERE userId='$userIDToCheck';";
$resource = mysql_query($sqlcheck)or die(mysql_error());
$count = mysql_fetch_assoc($resource);
if( count($count) > 0)
{return false;}
return true;
}
$userIDVerifiedUnique = false;
while(! $userIDVerifiedUnique )
{
$userIDToCheck = create_id();
$userIDVerifiedUnique = isUniqueUserID($userIDToCheck );
}
loop is just going on and on from while loop to function IsUniqueUser() and vice versa.????
If there are no rows returned from the MySQL query (i.e. the $userIDToCheck is not in the table, it is unique) then mysql_fetch_assoc will return FALSE. When that happens, count(FALSE) returns 1 (one)! Since that value is greater than zero the function returns FALSE.
In short, if there is a row returned (the string is not unique) your isUniqueUserID function returns FALSE; if there is no row returned (the string is unique) it still returns FALSE.
A simple, new, function to check on the database table could look something like the following...
function isUniqueUserID($userIDToCheck)
{
$userIDToCheck = mysql_real_escape_string($userIDToCheck); // Assume not already escaped
$sqlcheck = "SELECT 1 FROM ruser WHERE userId='$userIDToCheck' LIMIT 1";
$resource = mysql_query($sqlcheck) or die(mysql_error());
return (bool) mysql_num_rows($resource);
}
First, try changing your isUniqueUserID() function to this
function isUniqueUserID($userIDToCheck)
{
$userIDToCheck = mysql_real_escape_string($userIDToCheck); //prevent SQL injection
$sqlcheck = "Select userId FROM ruser WHERE userId='$userIDToCheck';";
$resource = mysql_query($sqlcheck)or die(mysql_error());
$count = mysql_num_rows($resource);
return ($count > 0) ? false : true;
There's no point in returning an associative array just to count the number of rows in it. And there's no point in doing a SELECT * when counting just do SELECT userId since that's all you're concerned with.
I don't see any other reason that isUniqueUserID() would return false unless your ruser table has every possible ID.