Possibly missing something very simple in this PHP foreach loop - sql

This question is an extension for this question.
Basically the script compares two arrays and outputs the difference (what to show to the user).
$urlsToShow = array_diff($siteUrls, $seenUrls);
if (!empty($urlsToShow)) {
// Echo the url to show for the iframe within browse.php and add an entry to the database that the user has seen this site
foreach ($urlsToShow as $urlToShow) {
echo $urlToShow;
$entry = "INSERT INTO views VALUES ('', '$currentUsername', '$urlToShow')";
mysqli_query($con, $entry);
break;
}
}
The problem is that I get two entries into the database with one iteration? The first site from the $urlsToShow array is displayed (echoed into the iframe) and gets added to the database along with the next site from the same array. But the user will never see the next site.
Am I using break incorrectly?

It is possible that using break; will not be in your best interest. I suggest using continue;.

Related

Do I need to implement full text search in this case? alternatives?

I have two columns in a table first_name and last_name(PostgreSQL).
In front end, I have an input to allow users to search for people. It is an auto-complete field that calls a web service for searching people by first and/or last names.
Currently, I have made a query (using my query builder):
$searches = preg_split('/\s+/', $search);
if (!empty($search)) {
$orX = $query->expr()->orX();
$i = 0;
foreach ($searches as $value) {
$orX->add($query->expr()->eq('c.firstName', ':name'.$i));
$orX->add($query->expr()->eq('c.lastName', ':name'.$i));
$query->setParameter('name'.$i, $value);
$i++;
}
$query->andWhere($orX);
}
But this query is not as precise as it is required, it uses OR for every word so if I am looking for "Rasmus Lerdorf" it also gives me "Rasmus Adams" and "Adel Lerdorf". It works only if I enter a single word ("Rasmus" for example), in this case it gives me all people with "Rasmus" as first_name or last_name.
I read about MATCH AGAINST but I am using PostgreSQL. I also heard about Full text search feature in PostgreSQL as the equivalent of MATCH AGAINST, but I am wondering if implementing a full text search would be an overkill for such an objective (especially that the maximum number of words in both columns wouldn't exceed 4).
I ask you please your advices, your usual help is always appreciated. Thanks
You don't need fulltext search.
Just add the different search terms with AND instead of OR:
$i = 0;
foreach ($searches as $value) {
$orX = $query->expr()->orX();
$orX->add($query->expr()->eq('c.firstName', ':name'.$i));
$orX->add($query->expr()->eq('c.lastName', ':name'.$i));
$query->setParameter('name'.$i, $value);
$i++;
$query->andWhere($orX);
}
I would also suggest using LIKE instead of an equality comparison (add '%' to the start and end of the users search term), and probably also make everything case insensitive by adding $query->expr()->lower() appropriately.

can there be a tooltip with data from the database

I need to know can there be a tooltip populated with data from database to be displayed in the tooltip.
something like the tooltip should contain
name stauts
abc active
xyz active
pqr active
name and status are retrived from db
I need this tooltip onmouseover, am using CJSON decoded to render the content
i did go google but hardly did find that i would throughly understand and implement.
can anyone out there has any ideas for what am looking.
There is a extension named yii-bootstrap, which described clearly here.
For using tooltip easily in this extension, just look here.
I use cluetip for this. Its not related to Yii but will give you some idea :
JS
function renderInfoTips(opts){
var elements=$('#'+opts.form).get(0).elements;
for(i=0; i<opts.tips.length;i++){
$(elements[opts.tips[i].field]).parent().prepend(opts.tips[i].tip);
}
var clue_opts={arrows:true,splitTitle: '|',closePosition: 'title',sticky:true,dropShadow:false,mouseOutClose:true,
onShow:function(ct, ci){
if(!$.browser.webkit) $(ct).css('top',$(ct).position().top- 30+'px');
}
}
$('#'+opts.form).find(".infotip").cluetip(clue_opts);
}
PHP
function setInfoTipsJavascript($form_id,infotips){
if (count($this->infotips) <1 ) return '';
//get all tip names
$names_csv=join(',',array_keys(infotips));
//get tips details from db
$query="select name, description from infotips where FIND_IN_SET(name ,'$names_csv')";
//run the query, in Yii you have to use InfoTipsModel , I have skipped that portion
//$infotipS , lets say this is query object
$tips=array();
while($tip=$infotipS->Assoc()){
$this->infotips[$tip['name']]['tip']="<a href='javascript:void(0)' class='infotip' title='|{$tip['description']}'> </a>";
$tips[]=$this->infotips[$tip['name']];
}
$tips=json_encode($tips);
$script="\nrenderInfoTips({\"form\":'{$form_id}', \"tips\":{$tips}});\n\n";
echo $script;
}
I am sharing this hoping this will give u some idea. Its obvious you have to : create infotips table, a model for that, and create a widget etc to fetch infotips related to your form fields . As someone suggested, if you are using Bootstrap, you have better way to do that.

Check if an existing value is in a database

I was wondering how I would go about checking to see if a table contains a value in a certain column.
I need to check if the column 'e-mail' contains an e-mail someone is trying to register with, and if something exists, do nothing, however, if nothing exists, insert the data into the database.
All I need to do is check if the e-mail column contains the value the user is registering with.
I'm using the RedBeanPHP ORM, I can do this without using it but I need to use that for program guidelines.
I've tried finding them but if they don't exist it returns an error within the redbean PHP file. Here's the error:Fatal error: Call to a member function find() on a non-object in /home/aeterna/www/user/rb.php on line 2433
Here's the code that I'm using when trying this:
function searchDatabase($email) {
return R::findOne('users', 'email LIKE "' . $email . '"');
}
My approach on the function would be
function searchDatabase($email) {
$data = array('email' => $email);
$user = R::findOne('users', 'email LIKE :email, $data);
if (!empty($user)) {
// do stuff here
} // end if
} // end function
It's a bit more clean and in your function
Seems like you are not connected to a database.
Have you done R::setup() before R::find()?
RedBeanPHP raises this error if it can't find the R::$redbean instance, the facade static functions just route calls to the $redbean object (to hide all object oriented fuzzyness for people who dont like that sort of thing).
However you need to bootstrap the facade using R::setup(). Normally you can start using RB with just two lines:
require('rb.php'); //cant make this any simpler :(
R::setup(); //this could be done in rb.php but people would not like that ;)
//and then go...
R::find( ... );
I recommend to check whether the $redbean object is available or whether for some reason the code flow has skipped the R::setup() boostrap method.
Edited to account for your updated question:
According to the error message, the error is happening inside the function find() in rb.php on line 2433. I'm guessing that rb.php is the RedBean package.
Make sure you've included rb.php in your script and set up your database, according to the instructions in the RedBean Manual.
As a starting point, look at what it's trying to do on line 2433 in rb.php. It appears to be calling a method on an invalid object. Figure out where that object is being created and why it's invalid. Maybe the find function was supplied with bad parameters.
Feel free to update your question by pasting the entirety of the find() function in rb.php and please indicate which line is 2433. If the function is too lengthy, you can paste it on a site like pastebin.com and link to it from here.
Your error sounds like you haven't done R::setup() yet.
My approach to performing the check you want would be something like this:
$count = count(R::find('users', 'email LIKE :email', array(':email' => $email)));
if($count === 0)
{
$user = R::dispense('users');
$user->name = $name;
$user->email = $email;
$user->dob = $dob;
R::store($user);
}
I don't know if it is this basic or not, but with SQL (using PHP for variables), a query could look like
$lookup = 'customerID';
$result = mysql_fetch_array(mysql_query("SELECT columnName IN tableName WHERE id='".$lookup."' LIMIT 1"));
$exists = is_null($result['columnName'])?false:true;
If you're just trying to find a single value in a database, you should always limit your result to 1, that way, if it is found in the first record, your query will stop.
Hope this helps

How can I see CakePHP's SQL dump in the controller?

Is there a way that one can cause CakePHP to dump its SQL log on demand? I'd like to execute code up until a point in my controller and see what SQL has been run.
Try this:
$log = $this->Model->getDataSource()->getLog(false, false);
debug($log);
http://api.cakephp.org/2.3/class-Model.html#_getDataSource
You will have to do this for each datasource if you have more than one though.
There are four ways to show queries:
This will show the last query executed of user model:
debug($this->User->lastQuery());
This will show all executed query of user model:
$log = $this->User->getDataSource()->getLog(false, false);
debug($log);
This will show a log of all queries:
$db =& ConnectionManager::getDataSource('default');
$db->showLog();
If you want to show all queries log all over the application you can use in view/element/filename.ctp.
<?php echo $this->element('sql_dump'); ?>
If you're using CakePHP 1.3, you can put this in your views to output the SQL:
<?php echo $this->element('sql_dump'); ?>
So you could create a view called 'sql', containing only the line above, and then call this in your controller whenever you want to see it:
$this->render('sql');
(Also remember to set your debug level to at least 2 in app/config/core.php)
Source
for cakephp 2.0
Write this function in AppModel.php
function getLastQuery()
{
$dbo = $this->getDatasource();
$logs = $dbo->getLog();
$lastLog = end($logs['log']);
return $lastLog['query'];
}
To use this in Controller
Write : echo $this->YourModelName->getLastQuery();
It is greatly frustrating that CakePHP does not have a $this->Model->lastQuery();. Here are two solutions including a modified version of Handsofaten's:
1. Create a Last Query Function
To print the last query run, in your /app_model.php file add:
function lastQuery(){
$dbo = $this->getDatasource();
$logs = $dbo->_queriesLog;
// return the first element of the last array (i.e. the last query)
return current(end($logs));
}
Then to print output you can run:
debug($this->lastQuery()); // in model
OR
debug($this->Model->lastQuery()); // in controller
2. Render the SQL View (Not avail within model)
To print out all queries run in a given page request, in your controller (or component, etc) run:
$this->render('sql');
It will likely throw a missing view error, but this is better than no access to recent queries!
(As Handsofaten said, there is the /elements/sql_dump.ctp in cake/libs/view/elements/, but I was able to do the above without creating the sql.ctp view. Can anyone explain that?)
In CakePHP 1.2 ..
$db =& ConnectionManager::getDataSource('default');
$db->showLog();
What worked finally for me and also compatible with 2.0 is to add in my layout (or in model)
<?php echo $this->element('sql_dump');?>
It is also depending on debug variable setted into Config/core.php
Plugin DebugKit for cake will do the job as well. https://github.com/cakephp/debug_kit
If you are interested in some specific part of code, you can clear first the log, and then display only queries that happen after that point.
Also note that 'Model' below, is the actual class name, like User, Page etc.
//clear log (boolean $clear = true)
$this->Model->getDataSource()->getLog(false, true);
...
...
...
...
//Show log so far
$log = $this->Model->getDataSource()->getLog(false, false);
debug($log);
exit;

jqGrid/NHibernate/SQL: navigate to selected record

I use jqGrid to display data which is retrieved using NHibernate. jqGrid does paging for me, I just tell NHibernate to get "count" rows starting from "n".
Also, I would like to highlight specific record. For example, in list of employees I'd like a specific employee (id) to be shown and pre-selected in table.
The problem is that this employee may be on non-current page. E.g. I display 20 rows from 0, but "highlighted" employee is #25 and is on second page.
It is possible to pass initial page to jqGrid, so, if I somehow use NHibernate to find what page the "highlighted" employee is on, it will just navigate to that page and then I'll use .setSelection(id) method of jqGrid.
So, the problem is narrowed down to this one: given specific search query like the one below, how do I tell NHibernate to calculate the page where the "highlighted" employee is?
A sample query (simplified):
var query = Session.CreateCriteria<T>();
foreach (var sr in request.SearchFields)
query = query.Add(Expression.Like(sr.Key, "%" + sr.Value + "%"));
query.SetFirstResult((request.Page - 1) * request.Rows)
query.SetMaxResults(request.Rows)
Here, I need to alter (calculate) request.Page so that it points to the page where request.SelectedId is.
Also, one interesting thing is, if sort order is not defined, will I get the same results when I run the search query twice? I'd say that SQL Server may optimize query because order is not defined... in which case I'll only get predictable result if I pull ALL query data once, and then will programmatically in C# slice the specified portion of query results - so that no second query occur. But it will be much slower, of course.
Or, is there another way?
Pretty sure you'd have to figure out the page with another query. This would surely require you to define the column to order by. You'll need to get the order by and restriction working together to count the rows before that particular id. Once you have the number of rows before your id, you can figure what page you need to select and perform the usual paging query.
OK, so currently I do this:
var iquery = GetPagedCriteria<T>(request, true)
.SetProjection(Projections.Property("Id"));
var ids = iquery.List<Guid>();
var index = ids.IndexOf(new Guid(request.SelectedId));
if (index >= 0)
request.Page = index / request.Rows + 1;
and in jqGrid setup options
url: "${Url.Href<MyController>(c => c.JsonIndex(null))}?_SelectedId=${Id}",
// remove _SelectedId from url once loaded because we only need to find its page once
gridComplete: function() {
$("#grid").setGridParam({url: "${Url.Href<MyController>(c => c.JsonIndex(null))}"});
},
loadComplete: function() {
$("#grid").setSelection("${Id}");
}
That is, in request I lookup for index of id and set page if found (jqGrid even understands to display the appropriate page number in the pager because I return the page number to in in json data). In grid setup, I setup url to include the lookup id first, but after grid is loaded I remove it from url so that prev/next buttons work. However I always try to highlight the selected id in the grid.
And of course I always use sorting or the method won't work.
One problem still exists is that I pull all ids from db which is a bit of performance hit. If someone can tell how to find index of the id in the filtered/sorted query I'd accept the answer (since that's the real problem); if no then I'll accept my own answer ;-)
UPDATE: hm, if I sort by id initially I'll be able to use the technique like "SELECT COUNT(*) ... WHERE id < selectedid". This will eliminate the "pull ids" problem... but I'd like to sort by name initially, anyway.
UPDATE: after implemented, I've found a neat side-effect of this technique... when sorting, the active/selected item is preserved ;-) This works if _SelectedId is reset only when page is changed, not when grid is loaded.
UPDATE: here's sources that include the above technique: http://sprokhorenko.blogspot.com/2010/01/jqgrid-mvc-new-version-sources.html