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

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.

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""
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

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>
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();

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);
...

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