HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

PHP Class for sending a response to Flash

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
flashphpresponsesendingforclass

Problem

I've created this code to send a response to Flash which can be handled with AS2/AS3:

con = mysql_connect(
                $this->sql_hostname,
                $this->sql_username,
                $this->sql_password
            );

            // Connection could not be established
            if(!$this->con)
            {
                $this->response = array(
                    "status" => "no_connection",
                    "message" => "Could not connect to MySQL, try again later."
                );

                $this->respond();
            }

            // Select database
            mysql_select_db($this->sql_database);
        }

        /**
         * Send response back to Flash
         */
        public function respond()
        {
            $ar = array();
            foreach($this->response as $key => $value)
                array_push($ar, $key . "=" . $value);

            die(implode("&", $ar));
        }
    }
?>


I'm not that great with PHP and the respond() function seems like it could be written a little better.. Any suggestions?

Solution

I have used PHP for a few years now, and here are my suggestions:

array_push() can be used to add multiple values into an array at once, but in your case, your pushing only one value in at a time which means you can use:

$ar[] = $key . "=" . $value

This should also speed up your code a little( What's better to use in PHP $array[] = $value or array_push($array, $value)?).

die() is normally used when there is an error. It spits out a message to the user. If you are using this code to just connect to a MySQL database then change die(implode("&", $ar)); to echo(implode("&", $ar));

But honestly, you should be able to take out the respond() function if you are only using it to send an array to flash.

// Connection could not be established
        if(!$this->con)
        {
            $this->response = array(
                "status" => "no_connection",
                "message" => "Could not connect to MySQL, try again later."
            );

             echo(implode("&", $this->response));
        }

Code Snippets

// Connection could not be established
        if(!$this->con)
        {
            $this->response = array(
                "status" => "no_connection",
                "message" => "Could not connect to MySQL, try again later."
            );

             echo(implode("&", $this->response));
        }

Context

StackExchange Code Review Q#3555, answer score: 3

Revisions (0)

No revisions yet.