...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
September 6, 2011

Is there a need to persist data in model for use in methods?

Question by yentsun

In my ZF project I have a model, wich has to address a large array stored in Zend_Registry. The array gets into the Registry from cache (not from database). Different methods of the model can use the array many times during request. Having in mind best practices and optimized performance, I am not sure if I should:

  • apply a dedicated property for that and use it for some kind of cache
  • just get the array from registry each time.

Example of dedicated property:

class Application_Model_Category {

    private $_tree = null;
    ...
    public function _getTree() {
        if (!$this->_tree) {
            $this->_tree = Zend_Registry::get('tree');
        }
        return $this->_tree;
    ...
    public function methodOne() {
        foreach ($this->_getTree() as $category) {
            ...
        }
    }
    public function methodTwo() {
        $tree = $this->_getTree();
        foreach ($tree as $category) {
            ...
            $count = count($tree);
        }
    }
    ...
}

Example of getting each time from registry:

class Application_Model_Category {

    ...
    public function methodOne() {
        foreach (Zend_Registry::get('tree') as $category) {
            ...
        }
    }
    public function methodTwo() {
        $tree = Zend_Registry::get('tree');
        foreach ($tree as $category) {
            ...
            $count = count($tree);
        }
    }
    ...
}

Do these ways have any differences at all (like memory or cpu usage)? Or is the first method just a bit nicier looking?

Answer by Corbin

I would definitely go with the first one. It’s much easier to change in the future if necessary and it encapsulates the data fetching better. (Really in that sentence, the second thing is the cause of the first.)

Think about this:

What if later down the road you want to be able to pass in an argument to the constructor to allow overriding the behavior of fetching it from a registry? If you go with the first method, you only have to change the code in one place.

Also, with the first option, if you extend the class, the child class does not need knowledge of the workings of getTree. With the second way, it would also have a dependence on a registry.

Basically the first way marginally decreases coupling, which is good.

Answer by Starx

Well, obviously the first method, will slow the processing, to near negligible, but it all depends on the functionality, you are trying to create. Your first method ensures the _tree variable to be present to continue the processing, the second one does not as it is more likely to bring up an exception. I would recommend the 1st method, rather than the 2nd.

Read more
August 29, 2011

Does MySQL table row contain two values

Question by daidai

I have a table with two columns:

ID1 | ID2
---------
 1  | A
 3  | V
 1  | C
 4  | B
 5  | Q
 1  | S

And I want to be able to find out if any row has, say ID1 = 5 and ID2 = Q , and return a true / false value.

Answer by Starx

Yes, Of course

SELECT * FROM table where ID1='5' and ID2='Q'

PHP (I am just guessing this backend)

$query = "SELECT * FROM table where ID1='5' and ID2='Q'";
$result = mysql_query($query);
if(mysql_num_rows($result)) { return true; }
else { return false; }
Read more
August 17, 2011

Looping through post data and updating corresponding database records

Question by George Reith

I am trying to loop through some data I post through jQuery. Here is my PHP script:

<?php
include '../dbconnect.php';
$map = $_POST['map'];
$position = 0;
foreach ($map as $ID)
{
  if ($_POST['type'] == "sub") {
    $query = "UPDATE Subcategories SET `Position` = '$position' WHERE CategoryID = '$ID';";
  } else {
    $query = "UPDATE Categories SET `Position` = '$position' WHERE CategoryID = '$ID';";
  }

  $result = mysql_query($query) or die(mysql_error());
  $position ++;
}
?>

and the data it is recieving as $map is sent in this format:

ID[]=27&ID[]=28&ID[]=33&ID[]=19

Obviously my foreach is wrong, but how would I go about getting it so that I retain $maps order and each numerical value becomes the variable $ID?

Answer by Starx

Ok, Since your $map contains, ID[]=27&ID[]=28&ID[]=33&ID[]=19 string value. Do something like this

$str = str_replace($map, "ID[]=","");
$mArr = explode("&", $str);
foreach($mArr as $key) {
   //now your $key will have 27, 28, 33, 19 as the loop progresses
}

P.S. Based on the OP’s comment of $map having a string output of that

Read more

What are the different ways to configure routes?

Question by Starx

If someone is familier with Zend Framewor, they know what routes are and how they affect the system overall. My question is concerned about ways to can configure this routes. I know two ways to configure them, through Bootstrap.php and application.ini.

However, not hiding the fact that, I am pretty much of a learner in Zend Framework myself, I dont know which one is better and which should be preferred over the other.

Moreover, I do not know, if these are only ways available to configure the router?

So, please tell me what are ways through which we can configure router and which method is better over others.

P.S: I have included the two ways I knew as an answer.

Answer by Starx

Since I am attempting this to be as a guide for those like me, I would like to include the two ways I know of.

Application.ini

resources.router.routes.cat.route = "/browse/:catid/:name/"
resources.router.routes.cat.defaults.controller = index
resources.router.routes.cat.defaults.action = browse

Here What you do is,
resources.router.routes.XXX.route Define the name of the route in place of XXX

catid and name are the two paramters that will taken, when you pass the url is such way /browse/1/pc 1 will be assinged to catid and pc to name

Remaining two line defines the default parameter from controller and action, from MVC

Bootstrap.php

    $front = Zend_Controller_Front::getInstance();  
    // Get Router
    $router = $front -> getRouter();
    $routeBrowse = new Zend_Controller_Router_Route(
        '/browse/:catid/:name',
        array(
            'controller' => 'index',
            'action' => 'index'
        )
    );
    $router -> addRoute('browse', $routeBrowse);

I will avoid the explanation, since pretty much is same as before.

However, I am not sure which one is better that the other one. So, those who knows, update my answer.

Read more

Making an option in an HTML dropdown menu selected.

Question by Mason240

Thanks for reading my question.

I have a website that uses PHP for a searchable card database. Right now I have the code for the head/searchbox section on each page, but I want to use functions instead. The function itself is working. The problem is with the drop down boxes. I currently have it set up so that when a user selects and option, and then searches, the selections are selected on the next page.

I am sure that I am having a problem with syntax.

Here is an example of the working code, which is used on the live site right now.

    <select name="Type" onchange="this.submit()">
        <option value="1" >[All Card Types] </option>
        <option value="Hero" <?php if($_GET['Type'] == "Hero") echo "selected='selected'"; ?>> Hero </option>
        <option value="Ally" <?php if($_GET['Type'] == "Ally") echo "selected='selected'"; ?>> Ally </option>
    </select>

This is the relevant code from the function, which is not working, and is on the test site (ignore the error):

function searchBox(){
//Cell 1
    echo '
        <select name="Type" onchange="this.submit()">
            <option value="1" >[All Card Types] </option>
            <option value="Hero"  <?php if($_GET["Type"] == "Hero") { echo "selected=selected" ; }?>>   Hero    </option>
            <option value="Event" <?php if($_GET["Type"] == "Event") { echo "selected=selected"; }?>>   Event </option>
        </select>
    ';
}

As you can see in the test page, the dropdown menu doesn’t function like it does on the live page.

Thanks for the help!

Answer by Jonah

You can’t embed <?php tags in a string like that. You have to concatenate it with ternary operators.

function searchBox(){
//Cell 1
    echo '
        <select name="Type" onchange="this.submit()">
            <option value="1" >[All Card Types] </option>
            <option value="Hero"' . ($_GET['Type'] == 'Hero' ? ' selected=""' : '') . '>   Hero    </option>
            <option value="Event"' . ($_GET['Type'] == 'Event' ? ' selected=""' : '') . '>   Event </option>
        </select>
    ';
}

But for the sake of maintainability, you might do something more like this:

function searchBox() {
    $types = array('Hero', 'Event');
    $output = '<select name="Type" onchange="this.submit()">';
    $output .= ' <option value="1" >[All Card Types] </option>';
    foreach ($types as $type) {
        $output .= '<option value="' . $type . '"' . ($_GET['Type'] == $type ? ' selected=""' : '') . '>    ' . $type . '    </option>';
    }
    $output .= '</select>';
    echo $output;
}

Answer by Starx

You are missing the quotes

echo "selected="selected""
Read more
August 11, 2011

Zend vs Symfony learning time

Question by Liutas

Is faster to learn Zend Framework or Symfony?
Which framework has more and clear documentation?

Answer by evilcelery

I think both frameworks take some time to learn properly but you can’t beat Symfony’s documentation.

Answer by Starx

I would say zend is harder to learn… not because it is complex but because it is way simple in design. As many will point out, its loosely coupled. It can be integreated to anything… any other framework. To make such a developement friendly framework, the simplicity level is overreached. And to do one small thing, like modifying some form design, you end up getting tangled in too many things and start banging your head in between decorator pattern, factory pattern, but still learn nothing related to the framework itself. But give time, it will start making sense eventually and when it does, you will be happy that you took the decision to go with zend framework

Read more
August 9, 2011

Problem reading xml file from Zend

Question by mrN

I created a simple xml file to store name of stylesheets, where is my xml file.

<?xml version="1.0" encoding="UTF-8"?>
<skin>
    <stylesheets>
        <stylesheet>default.css</stylesheet>
    </stylesheets>
</skin>

Now I tried to read the data using the following code

protected function loadSkin() {
    $skinData = new Zend_Config_Xml('./template/'.$this -> _template.'/skins/'.$this -> _skin.'/skin.xml');
    var_dump($skinData);
    $stylesheets = $skinData -> stylesheets -> stylesheet -> toArray();
    if(is_array($stylesheets)) {
        foreach($stylesheets as $stylesheet) {
            $this -> view -> headLink() -> appendStylesheet('/template/'.$this -> _template.'/skins/' . $this -> _skin . '/css/' . $stylesheet);
        }
    }       
}

But its gives Call to a member function toArray() on a non-object. What am i doing wrong?

Answer by Starx

Actually, there is nothing wrong with your code. Its just a logical error. You have told Zend_Config_Xml to parse the stylesheet as an array. But since there is just one stylesheet you are giving, it will not parse it as an array.

Your Solution

Just add another stylesheet to the xml file.

Like

<?xml version="1.0" encoding="UTF-8"?>
<skin>
    <stylesheets>
        <stylesheet>default.css</stylesheet>
        <stylesheet>another.css</stylesheet>
    </stylesheets>
</skin>
Read more
August 2, 2011

PDO lastInsertId does not work on transactions?

Question by jasondavis

I am using PDO for the first time with MySQL, just playing with it at the moment.

So far when I try to do an insert wrapped in transactions…

$this->dbh->beginTransaction();
// $sql query ran
$this->dbh->commit();

echo $this->dbh->lastInsertId();

lastInsertId() is returning 0…when I run the same query outside of a transaction, I get the proper id number returned. Is there something I am missing here?

Answer by Starx

You have to ask for the lastInsertId() before you commit a transaction

Try

$this->dbh->beginTransaction();
// $sql query ran
echo $this->dbh->lastInsertId();
$this->dbh->commit();
Read more

How to use jquery to perform actions on PHP loop results?

Question by tchnchn

I’ve searched and can’t seem to make sense of the answers I’ve found. Grateful for any help!!

Goal: Reveal selected message detail in section#details below the listed message headers in section#info.

Problem:

  1. The following code alerts a result but won’t fadeIn();, (or show();, or …anything).
  2. The following code is only grabbing the value of the last result in the PHP while loop.

php/html/jquery/javascript:

        <section id="info">
            <?php
                $user = $session->username;
                $q = sprintf("SELECT * FROM mail WHERE UserTo = '%s' ORDER BY SentDate DESC",
                      mysql_real_escape_string($user));
                $getMail = mysql_query($q, $link) or die(mysql_error());

                if(mysql_num_rows($getMail) == 0) {
                    echo "<p>you have no mail</p>";
                }
                else {
                ?>
            <form id="inbox" class="mail">
                <fieldset>
                    <ul>
                        <li style="border: 2px solid purple; width: 100%;">
                            <span style="display: inline-block; border: 1px solid black; width: 8%; margin-left: 13%;">Status</span>
                            <span style="display: inline-block; border: 1px solid black; width: 15%;">From</span>
                            <span style="display: inline-block; border: 1px solid black; width: 45%;">Subject</span>
                            <span style="display: inline-block; border: 1px solid black; width: 16%;">Time</span>
                        </li>
                <?php
                        while($mail = mysql_fetch_object($getMail)) {
                            $status         =       $mail->status;
                            $mailId     =       $mail->mail_id;
                            $from           =       $mail->UserFrom;
                            $subject        =       $mail->Subject;
                            $received       =       $mail->SentDate;
                            $theMessage     =       $mail->Message;
                        ?>
                        <li class="outerDiv" style="border: 2px dotted purple;">
                            <button style="display: inline;" class="viewButton">View</button>
                            <button style="display: inline;">Delete</button>
                            <?php
                            echo "<span style='border: 1px solid red;'>" . $mail_id . "</span>";
                            echo "<span style='display: inline-block; width: 8%; border: 1px solid red;'>" . $status . "</span>";
                            echo "<span style='display: inline-block; width: 15%; border: 1px solid red;'>" . $from . "</span>";
                            echo "<span style='display: inline-block; width: 45%; border: 1px solid red;'>" . $subject . "</span>";
                            echo "<span style='display: inline-block; font-size: x-small; width: 17%; border: 1px solid red;'>" . $received . "</span>";                    
                            ?>
                        </li>
                <?php   }

                    } ?>
                    </ul>
                </fieldset>
            </form>
        </section>
        <section id="details">
            <div class="theMessage" style="display: none;"><?php echo $theMessage; ?></div>
            <script type="text/javascript">
                $(document).ready(function() {
                    $(".outerDiv").click(function(e) {
                        if($(e.target).is(".viewButton")) {
                    alert($(document).find(".theMessage").text()); //this works
                   $(document).find(".theMessage").text().fadeIn(1000); //this doesn't work

                   var theMessage = $(document).find(".theMessage").text();
                   theMessage.fadeIn(1000); //this doesn't work
                        }
                    });
                    return false; (sometimes prevents default..sometimes not?
                });
            </script>
        </section>

p.s. the crazy colors and borders are/were for temp layout purposes. also, the delete button will obviously have functionality… once I can figure this out.

Answer by Starx

Instead of

$(document).find(".theMessage").text().fadeIn(1000);

use

$('.theMessage').fadeIn(1000);
Read more
July 27, 2011

How can I filter POST numeric values in php?

Question by user841823

Numeric values..

$price = $_POST['price'];
$zipcode = $_POST['zipcode'];

How can I filter two fields passing through a single select tag field called category_id that uses the explode() to recieve the values from this category_id field.

Form

    <?php echo '<label for="Category">Category:</label>
<select name="category_id" size="1" ><br />';


$sql = "SELECT id, name FROM category ORDER BY name";

$rs = mysql_query($sql);

while($row = mysql_fetch_array($rs))
{
echo "<option value="".$row['name']."$".$row['id']."">".$row['name']."</option>n  ";
}


echo '</select>';

the way I receive the category_id field with explode but don’t know how to filter it since it is a numeric and data field at the same time.

$option = explode("$", $_POST['category_id']); 

enter code here

Answer by Phil

Are you just trying to retrieve the category name and ID from the posted, $ delimited category_id field?

If so, then this should do it

$option = explode("$", $_POST['category_id']);
$name = $option[0];
$id   = $option[1];

I would be more inclined to just set the ID in the <option> value attribute and fetch the name from the database or a pre-fetched associative array.

Update

If you’re wanting to validate that field, you could try something like

if (!preg_match('/^[a-zA-Z0-9]+$d+$/', $_POST['category_id'])) {
    // not valid
}

I wouldn’t attempt to filter out invalid characters on that field. Validation and error conditions are more concise.

Answer by Starx

Not sure, If i got you correctly. If you are trying to receive the name and id of the product from the same select box, using your technique

echo "<option value="".$row['name']."$".$row['id']."">".$row['name']."</option>n  ";

Change this line to this. Just replace $ with “_” for simplicty

echo "<option value="".$row['name']."_".$row['id']."">".$row['name']."</option>n  ";

Then while processing it

$category_id = $_POST['category_id'];
$carr = explode("_",$category_id);
$category = $carr[0];
$id = $carr[1];

//now verify them
if((int)$id>0) { //id is valid number
// and so on
Read more
...

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