I am using Zend fetch method to fetch huge number of records from database for creating reports.Since fetchAll is costly as compared to fetch i am using it.And if its the last row i need to add some additinoal logic.So my question is that is there a way to check if next record exists or not inside the while loop. I am using it like the following
//$select is the select query
$objDb = Zend_Registry::get('db');
$objAchQry = $objDb->query($select);
while($arrResult = $objAchQry->fetch()) {
//Do something
//I need to do something here if its the last record like
/*
if($last_rec)
do something
*/
}
Is there a way to check if the current one is last record or if any other record exists. I know to do it by taking count of records and incrementing a counter inside the loop.But i dont need it.Any solutions.?
"is there a way to check if next record exists" The condition on your while loop does exactly just that. The loop won't execute any more if no more rows exist to fetch.
Think of it this way:
while($arrResult = $objAchQry->fetch()) {
//Do something
}
// Now I'm just after the last record
/*
do something
*/
If you really need to do something before the last row is processed, you could modify your code to
$total_records = // get total no of rows
$counter = 0;
while($arrResult = $objAchQry->current()) {
//Do something
$counter ++;
//I need to do something here if its the last record like
if( ! $bojAchQry->next()) {
// The row currently being processed is the last one.
} else {
break;
}
}
One way - You can track with counter,
$total_records = // get total no of rows
$counter = 0;
while($arrResult = $objAchQry->fetch()) {
//Do something
$counter ++;
//I need to do something here if its the last record like
if($counter == $total_records ) // this iteration will be the last one.
//do something
}
Related
In my laravel project I am inserting multiple records at time with modelname::insert method. Now I want to get last inserted id of it.I read somewhere when you insert multiple records with single insert method and try to get the last_record_id it will gives you the first id of the last inserted query bunch. But my first question is how to get last record id with following code .If I am able to get first id of the bunch .I ll make other ids for other record by my own using incremental variable.
Code to insert multiple record
if(!empty($req->contract_name) && count($req->contract_name)>0)
{
for($i=0; $i<count($req->contract_name); $i++)
{
$contract_arr[$i]['client_id'] = $this->id;
$contract_arr[$i]['contract_name'] = $req->contract_name[$i];
$contract_arr[$i]['contract_code'] = $req->contract_code[$i];
$contract_arr[$i]['contract_type'] = $req->contract_type[$i];
$contract_arr[$i]['contract_ext_period'] = $req->contract_ext_period[$i];
$contract_arr[$i]['contract_email'] = $req->contract_email[$i];
$contract_arr[$i]['created_at'] = \Carbon\Carbon::now();
$contract_arr[$i]['updated_at'] = \Carbon\Carbon::now();
$contract_arr[$i]['created_by'] = Auth::user()->id;
$contract_arr[$i]['updated_by'] = Auth::user()->id;
if($req->startdate[$i] != ''){
$contract_arr[$i]['startdate'] = date('Y-m-d',strtotime($req->startdate[$i]));
}
if($req->enddate[$i] != ''){
$contract_arr[$i]['enddate'] = date('Y-m-d',strtotime($req->enddate[$i]));
}
}
if(!empty($contract_arr)){
Contract::insert($contract_arr);
}
}
You should be able to call it like this
$lastId = Contract::insert($contract_arr)->lastInsertId();
If i see right, you're using a Model. Direct inserting only shows an success boolean. Try this instead:
Contract::create($contract_arr)->getKey()
I'm making a game in AS3.
I was wondering if it's possible to count how many times a function is called and do something when it has been called 5 times for exemple. (and then it's restarting to count at 0).
If we take an exemple, what would it be ?
Somethink like :
movieClip.addEventListener(MouseEvent.CLICK, functionExemple, false, 0, true);
function functionExemple(e:MouseEvent):void{
//do something;
count 1;
if (count = 5){
doThat();
count = 0;
}
So the function doThat would be called every 5 times.
I know the code is wrong. It's just in order to explain as good as possible what I meant.
Thank you for your help,
There are some errors in your example.
var count:int=0; //variable declaration
function functionExemple(e:MouseEvent):void{
//do something;
count++;//<=>count 1;
if (count == 5){//<=>if (count = 5){
doThat();
count = 0;
}
}
My initial guess would be to set a global variable that acts as a counter then when the function is called - increment its value. When value hits 5 take action. I would also guess using some form of "getter" to get the counter value would also help. This is my initial stab at it.
I need a page that displays records from a database, sorted by their jobs. So the database holds different kind of persons with different jobs. For example, on the page "teacher" I just want to display all the teachers, not the other persons. I want to have 3 persons on a page and a button "previous" and "next" beneath it. If an user clicks the next-button I want the next 3 records to be shown. When the user reaches the last records, I need the next-button to disappear. Same goes for "previous".
What I have so far:
This piece of code creates a value named startrow.
if (!isset($_GET['startrow']) or !is_numeric($_GET['startrow'])) {
//give the value of the starting row 0 because nothing was found in URL
$startrow = 0;
//otherwise take the value from the URL
} else {
$startrow = (int)$_GET['startrow'];
}
The query I have:
$sql = mysql_query("SELECT * FROM $tbl_name WHERE jobs='teacher' LIMIT $startrow, 3")or
die(mysql_error());
$sql2 = "SELECT COUNT(*) AS TotalJobs FROM $tbl_name WHERE jobs='teacher'";
$result_count = mysql_query($sql2);
$count = mysql_fetch_array($result_count);
I created the $count for the if / else function in the next part (the part that doesn't seem to work the way I want it to):
if ($startrow < $count )
echo 'Next';
$prev = $startrow - 3;
//only print a "Previous" link if a "Next" was clicked
if ($prev >= 0)
echo 'Previous';
So the previous-button seems to work the way it should. The next doesn't. I've created the
if ($startrow < $count)
so basicly, if the value of startrow is smaller than the total number of records, it puts a next-button. But if I test this, it displays the next-button anyhow, no matter the value of startrow.
What am I missing here?
mysql_fetch_array returns an array containing the count, not the value itself. Use $count['TotalJobs'] instead.
Also, you shouldn't use the mysql extension anymore, instead use PDO or MySQLi.
Edit
You can change:
$count = mysql_fetch_array($result_count);
to
$countArr = mysql_fetch_array($result_count);
$count = $countArr['TotalJobs'];
What I am trying to do is: (programmatically)
Update status where id is something, if no rows where updated, give error: we cannot find the record with id something, otherwise give message success.
Here I am using mysql_affected_rows() to know if a row was updated or not, but it always return 1, so the user gets a success message, even though there was no row updated.
Can anyone tell me what could it be?
Here's the code:
function update_sql($sql) {
$this->last_query = $sql;
$r = mysql_query($sql);
if (!$r) {
$this->last_error = mysql_error();
return false;
}
$rows = mysql_affected_rows();
if ($rows == 0) return true; // no rows were updated
else return $rows; }
This code returns 1.
That is because true will print out as "1" if you use echo. For debugging try using var_dump(), or let your function return 0 (which seems to me, in this case, the better option).
One little note; I think you should try to make your code a bit more readable (if the code in your question has the same layout as the code in your file). Try to indent code blocks, use separate lines for closing curly brackets, etc...
This is just a guess...
Maybe your function works as excepted? Maybe this piece of code if ($rows == 0) return true; works fine, and returns true but you treat that value as integer (boolean true can be displayed as 1)? Do: var_dump(uddated_sql('YOUR QUERY')) and check whether it returns boolean true or integer 1 value.
I wrote these lines:
foreach (var catId in CatIds)
{
AdCategory.AdId = LastAd.AdID;
AdCategory.CategoryId = catId;
EngineDB.Ad_Categories.InsertOnSubmit(AdCategory);
EngineDB.SubmitChanges();
}
and CatIds is an Integer Array.
this command inserts first element correctly but next loop causes this exception:
"Cannot add an entity that already exists."
How can I fix it. please help me as soon as posible!
as Jimmie said you need to create a new AdCategory in the loop. You also probably don't want to call SubmitChanges every time as well, this call uses a transaction to make sure all the items are added at once, or none at all.
Try something like:
foreach (var catId in CatIds)
{
var AdCategory = new AdCategory()
{
AdId = LastAd.AdID,
CategoryId = catId
}
EngineDB.Ad_Categories.InsertOnSubmit(AdCategory);
}
EngineDB.SubmitChanges();
You need to create a new AdCategory in the loop. Otherwise, as the error states, you are tyring to insert the same object again and again.
You should also move
EngineDB.SubmitChanges();
outside of the loop so you only make 1 call to the database.