08 November 2010

Check the group id of a user in Joomla

If you are doing your own custom Joomla component, somtimes it is very helpful to determine the user group of a user in order to perform necessary actions (for example, only admins can delete a record).

For doing this, we must get the group id. They are as follows:

Public : 0
Registered : 1
Special : 2

Users that have access to the backend fall under the Special group.

The following code will check the group id of the current user and display a message if user is not of 'Special' type.
$user = JFactory::getUser();
$userGID = $user->get('gid');
if ($userGID != 2)
{
   echo "You do not have the necessary permissions to perform this action.";
}

30 September 2010

Using 'NOT IN' in MySQL

MySQL (4th Edition)Suppose we have a table called USERS that has a primary key 'id' and another table SUBSCRIPTIONS with foreign key 'uid'.

If we want to remove all subscriptions (from the SUBSCRIPTIONS table) that does not correspond to any user, we can run this MySQL query:

DELETE FROM SUBSCRIPTIONS WHERE uid NOT IN (SELECT id from USERS)
What we are doing here is getting a list of all the ids from the USERS table and then deleting all rows from the SUBSCRIPTIONS table where the user id (uid) does not correspond to any id in the USERS table. Very simple.

Note: Throughout this blog, you will find many books that are for sale on Amazon. I recommend you get these books while learning web programming as they will help strengthening your skills.

20 August 2010

How to dynamycally remove an external Javascript or CSS file from a page

The key is to doing this is to traverse the DOM and then call the DOM's deleteChild() method.

We can identify the file to be deleted by using its filename or CSS class name. Here I am going to use its filename.

function deletejscssfile(filename, filetype){

var targetelement=(filetype=="js")? "script" : (filetype=="css")? "link" : "none" //determine element type to create nodelist from

var targetattr=(filetype=="js")? "src" : (filetype=="css")? "href" : "none" //determine corresponding attribute to test for

var allsuspects=document.getElementsByTagName(targetelement)

for (var i=allsuspects.length; i>=0; i--){ //search backwards within nodelist for matching elements to delete

if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(filename)!=-1)

allsuspects[i].parentNode.deleteChild(allsuspects[i]) //delete element by calling parentNode.deleteChild()

}

}

deletejscssfile("script_to_be_removed.js", "js") //delete all occurences of “script_to_be_removed.js” on page

deletejscssfile("script_to_be_removed.css", "css") //delete all occurences of “script_to_be_removed.css” on page

17 August 2010

Recommended Joomla books

I have come across these books during my career as a programmer and I can say, they are worth every penny. I highly recommend you buy them if you are into Joomla development.


Joomla! Start to Finish: How to Plan, Execute, and Maintain Your Web Site (Wrox Programmer to Programmer)Joomla! Start to Finish: How to Plan, Execute, and Maintain Your Web Site
$38.54











Joomla! 1.5: A User's Guide: Building a Successful Joomla! Powered Website (2nd Edition)Joomla! 1.5: A User's Guide: Building a Successful Joomla! Powered website
$29.69










Joomla! BibleJoomla! Bible
$29.69








Learning Joomla! 1.5 Extension DevelopmentLearning Joomla! 1.5 Extension Development
$34.08

22 April 2010

Joomla get current language

The following code might be useful to you if you want to get the current language in your custom component/module/plugin.

It will get the current language that is active on the website:

$lang =& JFactory::getLanguage();
echo "The current language is:". $lang->getName();

Reference : JFactory/getLanguage - Joomla! Documentation

If you are learning to develop your own Joomla component, module or plugin, the following book is a must have.

You can get it for cheap on Amazon.

11 April 2010

Adding additional Joomla registration fields

The default Joomla registration page is very basic. In many situations, one might want to add field to it. This is how to do it:

Just add the fields you want to the following files:

For saving the info
libraries/joomla/database/table/user.php

Display on registration page
components/com_user/views/register/tmpl/default.php 

For updating info
components/com_user/views/user/tmpl/form.php

Backend user form
administrator/components/com_users/views/user/tmpl/form.php
Joomla! Bible

Replacing MySQL characters

The following MySQL query will replace all occurences of Ã§ in the column 'name' of the 'customers' table with ç

UPDATE customers SET name = replace(name,'ç','ç');

I found it useful especially after copying databases. Copying databases with different collations tend to screw up the characters (especially when working with French accents). So applying this query will fix things up.

This is also useful in many other situations where we will want to replace a character in the database. I leave it to you to think it out.

Update mySQL table with values from another table

Suppose we have two tables myCustomers and allCustomers. We can update the value of table myCustomers based on the value that is common to both tables.

Example

UPDATE myCustomers , allCustomers
SET myCustomers.name = allCustomers.name
WHERE myCustomers.email = allCustomers.email;

What we did here is update all the names of table 'myCustomers' with the names of table 'allCustomers' where their email matches.

Table 'myCustomers' can be a smaller table that stores a small amount of info and table 'allCustomers' can be a reference master table.

French unreadable characters

To fix the problem of unreadable french characters when pulling info from a MySQL database, do this:

$query = mysql_query("SET NAMES UTF8",$conn) or die(mysql_error());

That is, we change the collation of the names column to utf8.

Display number of items in category / subcategory

In many cases, one might want to display the number of items found in a category / subcategory. This is specially the case for classifieds websites.

For example,

Vehicles (30)
  • Cars  (15)
  • Bikes (13)
  • Other (2)

This can be done by querying the database. In this case, I am using MySQL.

Let’s assume that we are passing the category id in the URL. So,
  1. Get the category id from the URL
  2. $cat = mysql_real_escape_string($_GET['category']);
  3. Query the database with that id
  4. $query = 'SELECT COUNT(*) as count FROM vehicles WHERE catId = '$cat'";
  5. Build the query
  6. $result = mysql_query($query);
  7. Get the resulting row
  8. $row = mysql_fetch_array($result);
  9.  Finally, get the count field from the resulting row (this is the data we want)
  10. $num_items_in_category = $row['count'];
Your comments are welcomed.

06 April 2010

AJAX post with JQuery

JQuery allows us to pass info to the server and get back results without leaving the page. This comes in handy for example when we want to submit a form, authenticate users against a database, load photos etc. I mostly use it for when I want to communicate with a MySQL database.

Here is an example where I send an id to the server which queries a MySQL database and return back the user's name for me.

I have a div called 'loading' in my HTML form. Before passing information to the server, I want the user to get a message, tell him to wait (the time that the information is being fetched from the server). So, I display a message in the 'loading' div.

$("#loading").html('Please wait...');

I then get the value that I want to pass to the server from my form.

var id = $('#userid').val();

I then create a data string of all the variables that I want to send to the server. In this case I will only send an id to the server.

var dataString = 'id='+ id;

Now, we move on to the AJAX part.

$j.ajax({
type: "POST",
url: "components/com_etudes/assets/ajax/getData.php", data: dataString,
success: function(data) {
//Display a message $j("#messages").html(data).css("color","green"); 
} });

POST : The way we want to submit the data to the server. We can use POST or GET

URL: This is the path to the PHP script that will receive the data, processes it and return a response to the Client browser.

DATA: This is the data that we have (concatenation of all the variables that we have)

success: function(data)
: This means that on success (i.e. if the script has been executed on the server without error). 'data' is a variable that contains the result sent from the server.

You see that I used the variable 'data' and updated the HTML of a div called 'messages'. That is this div 'messages' will get as content whatever was returned from the server.

SERVER PART

The getData.php is simple.

header('Content-Type: text/html; charset=iso-8859-1');

//Database connection
include('db.php');

//POST Variables
$id  = $_POST['id'];
$msg = '';

//Get the user
$SQL = "SELECT * FROM users WHERE id = ".$id; //execute the query $result = mysql_query($SQL,$conn) or die(mysql_error());
$row = mysql_fetch_array($result);
echo $row['name'];


So we basically passed an id to the server which queried a MySQL database and responded back with the name of the user that corresponded to the id passed. Simple!


Stay tuned for some other tips coming soon.


05 April 2010

Hello World

This blog was created to provide tips and tricks to web programmers as I gain experience in my Web development career. I will try to structure my information into a step by step guide so that it can easily be understood. I will also be updating the blog regularly and answering to any questions you may have (in your comments). So be sure to subscribe to the blog.