How to request MYSQL elements instead of using Array in PHP - php

I made language php code which working fine. I request the translations from different like en.php, de.php.
In en.php i have one array:
$language = Array('homepage' => 'Site Home','contact' => 'Contact Us');
I use $_SESSION for get the language en, de, hu and the others. I get the language files with this code:
$sql = mysql_query("SELECT * FROM languages ORDER BY langID");
$count = mysql_num_rows($sql);
if ($count) {
while ($ds = mysql_fetch_array($sql)) {
switch ($_SESSION['language']) {
case $ds['tag']:
include_once('language/' . $ds['tag'] . '.php');
break;
default:
include_once('language/en.php');
break;
}
}
}
But I would like to change array for mysql database. In my DB i have a table with:
translatesID
tag(its now the 'en' or can be other like 'de')
key(what i want to be the array like 'homepage')
value(which would be the 'Site Home')
In index.php I get the 'Site Home' with the following php code:
<?php echo $language['homepage']; ?>
My question is which Mysql request or PHP code can solve my request?

Problem solved with this code:
$language = array();
$sql = mysql_query("SELECT * FROM translates WHERE '" . $_SESSION['language'] . "' = tag");
while($row = mysql_fetch_array($sql)) {
$language[$row['key']] = $row['value'];
}

Related

ext js store/model example .net -converting php/mysql to .netwebservier/sql

Afternoon all,
I am working through a tutorial from MASTERING EXT JS and am stuck on retrieving data from db.
The book has been using examples using PHP and MYSQL... which I do not know. I use a .net web server and SQL, so I'm trying to convert this example from the tutorial, to how I would do it on my .net webserver.
the result in JSON format should be something like this
{
"data"[
{
"id":1",
"text" : "menu1",
"items": [
{"id": 2",
"text: "submenu2
},
{
"id":"3",
"text":"submenu3"
}
the php code they give me is this
php file 1
$permissions = retrievePermissions($userName); $modules =
retrieveModules($permissions); $result = retrieveMenuOptions($modules,
$permissions);
php file 2
function retrievePermissions($userName){
require('../db/db.php');
$sqlQuery = "SELECT p.menu_id menuId FROM User u ";
$sqlQuery .= "INNER JOIN permissions p ON u.groups_id = p.groups_id ";
$sqlQuery .= "INNER JOIN menu m ON p.menu_id = m.id ";
$sqlQuery .= "WHERE u.username = '$userName' ";
$permissions = [];
if ($resultDb = $mysqli->query($sqlQuery)) {
while($user = $resultDb->fetch_assoc()) {
$permissions[] = $user['menuId'];
}
}
$resultDb->free();
$mysqli->close();
return $permissions; }
function retrieveModules($permissions){
require('../db/db.php');
$inClause = '(' . join(',',$permissions) . ')';
$sqlQuery = "SELECT id, text, iconCls FROM menu WHERE menu_id IS NULL AND id in $inClause";
$modules = [];
if ($resultDb = $mysqli->query($sqlQuery)) {
while($module = $resultDb->fetch_assoc()) {
$modules[] = $module;
}
}
$resultDb->free();
$mysqli->close();
return $modules; }
function retrieveMenuOptions($modules, $permissions){
require('../db/db.php');
$inClause = '(' . join(',',$permissions) . ')';
$result = [];
foreach ($modules as $module) {
$sqlQuery = "SELECT * FROM menu WHERE menu_id = '";
$sqlQuery .= $module['id'] ."' AND id in $inClause";
// check if have a child node
if ($resultDb = $mysqli->query($sqlQuery)) {
// determine number of rows result set
$count = $resultDb->num_rows;
if ($count > 0){
$module['items'] = array();
while ($item = $resultDb->fetch_assoc()) {
$module['items'][] = $item;
}
}
$result[] = $module;
}
}
$resultDb->close();
$mysqli->close();
return $result;
I'm trying to figure out how to return the same json format using my .net webservice/SQL instead of php/MySQL.
It seems like it does 3 separate functions. And the result array is used as a parameter for the next query.
The basics seem easy... like for retreivePermissions... it is a simple SELECT WHERE statement.
retrieveModules seems to be an INNER JOIN with the first results.
But the last one... retrieveMenuOptions, it pulls in both results as parameters, and It returns results.
That is what I don't understand... how can I pull the results from SQL in the same JSON result format.
Am I making sense?
I have an example that uses a .NET Web API controller. Not exactly a web service, but you'll get the idea. Check it out here: http://jorgeramon.me/2015/ext-js-grid-search-with-net-and-mysql-backend/

stopping duplicate urls in a form submission

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;
}

PHP URL Routing - Using Database Entries in Class

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';
}
}

PHP Search Script Enhancement

I have a website that has a built in search function. It allows the users to search for keywords from within the main page header. When a user searches any keyword, the result is always:
There are no results matching your query.
In order to find any item, the user must go to the advanced search options and enter the keyword in the search box, select the checkbox for "Search item title and description" and select "Both" from the drop down box for "Listed In".
I cannot figure out how to automatically set the main page search box to search each of these options.
Below is the code that I have for the search function. Any help would be GREATLY APPRECIATED:
<?php
session_start();
define ('IN_SITE', 1);
include_once ('includes/global.php');
include_once ('includes/class_formchecker.php');
include_once ('includes/class_custom_field.php');
include_once ('global_header.php');
$option = $db->rem_special_chars($_REQUEST['option']);
$option = (empty($option)) ? 'auction_search' : $option;
$template->set('option', $option);
$item_details = $db->rem_special_chars_array($_POST);
$template->set('item_details', $item_details);
$header_search_page = header5(GMSG_ADVANCED_SEARCH);
$template->set('header_search_page', $header_search_page);
if ($_REQUEST['search_empty'] == 1)
{
$template->set('no_results_message', '<p align="center" class="errormessage">' . MSG_NO_RESULTS_QUERY . '</p>');
}
(string) $search_options_menu = null;
$search_options_menu .= display_link(process_link('search', array('option' => 'auction_search')), MSG_AUCTION_SEARCH, (($option = 'auction_search') ? false : true)) . ' | ';
$search_options_menu .= display_link(process_link('search', array('option' => 'seller_search')), MSG_SELLER_SEARCH, (($option = 'seller_search') ? false : true)) . ' | ';
$search_options_menu .= display_link(process_link('search', array('option' => 'buyer_search')), MSG_BUYER_SEARCH, (($option = 'buyer_search') ? false : true));
if ($setts['enable_stores'])
$template->set('search_options_menu', $search_options_menu);
switch ($option)
{
case 'auction_search':
$search_options_title = MSG_AUCTION_SEARCH;
$custom_fld = new custom_field();
$custom_fld->new_table = false;
$custom_fld->field_colspan = 2;
$custom_fld->box_search = 1;
$custom_sections_table = $custom_fld->display_sections($item_details, 'auction', false, 1, 0);
$template->set('custom_sections_table', $custom_sections_table);
$tax = new tax();
$template->set('country_dropdown', $tax->countries_dropdown('country', $item_details['country'], null, '', true));
//$template->set('state_box', $tax->states_box('state', $item_details['state'], $item_details['country']));
break;
case 'seller_search':
$search_options_title = MSG_SELLER_SEARCH;
break;
case 'buyer_search':
$search_options_title = MSG_BUYER_SEARCH;
break;
case 'store_search':
$search_options_title = MSG_STORE_SEARCH;
break;
}
$template->set('search_options_title', $search_options_title);
$template_output .= $template->process('search.tpl.php');
include_once ('global_footer.php');
echo $template_output;
?>
This issue after doing research was the result in a standard setting for MySQL. Minimum search length had to be longer than 3 characters. A search length of 3 characters or less yielded no search results.

Call of unknown method '_compile_source'. Smarty 3

Hopefully someone can help me with this. I am using smarty within CMSMS and have something called a User Defined Tag running within my page. This contains the following code:
$db = cmsms()->GetDb();
$menu = $smarty->get_template_vars('page');
$user_id = $smarty->get_template_vars('userid');
if (!isset($user_id)) {
$user_id = -1;
}
// Getting menu items from DB
$query = 'SELECT * FROM '. cms_db_prefix() .'module_tools_options
WHERE active = 1 AND user_id = ? AND menu = ?
ORDER BY sort';
$dbresult = $db->Execute($query, array($user_id, $menu));
while ($dbresult && $row = $dbresult->FetchRow()) {
$smarty->_compile_source('preprocess template', $row['title'], $_compiled);
#ob_start();
$smarty->_eval('?>' . $_compiled);
$result = #ob_get_contents();
#ob_end_clean();
echo '<li id="menu_' . $row['option_id'] . '">' . $result . "</li>\n";
}
I have upgraded the CMSMS installation so it now runs smarty 3 and this has broken my page. I get the following error:
/lib/smarty/sysplugins/smarty_internal_templatebase.php: Call of unknown method '_compile_source'.
I guess the Compile Source method has been depreciated in Smarty 3. Can anyone point me in the right direction of its replacement or a method to get this working again?
Many Thanks
Replace:
$smarty->_compile_source('preprocess template', $row['title'], $_compiled);
#ob_start();
$smarty->_eval('?>' . $_compiled);
$result = #ob_get_contents();
#ob_end_clean();
With:
$result = $smarty->fetch('string:'.$row['title']);

Categories