Your Ad Here

Monday, October 17, 2011

How To - Display products on home page

There are numerous ways to put products on your home page, and we’ll compile a list of code snippets you can use on your own store here. Some examples are outdated, they don’t work in magento 1.4.1 but solutions are provided at the bottom.

New products

Go to “CMS - Manage Pages” and select “Home Page” from the list of pages.
Use this code snippet to show products labeled as “new” on your front page:
  1. {{block type="catalog/product_new" name="home.catalog.product.new" alias="product_homepage" template="catalog/product/new.phtml"}}
(Note that you must have some new products in your catalogue for anything to show when you do this. In this context new doesn’t mean that you’ve recently added them; only products explicitly marked as new using ‘Set Product as New from Date’ and ‘Set Product as New to Date’ options in the ‘General’ product information page in the admin tool will be shown.)

All Products

Go to “CMS - Manage Pages” and select “Home Page” from the list of pages.
Use this code snippet to show all products in your catalog on your front page:
  1. {{block type="catalog/product_list" name="home.catalog.product.list" alias="products_homepage" template="catalog/product/list.phtml"}}

All Products from one Category

Go to “CMS - Manage Pages” and select “Home Page” from the list of pages.
Use this code snippet to show one category on your front page:
  1. {{block type="catalog/product_list" name="home.catalog.product.list" alias="products_homepage" category_id="4" template="catalog/product/list.phtml"}}
The category ID can be found when you go to “manage category” and then select the category you want. The ID is written in the header.
Examples are outdated, dosent work in magento 1.4.1

Layout Update XML for magento 1.4

Because in 1.4 version Layout update is different than in 1.3 version, you can use this example:
  1. <reference name="content">
  2.     <block type="catalog/product_list" name="featured" template="catalog/product/list.phtml">
  3.         <action method="setCategoryId"><category_id>[category id here]</category_id></action>
  4.     </block>
  5. </reference>
Note: source taken from BrightEyesDavid’s post
It’s possible to add the ‘Root category’ ID here to show all products (Is Anchor Yes required!)

New products - Layout Update XML for magento 1.4

To display new product / latest product, you can use this following XML code in layout xml file or layout display in backend. You can use also the widgets to display the products. The code below has been inspired by the widget.
diglin
  1. <reference name="content">
  2.     <block type="catalog/product_new" template="catalog/product/new.phtml">
  3.         <action method="setProductsCount"><count>5</count></action>
  4.         <action method="addColumnCountLayoutDepend"><layout>empty</layout><count>6</count></action>
  5.         <action method="addColumnCountLayoutDepend"><layout>one_column</layout><count>5</count></action>
  6.         <action method="addColumnCountLayoutDepend"><layout>two_columns_left</layout><count>4</count></action>
  7.         <action method="addColumnCountLayoutDepend"><layout>two_columns_right</layout><count>4</count></action>
  8.         <action method="addColumnCountLayoutDepend"><layout>three_columns</layout><count>3</count></action>
  9.     </block>
  10. </reference>

New products with pagination - Layout Update XML for Magento 1.4.1

By default the Magento New.php and New.phtml block and template do not provide a way for you to display new products with pagination. The pagination and toolbar elements of Magento belong to the Mage_Catalog_Block_Product_List class. It is possible for one to overwrite the New.php file that Magento provides so that it extends the


For more detail or step by step detail click here

Display categories on home page in Magento

The code below does a couple of things, first it will get all the store’s categories - it then checks to see if they are active before continuing.

<?php
$cats = Mage::getModel('catalog/category')->load(2)->getChildren();
$catIds = explode(',',$cats);
?>
<ul>
<?php foreach($catIds as $catId): ?>
<li>
    <?php
        $category =  Mage::getModel('catalog/category')->load($catId);
        echo '<a href="'.$category->getURL().'">'.$category->getName().'</a>';
               
        $subCats = Mage::getModel('catalog/category')->load($category->getId())->getChildren();
        $subCatIds = explode(',',$subCats);
        ?>
        <?php if(count($subCatIds)>1):?>
        <ul>
        <?php foreach($subCatIds as $subCat) :?>
        <li>
        <?php
        $subCategory = Mage::getModel('catalog/category')->load($subCat);
        //echo $subCategory->getName();
        if($subCategory->getIsActive())
        {
            echo '<a href="'.$subCategory->getURL().'">'.$subCategory->getName().'</a>';
        }

        ?>
        </li>
        <?php endforeach;?>
        </ul>
        <?php endif;?>
        </li>
        <?php endforeach; ?>
        

Friday, October 14, 2011

Posting to Twitter using PHP

Please note that Twitter no-longer support Basic Auth via the API so the following code no longer works. Please see the official docs for more info
Like others I’ve found myself becoming something of a fan of Twitter, the impossible to explain social networking site. If you’re reading this, have a twitter account and not already my friend then add me if you like.
Apart from the interesting social aspects I’m also interested in Twitter as an API for all sorts of communications, remember Twitter already deals nicely with SMS messaging, Instant Messaging, subscription and the like and has a nice XML and JSON based API. I’ve been using the Zamano SMS gateway at work for a few projects and Twitter actually lets me some more and doesn’t come with a price tag.
I started out playing with curl to send updates like so (obviously with a real username and password):
curl -u username:password -d status="twittering from curl" http://twitter.com/statuses/update.xml
I then used the PHP curl features to do the same thing from PHP:
&lt;?php
// Set username and password
$username = 'username';
$password = 'password';
// The message you want to send
$message = 'is twittering from php using curl';
// The twitter API address
$url = 'http://twitter.com/statuses/update.xml';
// Alternative JSON version
// $url = 'http://twitter.com/statuses/update.json';
// Set up and execute the curl process
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, "$url");
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_POST, 1);
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, "status=$message");
curl_setopt($curl_handle, CURLOPT_USERPWD, "$username:$password");
$buffer = curl_exec($curl_handle);
curl_close($curl_handle);
// check for success or failure
if (empty($buffer)) {
    echo 'message';
} else {
    echo 'success';
}
?&gt;
Obviously you could do more with the return than print out a success or failure message. The $buffer variable has the returned XML or JSON for you’re parsing pleasure.
I’m going to try out some of the other API methods too, probably play more with XSL or look more closely at the PEAR JSON module in building up a simple library as a quick search didn’t throw up much of interest and the API is nice and simple; making it fun to hack on.

Post comments on WordPress blogs

In a previous article, I have discussed how spammers spams your WordPress blog. To do so, they simply have to fill the $postfields array with the info they want to display and load the page.
Of course, this code is only for educationnal purposes.
<?php
$postfields = array();
$postfields["action"] = "submit";
$postfields["author"] = "Spammer";
$postfields["email"] = "spammer@spam.com";
$postfields["url"] = "http://www.iamaspammer.com/";
$postfields["comment"] = "I am a stupid spammer.";
$postfields["comment_post_ID"] = "123";
$postfields["_wp_unfiltered_html_comment"] = "0d870b294b";
//Url of the form submission
$url = "http://www.ablogthatdoesntexist.com/blog/suggerer_site.php?action=meta_pass&id_cat=0";
$useragent = "Mozilla/5.0";
$referer = $url; 

//Initialize CURL session
$ch = curl_init($url);
//CURL options
curl_setopt($ch, CURLOPT_POST, 1);
//We post $postfields data
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
//We define an useragent (Mozilla/5.0)
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
//We define a refferer ($url)
curl_setopt($ch, CURLOPT_REFERER, $referer);
//We get the result page in a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//We exits CURL
$result = curl_exec($ch);
curl_close($ch);

//Finally, we display the result
echo $result;
?>

Publish a post on your WordPress blog, using cURL

I know that most of you enjoy WordPress, so here is a nice “hack” as the ones I regulary publish on my other blog WpRecipes.
This function can post on your WordPress blog. You don’t need to login to your WP dashboard etc.
Though, you must activate the XMLRPC posting option in your WordPress blog. If this option isn’t activated, the code will not be able to insert anything into WordPress database. Another thing, make sure the XMLRPC functions are activated on your php.ini file.
function wpPostXMLRPC($title,$body,$rpcurl,$username,$password,$category,$keywords='',$encoding='UTF-8')
{
    $title = htmlentities($title,ENT_NOQUOTES,$encoding);
    $keywords = htmlentities($keywords,ENT_NOQUOTES,$encoding);

    $content = array(
        'title'=>$title,
        'description'=>$body,
        'mt_allow_comments'=>0,  // 1 to allow comments
        'mt_allow_pings'=>0,  // 1 to allow trackbacks
        'post_type'=>'post',
        'mt_keywords'=>$keywords,
        'categories'=>array($category)
    );
    $params = array(0,$username,$password,$content,true);
    $request = xmlrpc_encode_request('metaWeblog.newPost',$params);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
    curl_setopt($ch, CURLOPT_URL, $rpcurl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 1);
    $results = curl_exec($ch);
    curl_close($ch);
    return $results;
?>

Update your Facebook status


10 awesome things to do with cURL

Published on June 29th, 2009 by Jean-Baptiste Jung. 91 Comments -
cURL, and its PHP extension libcURL, are tools which can be used to simulate a web browser. In fact, it can for example, submit forms. In this article, I’m going to show you 10 incredible things that you can do using PHP and cURL.

Acknowledgments

New to cURL? If yes, check out the following articles to learn the purposes and basics of cURL/libcurl.
Please note that some of the techniques shown here can be used for “blackhat” methods. The goal of this article is only educationnal, please do not use any of the snippets below for illegal stuff.

1 – Update your Facebook status

Wanna update your facebook status, but don’t want to go to facebook.com, login, and finally being able to update your status? Simply save the following code on your server, define the variables, and voilà!

Download a URL’s Content Using PHP cURL

The Code

copy/* gets the data from a URL */
function get_data($url)
{
  $ch = curl_init();
  $timeout = 5;
  curl_setopt($ch,CURLOPT_URL,$url);
  curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
  curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
  $data = curl_exec($ch);
  curl_close($ch);
  return $data;
}
 

The Usage

$returned_content = get_data('http://davidwalsh.name');copy$returned_content = get_data('http://davidwalsh.name');



Alternatively you can use the PHP DOM:
$keywords = array();
$domain = array(‘http://davidwalsh.name‘);
$doc = new DOMDocument;
$doc->preserveWhiteSpace = FALSE;
foreach ($domain as $key => $value) {
@$doc->loadHTMLFile($value);
$anchor_tags = $doc->getElementsByTagName(‘a’);
foreach ($anchor_tags as $tag) {
$keywords[] = strtolower($tag->nodeValue);
}
}
Keep in mind this is not a tested piece of code, I took parts from a working script I have created and cut out several of the checks I’ve put in to remove whitespace, duplicates, and more.

 

Friday, October 7, 2011

CSS Bubble Tooltips

/*---------- bubble tooltip -----------*/
a.tt{
    position:relative;
    z-index:24;
    color:#3CA3FF;
    font-weight:bold;
    text-decoration:none;
}
a.tt span{ display: none; }

/*background:; ie hack, something must be changed in a for ie to execute it*/
a.tt:hover{ z-index:25; color: #aaaaff; background:;}
a.tt:hover span.tooltip{
    display:block;
    position:absolute;
    top:0px; left:-40px;
    padding: 15px 0 0 0;
    width:200px;
    color: #993300;
    text-align: center;
    filter: alpha(opacity:90);
    KHTMLOpacity: 0.90;
    MozOpacity: 0.90;
    opacity: 0.90;
}
a.tt:hover span.top{
    display: block;
    padding: 30px 8px 0;
    background: url(bubble.gif) no-repeat top;
}
a.tt:hover span.middle{ /* different middle bg for stretch */
    display: block;
    padding: 0 8px;
    background: url(bubble_filler.gif) repeat bottom;
}
a.tt:hover span.bottom{
    display: block;
    padding:3px 8px 10px;
    color: #548912;
    background: url(bubble.gif) no-repeat bottom;
}



And HTML example:
<div id="container">
        <h1>CSS Bubble Tooltips</h1>
        <p>Avoid cross-browser javascript when you can use css to make tooltips with less code. Honestly you were going to use css to style your tooltips anyway right? Your probably already have most of this code in your css already too.  You can <a href="#" class="tt">hover over me<span class="tooltip"><span class="top"></span><span class="middle">This is my Bubble Tooltip with CSS</span><span class="bottom"></span></span></a> to see how well these bubble tooltips work.  Besides that if you have an advanced site in the first place you probably have enought javascript already.</p>
        <p>This example will show you how well this tooltip stretches for long descriptions when you <a href="#" class="tt">hover here!<span class="tooltip"><span class="top"></span><span class="middle">WWOOWW!, <br />This really is a very long tooltip.  Normally they aren't this long but every once in a while you feel the urge to use a really long description to make sure you get your point across to everyone!  This could go on and on all of the way down the page and probably overflow onto the next website you visit!;)</span><span class="bottom"></span></span></a>.  Also with the IE hack for the :hover state, you can do this with elements besides anchors.</p>
        <p>If you dont like how it allows you to hover over the tooltip also then you can adjust the padding and top to separate the tool tip from the link.</p>

    </div>
If you dont like how it allows you to hover over the tooltip also then you can adjust the padding and top to separate the tool tip from the link.
Download Source

Tuesday, October 4, 2011

Convert PHP array to Javascript array

A very basic tutorial. For the beginners who want to pass array values from PHP to Javascript for them to be accessible in the client side JS as an array. It’s really easy to pass PHP array to Javascript.
The below code passes a string array in PHP to Javascript.




<?php

$arr = array("a","b","c");

?>

<script>

var jsArray = ["<?php echo join("\", \"", $arr); ?>"];

alert(jsArray);

</script>

How to use the database classes in your script

Why should I use the Joomla database class?

Joomla can use different kinds of SQL database systems and run in a variety of environments with different table-prefixes. In addition to these functions, the class automatically creates the database connection. Besides instantiating the object you need just two lines of code to get a result from the database in a variety of formats. Using the Joomla database layer ensures a maximum of compatibility and flexibility for your extension.

Preparing the query

// Get a database object
$db =& JFactory::getDBO();
 
$query = "SELECT * FROM #__example_table WHERE id = 999999;";
$db->setQuery($query);
First we instantiate the database object; then we prepare the query. You can use the normal SQL syntax. The only thing you have to change is the table prefix. To make this as flexible as possible, Joomla uses a placeholder for the prefix, the “#__”. In the next step, the $db->setQuery(), this string is replaced with the correct prefix.
Now, if we don't want to get information from the database, but rather insert a row into it, we need one more function. Every string value in the SQL syntax should be quoted. For example, MySQL uses backticks `` for names and single quotes ‘‘ for values. Joomla has some functions to do this for us and to ensure code compatibility between different databases. We can pass the names to the function $db->nameQuote($name) and the values to the function $db->Quote($value).
A fully quoted query example is:
$query = "
  SELECT * 
    FROM ".$db->nameQuote('#__example_table')."  
    WHERE ".$db->nameQuote('id')." = ".$db->quote('999999').";
  ";
Whatever we want to do, we have to set the query with the $db->setQuery() function. Although you could write the query directly as a parameter for $db->setQuery(), it's commonly done by first saving it in a variable, normally $query, and then handing this variable over. This results in clean, readable code.

setQuery($query)

The setQuery($query) method sets up a database query for later execution either by the query() method or one of the Load result methods.
$db =& JFactory::getDBO();
$query = "/* some valid sql string */";
$db->setQuery($query);
Notes: The parameter $query must be a valid SQL string. It can either be added as a string parameter or as a variable. Generally a variable is preferred; it leads to more legible code and can help in debugging.
setQuery() also takes three other parameters: $offset, $limit (both used in list pagination) and $prefix, an alternative table prefix. All three variables have default values set and can usually be ignored.

Executing the Query

To execute the query, Joomla provides several functions, which differ in their return value.

Basic Query Execution

query()

The query() method is the basic tool for executing SQL queries on a database. In Joomla it is most often used for updating or administering the database simply because the various load methods detailed on this page have the query step built into them.
The syntax is very straightforward:
$db =& JFactory::getDBO();
$query = "/* some valid sql string */";
$db->setQuery($query);
$result = $db->query();
Note: $query() returns an appropriate database resource if successful, or FALSE if not.

Query Execution Information

  • getAffectedRows()
  • explain()

insertid()

If you insert a record into a table that contains an AUTO_INCREMENT column, you can obtain the value stored into that column by calling the insertid() function
$query = "INSERT INTO '#__example_table' ('name','email','username')
        VALUES ('John Smith','johnsmith@domain.example','johnsmith')";
$db->setQuery($query);
$db->query();
$user_id = $db->insertid();

Insert Query Execution

  • insertObject()

Query Results

The database class contains many methods for working with a query's result set.

Single Value Result

loadResult()

Use loadResult() when you expect just a single value back from your database query.
id name email username
1 John Smith johnsmith@domain.example johnsmith
2 Magda Hellman magda_h@domain.example magdah
3 Yvonne de Gaulle ydg@domain.example ydegaulle
This is often the result of a 'count' query to get a number of records:
$db =& JFactory::getDBO();
$query = "
  SELECT COUNT(*)
    FROM ".$db->nameQuote('#__my_table')."
    WHERE ".$db->nameQuote('name')." = ".$db->quote($value).";
  ";
$db->setQuery($query);
$count = $db->loadResult();
or where you are just looking for a single field from a single row of the table (or possibly a single field from the first row returned).
$db =& JFactory::getDBO();
$query = "
  SELECT ".$db->nameQuote('field_name')."
    FROM ".$db->nameQuote('#__my_table')."
    WHERE ".$db->nameQuote('some_name')." = ".$db->quote($some_value).";
  ";
$db->setQuery($query);
$result = $db->loadResult();

Single Row Results

Each of these results functions will return a single record from the database even though there may be several records that meet the criteria that you have set. To get more records you need to call the function again.
id name email username
1 John Smith johnsmith@domain.example johnsmith
2 Magda Hellman magda_h@domain.example magdah
3 Yvonne de Gaulle ydg@domain.example ydegaulle

loadRow()

loadRow() returns an indexed array from a single record in the table:
. . .
$db->setQuery($query);
$row = $db->loadRow();
print_r($row);
will give:
Array ( [0] => 1 [1] => John Smith [2] => johnsmith@domain.example [3] => johnsmith ) 
You can access the individual values by using:
$row['index'] // e.g. $row['2']
Notes:
  1. The array indices are numeric starting from zero.
  2. Whilst you can repeat the call to get further rows, one of the functions that returns multiple rows might be more useful.

loadAssoc()

loadAssoc() returns an associated array from a single record in the table:
. . .
$db->setQuery($query);
$row = $db->loadAssoc();
print_r($row);
will give:
Array ( [id] => 1 [name] => John Smith [email] => johnsmith@domain.example [username] => johnsmith )
You can access the individual values by using:
$row['name'] // e.g. $row['name']
Notes:
  1. Whilst you can repeat the call to get further rows, one of the functions that returns multiple rows might be more useful.

loadObject()

loadObject returns a PHP object from a single record in the table:
. . .
$db->setQuery($query);
$result = $db->loadObject();
print_r($result);
will give:
stdClass Object ( [id] => 1 [name] => John Smith [email] => johnsmith@domain.example [username] => johnsmith )
You can access the individual values by using:
$result->index // e.g. $result->email
Notes:
  1. Whilst you can repeat the call to get further rows, one of the functions that returns multiple rows might be more useful.

Single Column Results

Each of these results functions will return a single column from the database.
id name email username
1 John Smith johnsmith@domain.example johnsmith
2 Magda Hellman magda_h@domain.example magdah
3 Yvonne de Gaulle ydg@domain.example ydegaulle

loadResultArray()

loadResultArray() returns an indexed array from a single column in the table:
$query = "
  SELECT name, email, username
    FROM . . . ";
. . .
$db->setQuery($query);
$column= $db->loadResultArray();
print_r($column);
will give:
Array ( [0] => John Smith [1] => Magda Hellman [2] => Yvonne de Gaulle )
You can access the individual values by using:
$column['index'] // e.g. $column['2']
Notes:
  1. The array indices are numeric starting from zero.
  2. loadResultArray() is equivalent to loadResultArray(0).

loadResultArray($index)

loadResultArray($index) returns an indexed array from a single column in the table:
$query = "
  SELECT name, email, username
    FROM . . . ";
. . .
$db->setQuery($query);
$column= $db->loadResultArray(1);
print_r($column);
will give:
Array ( [0] => johnsmith@domain.example [1] => magda_h@domain.example [2] => ydg@domain.example )
You can access the individual values by using:
$column['index'] // e.g. $column['2']
loadResultArray($index) allows you to iterate through a series of columns in the results
. . .
$db->setQuery($query);
for ( $i = 0; $i <= 2; $i++ ) {
  $column= $db->loadResultArray($i);
  print_r($column);
}
will give:
Array ( [0] => John Smith [1] => Magda Hellman [2] => Yvonne de Gaulle )
Array ( [0] => johnsmith@domain.example [1] => magda_h@domain.example [2] => ydg@domain.example )
Array ( [0] => johnsmith [1] => magdah [2] => ydegaulle )
Notes:
  1. The array indices are numeric starting from zero.

Multi-Row Results

Each of these results functions will return multiple records from the database.
id name email username
1 John Smith johnsmith@domain.example johnsmith
2 Magda Hellman magda_h@domain.example magdah
3 Yvonne de Gaulle ydg@domain.example ydegaulle

loadRowList()

loadRowList() returns an indexed array of indexed arrays from the table records returned by the query:
. . .
$db->setQuery($query);
$row = $db->loadRowList();
print_r($row);
will give (with line breaks added for clarity):
Array ( 
[0] => Array ( [0] => 1 [1] => John Smith [2] => johnsmith@domain.example [3] => johnsmith ) 
[1] => Array ( [0] => 2 [1] => Magda Hellman [2] => magda_h@domain.example [3] => magdah ) 
[2] => Array ( [0] => 3 [1] => Yvonne de Gaulle [2] => ydg@domain.example [3] => ydegaulle ) 
)
You can access the individual rows by using:
$row['index'] // e.g. $row['2']
and you can access the individual values by using:
$row['index']['index'] // e.g. $row['2']['3']
Notes:
  1. The array indices are numeric starting from zero.

loadAssocList()

loadAssocList() returns an indexed array of associated arrays from the table records returned by the query:
. . .
$db->setQuery($query);
$row = $db->loadAssocList();
print_r($row);
will give (with line breaks added for clarity):
Array ( 
[0] => Array ( [id] => 1 [name] => John Smith [email] => johnsmith@domain.example [username] => johnsmith ) 
[1] => Array ( [id] => 2 [name] => Magda Hellman [email] => magda_h@domain.example [username] => magdah ) 
[2] => Array ( [id] => 3 [name] => Yvonne de Gaulle [email] => ydg@domain.example [username] => ydegaulle ) 
) 
You can access the individual rows by using:
$row['index'] // e.g. $row['2']
and you can access the individual values by using:
$row['index']['column_name'] // e.g. $row['2']['email']

loadAssocList($key)

loadAssocList('key') returns an associated array - indexed on 'key' - of associated arrays from the table records returned by the query:
. . .
$db->setQuery($query);
$row = $db->loadAssocList('username');
print_r($row);
will give (with line breaks added for clarity):
Array ( 
[johnsmith] => Array ( [id] => 1 [name] => John Smith [email] => johnsmith@domain.example [username] => johnsmith ) 
[magdah] => Array ( [id] => 2 [name] => Magda Hellman [email] => magda_h@domain.example [username] => magdah ) 
[ydegaulle] => Array ( [id] => 3 [name] => Yvonne de Gaulle [email] => ydg@domain.example [username] => ydegaulle ) 
)
You can access the individual rows by using:
$row['key_value'] // e.g. $row['johnsmith']
and you can access the individual values by using:
$row['key_value']['column_name'] // e.g. $row['johnsmith']['email']
Note: Key must be a valid column name from the table; it does not have to be an Index or a Primary Key. But if it does not have a unique value you may not be able to retrieve results reliably.

loadObjectList()

loadObjectList() returns an indexed array of PHP objects from the table records returned by the query:
. . .
$db->setQuery($query);
$row = $db->loadObjectList();
print_r($row);
will give (with line breaks added for clarity):
Array ( 
[0] => stdClass Object ( [id] => 1 [name] => John Smith 
    [email] => johnsmith@domain.example [username] => johnsmith ) 
[1] => stdClass Object ( [id] => 2 [name] => Magda Hellman 
    [email] => magda_h@domain.example [username] => magdah ) 
[2] => stdClass Object ( [id] => 3 [name] => Yvonne de Gaulle 
    [email] => ydg@domain.example [username] => ydegaulle ) 
)
You can access the individual rows by using:
$row['index'] // e.g. $row['2']
and you can access the individual values by using:
$row['index']->name // e.g. $row['2']->email

loadObjectList('key')

loadObjectList($key) returns an associated array - indexed on 'key' - of objects from the table records returned by the query:
. . .
$db->setQuery($query);
$row = $db->loadObjectList('username');
print_r($row);
will give (with line breaks added for clarity):
Array ( 
[johnsmith] => stdClass Object ( [id] => 1 [name] => John Smith 
    [email] => johnsmith@domain.example [username] => johnsmith ) 
[magdah] => stdClass Object ( [id] => 2 [name] => Magda Hellman 
    [email] => magda_h@domain.example [username] => magdah ) 
[ydegaulle] => stdClass Object ( [id] => 3 [name] => Yvonne de Gaulle 
    [email] => ydg@domain.example [username] => ydegaulle ) 
)
You can access the individual rows by using:
$row['key_value'] // e.g. $row['johnsmith']
and you can access the individual values by using:
$row['key_value']->column_name // e.g. $row['johnsmith']->email
Note: Key must be a valid column name from the table; it does not have to be an Index or a Primary Key. But if it does not have a unique value you may not be able to retrieve results reliably.

Miscellaneous Result Set Methods

getNumRows()

getNumRows() will return the number of result rows found by the last query and waiting to be read. To get a result from getNumRows() you have to run it after the query and before you have retrieved any results.
. . .
$db->setQuery($query);
$db->query();
$num_rows = $db->getNumRows();
print_r($num_rows);
$result = $db->loadRowList();
will return
3
Note: if you run getNumRows() after loadRowList() - or any other retrieval method - you may get a PHP Warning:
Warning: mysql_num_rows(): 80 is not a valid MySQL result resource 
in D:\xampp\htdocs\joomla1.5a\libraries\joomla\database\database\mysql.php on line 344

Tips, Tricks & FAQ

Subqueries

Subqueries should be written as follows:
SELECT * FROM #__example WHERE id IN (SELECT id FROM #__example2);
These kinds of queries are supported since MySQL 4.1. If this method fails, you can split the query into two as demonstrated below. Please note that this will (often unnecessarily) increase the load on the database server.
$query = "SELECT id FROM #__example2";
$database->setQuery($query);
$query = "SELECT * FROM #__example WHERE id IN (". implode(",", $database->loadResultArray()) .")";

Using MySQL User-Defined Variables

MySQL User-Defined Variables are created and maintained for the lifespan of a connection. In Joomla terms this is usually the lifespan of a page request. They can be used in consecutive queries, retaining their value, as long as each query is inside the same connection lifespan.
$database =& JFactory::getDBO();
$database->setQuery("SET @num := 0");
$database->query();
$database->setQuery("SET @num := @num + 5");
$database->query();
$database->setQuery("SELECT @num");
$result = $localDB->loadResult();
The first query defines the MySQL User-Defined Variable, the second one increments it by 5, the third one retrieves it's value and will in this case return a value of 5.

The fact that they retain their value can be quite useful, however there is also a little risk. If you use the same User-Defined Variable, in this case @num, in another query, make sure you reset it first. If that other query runs within the same connection lifespan, @num will have remembered its value of 5. You may expect it to start at null or 0.

For details on working with MySQL's User-Defined Variables, please refer to the MySQL documentation at http://dev.mysql.com/doc/

Developer-Friendly Tips

Here is a quick way to do four developer-friendly things at once:
  • Use a simple constant as an SQL seperator (which can probably be used in many queries).
  • Make your SQL-in-PHP code easy to read (for yourself and possibly other developers later on).
  • Give an error inside your (component-) content without really setting debugging on.
  • Have a visibly nice SQL by splitting SQL groups with linebreaks in your error.
$db =& JFactory::getDBO();
$jAp=& JFactory::getApplication();
    //We define a linebreak constant
define('L', chr(10));
    //Here is the most magic
$db->setQuery(
 'SELECT * FROM #__table'.L.
 'WHERE something="something else")'.L.
 'ORDER BY date desc'
); 
$db->query();
    //display and convert to HTML when SQL error
if (is_null($posts=$db->loadRowList())) {$jAp->enqueueMessage(nl2br($db->getErrorMsg()),'error'); return;}

Monday, October 3, 2011

jQuery get select option id

$('#size').change(function(){
   var id = $(this).find(':selected')[0].id;
   $('#changevalue').val(id);
})

PHP to JAVASCRIPT: 2D Array Conversion


<?php


// start off the javascript array stirng
$js_array 'var pf = [';


// loop into the first dimension
for($i 0$ic = (count($pf)-1); $i $ic$i++)

{

    // add a new javascript array to the js_stirng

    $js_array .= '[';

    

    // loop through the second dimension

    for($x 0$xc = (count($pf[$i])-1); $x $xc$x++)

    {

        // add the data to the js_array

        $js_array .= '"'.$pf[$i][$x].'"';

        

        // if its not the last peice of data, add a comma

        if($x != $xc)

            $js_array .= ',';

    }

    

    // end the javascript array

    $js_array .= ']';

    

    // if its not the last peice of data, add a comma

    if($i != $ic)

        $js_array .= ',';

}


// finish the js_array string
$js_array .= '];';


PHP to JAVASCRIPT: 2D Array Conversion// now just print the js
?>


<script language="javascript">

<!--

<?=$js_array?>
//-->

</script>