I have a community site, where people can put up pages, and the url generates from their name. e.g. My Business, becomes my-business. I want to create a way, that if there is another My Business, it will check and make the url my-business-2, my-business-3, etc.
function check_url($url) {
$qry = mysqli_query($this->con, "SELECT * FROM businesses WHERE url LIKE '$url%'");
if(mysqli_num_rows($qry)>0) {
$slugs = array();
while($row = mysqli_fetch_array($qry)) $slugs[] = $row['url'];
if(in_array($url, $slugs)) {
$max = 1;
while(in_array(($url . '-' . ++$max ), $slugs)) $url .= '-' . $max;
}
}
return $url;
}
This is my function, but this still wont work, as if there is a business called My Bus, it will make it my-bus-2, when it would have been unique at my-bus. I have experimented with other functions too, but this one is the closest I got. Can anyone tell me one that works perfectly?
So form my understanding, you are trying to avoid inserting/generating duplicate URL. Output will be something like this -
www.example.com/my-business
www.example.com/my-business-1
www.example.com/my-business-2
www.example.com/my-business-3
...
Try using this function -
function check_url($base_url, $new_url='', $num=0) {
if($new_url == '') {
$new_url = $base_url;
}
$qry = mysqli_query($this->con, "SELECT * FROM businesses WHERE url = '$new_url'");
if(mysqli_num_rows($qry) > 0) {
while($row = mysqli_fetch_array($qry)) {
$num++;
check_url($base_url, $base_url . '-' . $num, $num);
}
}
return $url;
}
Basically, this function will check the database until it finds a valid URL. Each time it will increment the number and recursively call the same function to generate new/valid URL.
Simple and basic!
#SpritsDracula has working code, but his function will query your database each time it executes. That being said, the recursion is a nice concept. Here is a piece of code that will save your the multiple database calls.
function check_url($url) {
$qry = mysqli_query($this->con, "SELECT * FROM businesses WHERE url LIKE '$url%'");
if(mysqli_num_rows($qry)>0) {
$baseUrl = $url;
$slugs = [];
while($row = mysqli_fetch_array($qry)) $slugs[] = $row['url'];
$max = 1;
while(in_array($url, $slugs)) {
$url = $baseUrl . "-" . $max++;
}
}
return $url;
}
Related
I have an IVR that plays some audios for the user and then I need to redirect to another php file. The strange thing is that this redirect does not work.
NOTE 1: the redirect that does not work is the last one ($response->redirect("./chooseLicense.php?rs=$rs"))
NOTE 2: if I put it in if(!is_object($rs)) it works perfectly.
Can anyone tell me why this happens?
Snippet of my code:
$rs = json_decode(Curl::post(baseUrl . "users/auth/", $cpfOrCnpj, $password));
// logText('rs in login', $rs);
if(!is_object($rs)) {
$gather->play("https://digital-lock-api.azurewebsites.net/ura-hmg/assets/audios/licenseNotFound.mp3");
}
if($rs->licenses === []) {
$gather->play("https://digital-lock-api.azurewebsites.net/ura-hmg/assets/audios/licenseNotFound.mp3");
}
if(count($rs->licenses) == 1) {
$licenseId = $rs->licenses[0]->id;
$isBlocked = $rs->licenses[0]->blocked;
$token = $rs->auth->token;
$response->redirect("./waitForFlip.php?licenseId=$licenseId&isBlocked=$isBlocked&token=$token");
}
if(count($rs->licenses) > 1) {
$count = 0;
foreach($rs->licenses as $license) {
$count++;
$gather->play("https://digital-lock-api.azurewebsites.net/ura-hmg/assets/audios/chooseLicense$count.mp3");
$gather->play($license->nicknameAudioUrl);
}
$rs = json_encode($rs);
logText("rs encode", $rs);
$response->redirect("./chooseLicense.php?rs=$rs");
}
I am new to codeigniter and working on a project where I need to add search filters on a page. The way its been setup under applications/core there is a MY_Model.php file and here it the get_result function it.
function get_result() {
$this->db->from($this->tableName . ' ' . $this->alias);
$this->db->select($this->selectFields, FALSE);
for($j=0;$j<count($this->arrJoins);$j++){
$this->db->join($this->arrJoins[$j][0], $this->arrJoins[$j][1], $this->arrJoins[$j][2]);
}
$this->db->like($this->arrLike);
$this->db->or_like($this->arrOrLike);
if(isset($this->custLikeStr) && count($this->custLikeStr) > 0){
$this->db->where($this->custLikeStr);
}
$this->db->where($this->arrWhere);
$this->db->order_by($this->sortBy, $this->sortOrder);
$query = $this->db->get()->result();
//echo '<br>'.$this->db->last_query();
return $query;
}
There is a get_where function to build all where clauses
function get_where() {
foreach($this->arrWhereInputs as $arrWhereInput) {
if(isset($this->$arrWhereInput) && $this->$arrWhereInput != ''){
$this->arrWhere[$this->fieldAlias[$arrWhereInput].'.'.$arrWhereInput] = trim($this->$arrWhereInput);
}
}
return $this->arrWhere;
}
And in the model file for the application so under application/models here is there is a select function we need to call to get results.
function select(){
/* for search list */
$this->arrLikeInputs = array('stock_title', 'stock_id', 'price_band', );
$this->arrWhereInputs = array();
$this->arrWhere = array();
if ($this->input->post('record_per_page') != '') {
$records_per_page = $this->input->post('record_per_page');
} else {
$records_per_page = ROWS_PER_PAGE;
}
if (!(isset($this->record_per_page) && $this->record_per_page != '')) {
$this->record_per_page = ROWS_PER_PAGE;
}
$this->arrLike = $this->get_like();
$this->arrWhere = $this->get_where();
$this->arrWhere['SC.isDeleted'] = 0;
/* for search list */
if ($this->countQuery == 1) {
$this->db->from($this->tableName . ' ' . $this->alias);
$this->countSelectFields = 'COUNT(SC.stock_id) as cnt';
$result['count'] = $this->get_count();
}
$result['resultarr'] = $this->get_result();
$result['record_per_page'] = $records_per_page;
return $result;
}
Now I want to add where in to my query and I have tried a few ways but it just does not work.
I am getting confused on to where I am going wrong on such a simple thing.
So I have added a get_wherein function.
function get_wherein() {
foreach($this->arrWhereInInputs as $arrWhereInInput) {
if(isset($this->$arrWhereInInput) && $this->$arrWhereInInput != ''){
$this->arrWhereIn[$this->fieldAlias[$arrWhereInInput].'.'.$arrWhereInInput] = trim($this->$arrWhereInInput);
}
}
return $this->arrWhereIn;
}
So I added $this->arrWhereIn['Field'] = $arr which does not work and also tried to to call $this->db->where_in('field',$array) in the select function directly that does not work either. In both the cases it gets ignored and the query is build without the "and where in".
Where am I going wrong and how to build this query?
ORGINAL QUERY - Updated Query Below
I am in the process of building a custom application in PHP. I know there have been many questions asked about Routing etc. on here and I have spent many of hours reading them all. This is how I got my routing elements to work in the first place. However 1 thing I cant get to fit into my project is peoples suggestions on how to route URLs based on a database entry.
The application itself is working perfectly fine and I already have some URL Routing in place which works exactly how I want it. The issue I have is when I add new products into my database I have a trigger that generates a SEO Friendly URL and stores it in a field in the database.
All the product URLs are structured in the same way.
/North/productdetails/Productname
/South/productdetails/Productname
/NorthEast/productdetails/Productname
etc.
What I am looking to do is not have to manually write a new URL Route into the routes.php file every time a product is added.
this is my .htaccess
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
rewriteRule ^(.+)$ index.php?uri=$1 [QSA,L]
and my index.php file contains:
<?php
header("Cache-Control: no-cache");
include 'System/Config/route.php';
include 'System/Config/settings.php';
connect();
$route = new Route();
include 'System/Config/routeURL.php';
$route->add('/', 'Home');
$route->add('/results', 'Results');
$route->add('/special', 'Special');
$route->gogo();
?>
I need something like this to go in and catch every URL passed to it. It then needs to check the URL and send the relevant information to a page.
$route->add('/results/NorthEast/productdetails/<whateveryisstoredindatabse>', 'productURLS');
The class file that I use at the min to check it is this:
class productURLS
{
function Item($itemID)
{
$host = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
$itemID = '0';
if($host == host +<URLStored in database>) {
$itemID = <what ever id is in database>;
} else {
$itemID = '0';
$_POST['ShowProductDetails'] = $itemID;
}
public function __construct()
{
productURLS::Item($ItemID);
include 'pages/productdetails.php';
}
}
The class I wrote above is what I use to deter the current URLS onsite, I have modified it to identify where I need help on.
This is the route controller:
class Route
{
private $_uri = array();
private $_method = array();
/**
* Builds a collection of internal URL's to look for
* #param type $uri
*/
public function add($uri, $method = null)
{
$this->_uri[] = '/' . trim($uri, '/');
if ($method != null) {
$this->_method[] = $method;
}
}
/**
* Triggers from start page
*/
public function gogo()
{
$uriGetParam = isset($_GET['uri']) ? '/' . $_GET['uri'] : '/';
foreach ($this->_uri as $key => $value)
{
if (preg_match("#^$value$#", $uriGetParam))
{
$usemethod = $this->_method[$key];
new $usemethod();
}
}
}
}
Does anyone have any suggestions in what I can do with what I have? or will it require a complete rewrite of the routing?
Regards
UPDATED
I have left the original query in as well as this one. For anyone landing on this page I have now been able to obtain data from the database and use it to generate a route in my routing controller dynamically. This is how I did it.
my index.php file now looks like this:
<?php
header("Cache-Control: no-cache");
include 'System/Config/route.php';
include 'System/Config/settings.php';
connect();
$route = new Route();
include 'System/Config/routeURL.php';
$q="SELECT `itemID`,`SEOFriendlyURL` FROM `Products`";
$r=mysql_query($q);
$numrows = mysql_num_rows($r);
if($numrows==0)
{
// Does nothing as the database is empty - Not really needed but good just in case
}
// Dynamic Routing Elements
while($row = mysql_fetch_array($r))
{
$route->add("/results" . $row['SEOFriendlyURL'] ."", 'productURLS');
}
//Static Routing Elements
$route->add('/', 'Home');
$route->add('/results', 'Results');
$route->add('/special', 'Special');
$route->gogo();
?>
This has worked perfectly, When ever one of these URLS is called it diverts to the right page. The only thing I'm having issues with now is passing the relevant ID's via $_post
This is what I ended up with but its not working.
class productURLS
{
function clubs($ItemID)
{
$q="SELECT `itemID`,`SEOFriendlyURL` FROM `products`";
$r=mysql_query($q);
$numrows = mysql_num_rows($r);
if($numrows==0)
{
$ItemID = '0';
}
while($row = mysql_fetch_array($r))
{
$host = $_SERVER['REQUEST_URI'];
$ClubID = '0';
if($host == "/newtest/results" . $row['SEOFriendlyURL'] ."") {
$ClubID = "'" . $row['itemID'] ."'";
} else {
$itemID = '0';
}
}
$_POST['ShowClubDetails'] = $itemID;
}
public function __construct()
{
productURLS::clubs($itemID);
include 'pages/productdetails.php';
}
}
However this doesn't work. Because the query etc. is in the index page is it really needed again here? and is it better to get the query to store the ID in a variable and use that in the function instead?
Regards
I have managed to get this fully working. Here is what I did. May be of some use to someone else.
Index.php
include 'System/Config/routeURL.php';
$q="SELECT `ItemID`,`SEOFriendlyURL` FROM `Products`";
$r=mysql_query($q);
$numrows = mysql_num_rows($r);
if($numrows==0)
{
echo "There's nothing here!";
}
// Add's all SEOFriendly URL's in table into route file (Dynamic)
while($row = mysql_fetch_array($r))
{
$route->add("/results" . $row['SEOFriendlyURL'] ."", 'ProductURLS');
}
routeURL.php
class ProductURLS
{
public function __construct()
{
$host = $_SERVER['REQUEST_URI'];
$host = ltrim ($host, '/results');
$host = "/$host";
$q="SELECT `ItemID`,`SEOFriendlyURL` FROM `Products` WHERE `SEOFriendlyURL` = '$host'";
$r=mysql_query($q);
if($r) {
$row = mysql_fetch_assoc($r);
$ItemID = $row['ItemID'];
} else {
$ItemID = '0';
}
$_POST['ShowClubDetails'] = $ItemID;
//echo "Whole query: $ItemID"; // This is to make sure the ProductID is being passed.
include 'pages/ProductDetails.php';
}
}
I downloaded AlegroCart from https://code.google.com/p/alegrocart/ and I am trying to figure out which database framework is being used.
One of the methods being used is getRow:
$result = $this->database->getRow("select order_reference, total from order_google where order_number = '" . $orderNumber . "'");
but there is also a call to getRows:
$result = $this->database->getRows("select * from zone_to_geo_zone where geo_zone_id = '" ...
Does any one know which framework allows these two calls? I see that Pear framework has getRow but not getRows.
thanks
It's not really a framework but it seems like it's just some piece of (easy) code directly written by alegrocart :
function getRow($sql) {
$this->query($sql);
$row = mysql_fetch_assoc($this->result);
mysql_free_result($this->result);
return $row;
}
function getRows($sql) {
if (func_num_args()) { $this->query(implode(func_get_args(), ', ')); }
else { $this->query($sql); }
$rows = array();
while (is_resource($this->result) && $row = mysql_fetch_assoc($this->result)) { $rows[] = $row; }
if(is_resource($this->result)){
mysql_free_result($this->result);
}
return $rows;
}
https://code.google.com/p/alegrocart/source/browse/trunk/AlegroCart/upload/library/database/database.php
One of my project use solr1.2 and when i use "sort by score" in search function it's not working.I don't know why?
Can any one explain this.I am totally confuse.
my controller where i do :
protected function globalSearch($searchTerm, $productFilter = array())
{
$solrService = $this->get('syd.solr_service');
$solrQuery = new SolrQuery('*:*');
$solrQuery->addField('id')
->addField('first_product_slug')
->addField('first_product_name')
->addField('name')
->addField('slug')
->addField('thumbnail_path')
->addField('product_slug')
->addField('design_category_id')
->addSortField('score', SolrQuery::ORDER_DESC);
$solrQuery->set("group", "true");
$solrQuery->set("group.field", "first_product_id");
$solrQuery->set("group.limit", 4);
if($searchTerm){
$filterQueries = array();
$searchTerms = explode(' ',$searchTerm);
$searchTerms[] = $searchTerm;
$searchTerm = '("' . implode('" OR "', $searchTerms) . '")';
$filterQuery = sprintf(self::SEARCH_STRING, $searchTerm);
$solrQuery->addFilterQuery($filterQuery);
}
if (!empty($productFilter))
{
$productFiltersArr = array();
$productFilterQry = '';
foreach ($productFilter as $productFilterValue )
{
$productFiltersArr[] = 'first_product_slug:' . $productFilterValue;
}
$productFilterQry = implode(' OR ', $productFiltersArr);
$solrQuery->addFilterQuery($productFilterQry);
}
$solrQuery->setRows(1000);
try {
$solrObject = $solrService->query(
'SydPrintBundle:DesignTemplate',
$solrQuery,
SolrService::WRITER_FORMAT_SOLR_OBJECT
);
$templates = $solrObject->offsetGet('grouped')->offsetGet('first_product_id')->offsetGet('groups');
}
catch (\Exception $e) {
$templates = array();
}
if (!$templates) {
if (!empty($searchTerm)) {
$this->setFlash('catalog-message', 'No results found for your search.');
}
return array();
}
if (!$searchTerm) {
if (!empty($searchTerm)) {
$this->setFlash('catalog-message', 'No results found for your search.');
}
return array();
}
return $templates;
}
When you say when i use "sort by score" in search function it's not working I assume you are telling that the results are not sorted by score.
This is because your main query is *:* and you are adding your search terms via a filter query, which won't influence the score. See https://wiki.apache.org/solr/CommonQueryParameters#fq where it says
This parameter can be used to specify a query that can be used to restrict the super set of documents that can be returned, without influencing score.
So if you make the search term filter query as your main query, then you should see results sorted by score.
Update:
Instead of
$solrQuery = new SolrQuery('*:*');
use
$solrQuery = new SolrQuery();
and instead of
$solrQuery->addFilterQuery($filterQuery);
use
$solrQuery->setQuery($filterQuery);