...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
March 5, 2012

Return category and forums in query?

Question by Leeloo

I’m currently developing a simple forum inside CodeIgniter to get a handle on PHP, and I’ve ran into a problem, albeit elementary.

My forum index is made up of categories, which each have a few forums assigned to them. I would like to display the title of each category, and then return each of the forums underneath.

Here is my MODEL at the moment to return the data:

function get_top_level_forums()

{

    $this->db->select('id, title');
    $this->db->from('forum_category');
    $query = $this->db->get();

    if ($query->num_rows() > 0)

    {

        $categories = $query->result();

        foreach($categories as $category)

        {

            $this->db->select('id, title, description');
            $this->db->from('forum');
            $this->db->where('parent_id', 0);
            $this->db->where('category_id', $category->id);
            $query = $this->db->get();

            $forums = $query->result();

        }

        return $categories;

    }

}

I’m struggling to work out how to return all of the data in a single array. I know this is a rookie question, but I’ve poked at it for an hour and can’t see any light at the end of the tunnel!

I know how to use the data in my CONTROLLER and VIEW. I’m just stuck on the MODEL part.

Thanks.

🙂

Answer by Starx

Instead of using a variable to store the result, use an array instead

$forums[] = $query->result();

Full Example:

$forums = array();
foreach($categories as $category)

        {

            $this->db->select('id, title, description');
            $this->db->from('forum');
            $this->db->where('parent_id', 0);
            $this->db->where('category_id', $category->id);
            $query = $this->db->get();

            $forums[] = $query->result();

        }
        //$forums now contains all the query results

Update

To access the variables you can use

$forums[$forumindex][0] -> id;
Read more

Nested Divs Spacing

Question by user596075

I have a parent div and two nested divs. I have the nested divs set as display: table-cell. How can you set spacing between those nested divs? I’ve tried margin, but that didn’t do anything (the jsFiddle has margin set, yet with no effect).

jsFiddle showing my question/problem

Answer by sandeep

Give display: inline-table; instead of display: table-cell. Write like this

.child {
    width: 100px;
    height: 100px;
    display: inline-table;
    margin-left: 100px;
}

Check this http://jsfiddle.net/cZptA/9/

Answer by Starx

It is possible and very simple

Since you have specified the child divs to behave as table-cell, by default they will be no spacing between them just like a regular table. So, there is nothing wrong with you code.

If you really want your divs to behave as tables. Your parent div should have border-spacing for the spacing between the table-cells.

.parent {
    width: 400px;
    height: 400px;
    background-color: red;
    border-spacing: 10px;
}

Demo

Read more
March 4, 2012

Select box opening input box jQuery

Question by user1235905

I am trying to open a have a select box show an input box when certain options are selected.

Here is my code:

$("document").ready(function() {
    $('input.other').hide();
    $('#amount').change(function() {
        // var val = $(this).find('option:selected').text();
        //alert(val);
        var selectedValue = $(this).find(":selected").val();
        //alert(selectedValue);
        if( $(this).selectedValue == '25.00') {
            // only if the radio button has a dob-field
            $('input.other').show();// show only the following first
        }
    });
});

Answer by adeneo

You can target the selected option inside the #amount element directly by using the selector below, and find it’s value and compare it all inside the if statement.

The problem with the code in the question is $(this).selectedValue, where $(this) is referring to #amount and not the option, and selectedValue is a variable, and should be used directly, but it’s not really necessary to use a variable here, as it’s fully readable and straight forward to do everything inside the if statement.

$('input.other').hide();
$('#amount').on('change', function(){
    if( $(':selected', this).val() == '25.00') {
        $('input.other').show();
    }
});

Answer by Starx

Use selectedValue to check not $(this).selectedValue

if( selectedValue == '25.00') { // only if the radio button has a dob-field
 $('input.other').show();// show only the following first
}

Here is a full working snippet

$(document).ready(function() {
    $('input.other').hide();
        var selectedValue = $(this).find(":selected").val();
        if( selectedValue == '25.00') {
            // only if the radio button has a dob-field
            $('input.other').show();// show only the following first
        }
    });
});
Read more

Database class design

Question by JamWaffles

I’m creating a web app with various classes for things like the user, Smarty template control, etc.

I already have a database class which is all well and good, but I’m concerned about the performance of it.

Currently, in another class, I’m doing $this->db = new DB() to create a local database instance, however the database class’s __construct() function creates a new connection to the MySQL server every time I make a new DB() instance, which is obviously less than sensible. This means that each instance of all my different classes that uses the database class makes a connection to the server. I don’t have a vast amount of classes, but I only want one per page load.

This is a stripped down sample of what I have at the moment:

// Database class used by multiple other classes
class DB {
    private $dbh;

    function __construct() {
        $this->dbh = // PDO connection here
    }

    public function query($str) {
        // Do a query
    }
}

// Example class User
class User {
    private $db;    // Stores local instance of DB class.

    function __construct() {
        $this->db = new DB();    // Makes a new connection in DB::__construct()
    }

    public function login() {
        $this->db->query('SELECT * FROM users');
    }
}

I’m looking for the “best” or most common practice of doing this. I don’t want to make 10-ish separate connections for each page load.

I want to know what the best way of using and managing a DB class in my application. My four thoughts are these:

  1. Would using a persistent connection to the MySQL server solve this multiple connection issue for me?
  2. Should I use a static factory class and return a DB instance instead of using new DB()?
  3. Is the proper solution to use an entirely static class and just do DB::query() (for example) every time I reference it?
  4. I often use multiple classes in another (so we might have class Folders which requires classes User, DB and Smarty). Is it general practice to extend each class somehow?

Answer by Brent Baisley

If you make the variable holding the connection static, then you can check if you already established a connection. Static variables are the same across all instances of the class, so you can create 100 instances that all use the same connection. You just need to reference it statically: self::$dbh instead of $this->dbh.

class DB {
    private static $dbh = null;

    function __construct() {
        if ( is_null(self::$dbh) ) {
            self::$dbh = // PDO connection here
        }
    }
 }

Answer by Starx

I would suggest you to check the $this -> db at first and then only create it.

function __construct() {
        if(!isset($this -> db) || !is_a("DB", $this -> db)) {
         $this->db = new DB();    // Makes a new connection in DB::__construct()
    }
}
Read more

jquery comment system on.(…click) issue

Question by Anonymous

I’m having trouble keeping event handlers attached to future loaded selectors. For example, when pull.php is loaded, the confirmdelete is no longer hidden, and also the click event handlers no longer exist. I am new to jquery and ajax. Below is my code.
$id= (int)strip_tags($_GET[‘id’]);

$(document).ready(function() { //make a comment delete js file eventually, just so we can reference the source
    $('.confirmdeletecomment').hide();
    $('.deletecomment').on("click", function(e){
        var cid = $(this).attr("id");
        $('a#c'+cid).show(500, function(){ //right now as call back
            $(this).on("click", function(e){
            var id = $(this).attr("id"); 
            var did = id.substring(1);  
            $.post(

                'deletecommentdata.php?cid='+did,

                function(data)
                {
                   $("#commentarea").load("pull.php?id=<? echo $id; ?>");
                   $("#comment").val("");
                   $('.confirmdeletecomment').hide();

                }

                )

                e.preventDefault();//so it doesn't interpret is as an anchor link

                });



                });

    e.preventDefault();//so it doesn't interpret is as an anchor link
    });


});

</script>

the below script is the php part:

<div id="commentarea">

<?

$query = mysql_query("SELECT users.user_id, users.username, users.miniavatar, comments.comment_id, comments.comment, comments.time_stamp FROM users INNER JOIN comments ON users.user_id=comments.products_users_user_id WHERE comments.products_products_id = '$id' ORDER BY comments.time_stamp DESC");

while($row2 = mysql_fetch_array($query)) {

?>
<div id='singlecomment'>

<hr class="comment" />
<table>
<col width="*" />
<col width="400" />
<col width="*" />    
<tr>
<td valign = "top" rowspan="2">
<a href="collection.php?profile=<? echo $row2['user_id']; ?>"><img src="<? echo $row2['miniavatar']; ?>" height="52" width="52" /></a> <br />
<?  
if ($user_id == $row2['user_id']) { 
    $cid = $row2['comment_id'];


    echo "<a id='$cid' class='deletecomment' title='Delete Post'>X</a> &nbsp";
    echo "<a id='c$cid' class='confirmdeletecomment'>confirm</a>";
}   
?>
</td>
<td valign="top">
<a class="blue" href="collection.php?profile=<? echo $row2['user_id']; ?>"> <? echo $row2['username']; ?> </a>
</td>
<td> 
<span class="date"><? echo date("F j, Y g:i a ", strtotime($row2['time_stamp'])); ?> </span>
</td>
<tr>
<td colspan="2">
<? echo stripslashes($row2['comment']); ?> <br/><br/>
</td>
</tr>
</table> 
</div>

Answer by Starx

I am guessing the event got messed up since you are the passing the event handler from

$('.deletecomment').on("click", function(e){

to

 $(this).on("click", function(e){

Change the event names, if you really want to handle them separately. More like updating your second handler as these will do goo

$(this).on("click", function(event){

Since I dont have your markup structure, I am guessing, when you are loading pull.php to #commentarea, another element with class confirmdelete should have been loaded as well, thus making the code execution incomplete logically.

Put, $(".confirmdelete").hide(); right above e.preventDefault() to see if I am right.

Read more

Php, optional public variable

Question by Malixxl

i’ve some public variables in my class, here is how i define them

class MyClass
{
   public $var1;
   public $var2;
   public $var3;

   function __construct($params)
   {
     if(isset($params['var1']))
     $this->var1 = $params['var1'];

     if(isset($params['var2']))
     $this->var3 = $params['var2'];

     if(isset($params['var3']))
     $this->var3 = $params['var3'];

   }
}

but as i said theese are optional parameters. Some object’s will use it, some wont use it. My question is i’m defining it everytime even it’s used or not. Should i define it when it’s passed something like:

     if(isset($params['var1']))
     public $var1 = $params['var1'];

i’m quite newbie with php, just need to know what i’m doing at top is right?

edit:typo.

Answer by Sarfraz

You can create an array instead and store only those values that are submitted like this:

class MyClass
{
   public $data = array();

   function __construct($params)
   {
     if(isset($params['var1']))
        $this->data['var1'] = $params['var1'];

     if(isset($params['var2']))
        $this->data['var2'] = $params['var2'];

     if(isset($params['var3']))
        $this->data['var3'] = $params['var3'];

   }
}

This way you have a single concrete known variable you can refer to anytime to get needed data back.

Answer by Starx

I dont like the whole concept. Since you are defining a public variable, what is the entire point. Unless you are blocking this, we can easily initialize a public variable outside the class, like:

$obj = new classname();

$obj -> unknowpublicname = "somevaue";

Whatever you do, unless you restrict some rules, or change the access modifiers, it does not make any difference.

Read more

PHP cant use variable defined outside functions

Question by Adonis K.

Im working on a project (simple xml CMS) just to learn some basic PHP.

first i include a config.php file which contains information about the CMS, then i include a route.php for the url routing and after that i include a functions.php file which is pretty similar to the wordpress’ one (contains all the functions to for example load posts, tags, categories etc).

The structure looks like this:

    function products($search = FALSE, $query= '', $page = 1, $results = 5){
    }

    function getProductById($id){
    }

    function getProductTitleById($id){
    }

    function getProductByExcerpt($excerpt){
    }

    function getProductTitleByExcerpt($excerpt){
    }

    function getPost($id, $title, $description, $category, $excerpt = FALSE){
    }

    function getTitle(){
    }

    function breadcrumb($params, $first){
    }

    function pagination($page, $pages){
    }
?>

In config.php file i also use this code:

$xml = simplexml_load_file('products.xml') or die('The Product xml file couldnt be loaded.');

But when i try to access $xml from within the functions i prepared in functions.php, i get a undefined variable notice. (i also tried placing the $xml variable inside the functions.php before the definition of the functions but got the same result).

Can someone please tell me my mistake? I know its simple, i just cant see clearly right now.

Thanks in advance.

Answer by Another Code

You have a scoping issue. The variables declared in the global scope aren’t visible inside your functions. The manual explains what you can do about it. An overview:

  • Import the variable from the global scope into the local scope of your function with global $xml; at the start of the function
  • Store the variable as a key of the global variables superglobal, i.e. $GLOBALS['xml']
  • Make the variable a static member of a class or create a singleton construction
  • Pass the variable as an argument to every function that needs it

Note that when using a good OOP-style architecture these kind of problems can often be avoided, e.g. $xml would be a property of class instances that need direct access to the DOM object.

Answer by Starx

Functions or methods do not have scopes outside them. In order to use a variable declared outside. Using global keyword, to tell the server to use the variable defined in higher scope.

$varname = "value";
function yourfunctionname() {
    //In order to use the variable declare you want to use the globally declared 
    global $varname;
    //now $varname will have "value` as its value

   //continue with your logic
}
Read more

How to properly apply values farmed from .each()

Question by Morningseven

Markup:
<ul>
  <li>
    <ul id="ratx">
      <li>Location</li>
      <li class="bar"><span></span></li>
      <li class="value">4</li>
    </ul>
  </li>
  <li>
    <ul id="ratx">
     <li>Hotel Services</li>
     <li class="bar"><span></span></li>
     <li class="value">5</li>
    </ul>
  </li>
  <li>
    <ul id="ratx">
      <li>Hotel Facilities</li>
      <li class="bar"><span></span></li>
      <li class="value">3</li>
    </ul>
  </li>
  <li>
    <ul id="ratx">
      <li>Room Cleanliness</li>
      <li class="bar"><span></span></li>
      <li class="value">4</li>
    </ul>
  </li>
  <li>
    <ul id="ratx">
      <li>Value for Money</li>
      <li class="bar"><span></span></li>
      <li class="value">1</li>
    </ul>
  </li>
</ul>

I want to represent User Ratings dynamically using JQuery so I made a function like this,

jQuery:
$("ul#ratx").each(function(index) {
var val = $(this).children(".value").text();
var barval = val * 40;

/* compute ratings */ 
$("li.bar span").css("width", barval);

});

Now, when I alert barval I get all 5 values but when I try to apply the “compute ratings” line, all it does is apply the last value that it finds. How should I go about this?

Sorry if the question is a confusing. I am not quite sure how to phrase everything.

Answer by Starx

The problem is that, while interating through each elements it find, it is applying a common value to all li.bar span. You should represent a single element, you are trying to apply to.

$(this).children(“li.bar span”).css(“width”, barval);

Update

Here is a working Demo

The snippet that worked was

$(this).find("li.bar").children("span").css("width", barVal );

Also, I changed the display property of the span to display: inline-block;

Read more

Jquery $.ajax not returning correctly, but does for someone else

Question by user1247901

jquery:

var value="value"
var datastr="data"+value;
 $.ajax({
        type:'POST',
        url:'ggg.php',
        data: datastr,
        dataType: "html",
        success:function(response) {
            $("#task").html(response);
        }
        });

});

php:

echo 'this is your response';

The variables are just there to show what I would do if I were using them. It should be returning “this is your response”, but i’m getting “jtftcyrxcktfitdkfkf”. I’m not sure what is causing this, I’ve tried changing the dataType, etc. Someone else used the code as is, and said it is returning correctly for them. So is there anything that would be causing it not to work correctly for me? :/

Answer by Starx

I think your script is giving that jtftcyrxcktfitdkfkf somewhere in ggg.php. Have you included or required some file before/after. Make sure they are not returning any output.

When all hope seems to fail, clear the output buffer

ob_clean();
echo 'this is your response';
exit;
Read more

jQuery code conflicts

Question by user1220022

Apologies for the generic title.

I have two jQuery files, one handles form submissions and one handles page hyperlinks.

The form submission checks that the form entries are not blank, if it is – it informs the user and will display an error message, when the form is filled in the form data is passed to a processing file.

The hyperlinks loads new page data into a div, this new page data often includes forms as handled by the processing file.

I don’t know why – but ~60% of the time the form submission will ‘refresh’ on click and load the main index page OR the page last visited. This seems entirely random.

I can’t see why this is happening and if anyone can show me I would greatly appreciate it.

Form submission code:

$(document).ready(function(){

    $('.ajax_form').submit(function() {

        // check for empty inputs
        var errors = 0;
        $(".ajax_form :input").map(function(){
            if(!$(this).val()) {
                errors++;
            }  
        });

        // if empty inputs inform user
        if(errors > 0){
            $('#results').text("All fields are required");
            return false;
        }

        // hide form and show loader
        $(".ajax_form").slideUp("normal");
        $('#results').html('<span id="load">Loading..</span>');

        // post data to processing file
        $.post(
            'processing.php',
            $(this).serialize(),
            function(data){
                $("#results").slideDown("normal");
                $("#results").html(data)
            }
        );

        return false;

    });

});

Navigation code:

$(document).ready(function(){

    // if hash is already set, load linked data
    var hash = window.location.hash.substr(1);
    $('#nav li a').each(function(){
        if(hash == $(this).attr('href')){
            var toLoad = hash + '.php';
            $('#content').load(toLoad)
        }
    });

    // each menu item on click load linked data
    $('#nav li a').click(function(){

        var toLoad = $(this).attr('href') + '.php';
        window.location.hash = $(this).attr('href');

        $('#content').prepend('<span id="load">Loading..</span>');
        $('#content').hide();
        $('#content').load(toLoad);
        $('#content').slideDown('normal');

        return false;

    });

});

Answer by Starx

Your form refreshes because before reaching the part of return false;, the scripts breaks
somewhere before.

Use firebug or similar to detect this. Be sure to handle all outcomes or every condition.

May be a quick dry run can detect the gaps.

Read more
...

Please fill the form - I will response as fast as I can!