Flex & PHP - вставка запроса в службу Php - PullRequest
1 голос
/ 16 февраля 2012

У меня есть MySql DB с 2 таблицами:
1. Категория - ID категории / категория / описание
2. Фото - ID фотографии / ID категории / фотоописание / фотография

И у меня есть услуга (CategoryService.php) автоматически создается Flash Builder, но я не могу получить вторую таблицу !!

    <?php

class CategoryService {

    var $username = "root";
    var $password = "";
    var $server = "localhost";
    var $port = "3306";
    var $databasename = "teste";
    var $tablename = "category";

    var $connection;

    /**
     * The constructor initializes the connection to database. Everytime a request is 
     * received by Zend AMF, an instance of the service class is created and then the
     * requested method is invoked.
     */
    public function __construct() {
        $this->connection = mysqli_connect(
                                $this->server,  
                                $this->username,  
                                $this->password, 
                                $this->databasename,
                                $this->port
                            );

        $this->throwExceptionOnError($this->connection);
    }

    /**
     * Returns all the rows from the table.
     *
     * Add authroization or any logical checks for secure access to your data 
     *
     * @return array
     */
    public function getAllCategory() {

        $stmt = mysqli_prepare($this->connection, "SELECT * FROM $this->tablename");        
        $this->throwExceptionOnError();

        mysqli_stmt_execute($stmt);
        $this->throwExceptionOnError();

        $rows = array();

        mysqli_stmt_bind_result($stmt, $row->categoryId, $row->category, $row->description);

        while (mysqli_stmt_fetch($stmt)) {
          $rows[] = $row;
          $row = new stdClass();
          mysqli_stmt_bind_result($stmt, $row->categoryId, $row->category, $row->description);
        }

        mysqli_stmt_free_result($stmt);
        mysqli_close($this->connection);

        return $rows;
    }

    /**
     * Returns the item corresponding to the value specified for the primary key.
     *
     * Add authorization or any logical checks for secure access to your data 
     *
     * 
     * @return stdClass
     */
    public function getCategoryByID($itemID) {

        $stmt = mysqli_prepare($this->connection, "SELECT * FROM $this->tablename where categoryId=?");
        $this->throwExceptionOnError();

        mysqli_stmt_bind_param($stmt, 'i', $itemID);        
        $this->throwExceptionOnError();

        mysqli_stmt_execute($stmt);
        $this->throwExceptionOnError();

        mysqli_stmt_bind_result($stmt, $row->categoryId, $row->category, $row->description);

        if(mysqli_stmt_fetch($stmt)) {
          return $row;
        } else {
          return null;
        }
    }

    /**
     * Returns the item corresponding to the value specified for the primary key.
     *
     * Add authorization or any logical checks for secure access to your data 
     *
     * 
     * @return stdClass
     */
    public function createCategory($item) {

        $stmt = mysqli_prepare($this->connection, "INSERT INTO $this->tablename (category, description) VALUES (?, ?)");
        $this->throwExceptionOnError();

        mysqli_stmt_bind_param($stmt, 'ss', $item->category, $item->description);
        $this->throwExceptionOnError();

        mysqli_stmt_execute($stmt);     
        $this->throwExceptionOnError();

        $autoid = mysqli_stmt_insert_id($stmt);

        mysqli_stmt_free_result($stmt);     
        mysqli_close($this->connection);

        return $autoid;
    }

    /**
     * Updates the passed item in the table.
     *
     * Add authorization or any logical checks for secure access to your data 
     *
     * @param stdClass $item
     * @return void
     */
    public function updateCategory($item) {

        $stmt = mysqli_prepare($this->connection, "UPDATE $this->tablename SET category=?, description=? WHERE categoryId=?");      
        $this->throwExceptionOnError();

        mysqli_stmt_bind_param($stmt, 'ssi', $item->category, $item->description, $item->categoryId);       
        $this->throwExceptionOnError();

        mysqli_stmt_execute($stmt);     
        $this->throwExceptionOnError();

        mysqli_stmt_free_result($stmt);     
        mysqli_close($this->connection);
    }

    /**
     * Deletes the item corresponding to the passed primary key value from 
     * the table.
     *
     * Add authorization or any logical checks for secure access to your data 
     *
     * 
     * @return void
     */
    public function deleteCategory($itemID) {

        $stmt = mysqli_prepare($this->connection, "DELETE FROM $this->tablename WHERE categoryId = ?");
        $this->throwExceptionOnError();

        mysqli_stmt_bind_param($stmt, 'i', $itemID);
        mysqli_stmt_execute($stmt);
        $this->throwExceptionOnError();

        mysqli_stmt_free_result($stmt);     
        mysqli_close($this->connection);
    }


    /**
     * Returns the number of rows in the table.
     *
     * Add authorization or any logical checks for secure access to your data 
     *
     * 
     */
    public function count() {
        $stmt = mysqli_prepare($this->connection, "SELECT COUNT(*) AS COUNT FROM $this->tablename");
        $this->throwExceptionOnError();

        mysqli_stmt_execute($stmt);
        $this->throwExceptionOnError();

        mysqli_stmt_bind_result($stmt, $rec_count);
        $this->throwExceptionOnError();

        mysqli_stmt_fetch($stmt);
        $this->throwExceptionOnError();

        mysqli_stmt_free_result($stmt);
        mysqli_close($this->connection);

        return $rec_count;
    }


    /**
     * Returns $numItems rows starting from the $startIndex row from the 
     * table.
     *
     * Add authorization or any logical checks for secure access to your data 
     *
     * 
     * 
     * @return array
     */
    public function getCategory_paged($startIndex, $numItems) {

        $stmt = mysqli_prepare($this->connection, "SELECT * FROM $this->tablename LIMIT ?, ?");
        $this->throwExceptionOnError();

        mysqli_stmt_bind_param($stmt, 'ii', $startIndex, $numItems);
        mysqli_stmt_execute($stmt);
        $this->throwExceptionOnError();

        $rows = array();

        mysqli_stmt_bind_result($stmt, $row->categoryId, $row->category, $row->description);

        while (mysqli_stmt_fetch($stmt)) {
          $rows[] = $row;
          $row = new stdClass();
          mysqli_stmt_bind_result($stmt, $row->categoryId, $row->category, $row->description);
        }

        mysqli_stmt_free_result($stmt);     
        mysqli_close($this->connection);

        return $rows;
    }


    /**
     * Utility function to throw an exception if an error occurs 
     * while running a mysql command.
     */
    private function throwExceptionOnError($link = null) {
        if($link == null) {
            $link = $this->connection;
        }
        if(mysqli_error($link)) {
            $msg = mysqli_errno($link) . ": " . mysqli_error($link);
            throw new Exception('MySQL Error - '. $msg);
        }       
    }
}

?>

В Flash Builder у меня есть 2 списка свечей, в первой есть все категории, и я хочу, когда selectedItemон заполняет другой соответствующими фотографиями.У меня есть запрос, который работает с базой данных, но я не могу вставить его в php.Это запрос:

SELECT TC.*, TP.photodescription , TP.photo FROM category TC inner join photos TP on TC.categoryId = TP.categoryId

Как я могу это сделать?Надеюсь, это понятно, спасибо за "прослушивание".

РЕДАКТИРОВАТЬ:

<fx:Script>
    <![CDATA[
        import mx.controls.Alert;
        import mx.events.FlexEvent;

        import spark.events.IndexChangeEvent;

        protected function list_creationCompleteHandler(event:FlexEvent):void
        {
            getAllCategoryResult.token = categoryService.getAllCategory();
        }


        protected function list2_creationCompleteHandler(event:FlexEvent):void
        {
            getAllphotosResult.token = photosService.getAllphotos();
        }

        protected function list_changeHandler(event:IndexChangeEvent):void
        {
            category = list.selectedItem;
        }

    ]]>
</fx:Script>
<fx:Declarations>
    <s:CallResponder id="getAllCategoryResult"/>
    <categoryservice:CategoryService id="categoryService"
                                     fault="Alert.show(event.fault.faultString + '\n' + event.fault.faultDetail)"
                                     showBusyCursor="true"/>
    <valueObjects:Category id="category"/>
    <s:CallResponder id="getAllphotosResult"/>
    <photosservice:photosService id="photosService"
                                   fault="Alert.show(event.fault.faultString + '\n' + event.fault.faultDetail)"
                                   showBusyCursor="true"/>
</fx:Declarations>
<s:List id="list" x="197" y="127" creationComplete="list_creationCompleteHandler(event)" change="list_changeHandler(event)"
        labelField="category">
    <s:AsyncListView list="{getAllCategoryResult.lastResult}"/>
</s:List>
<s:List id="list2" x="708" y="127" creationComplete="list2_creationCompleteHandler(event)"
        labelField="photo">
    <s:AsyncListView list="{getAllphotosResult.lastResult}"/>
</s:List>

Это пример моего .mxml.
Как я могу на "selectedItem "изменить второй список на основе categoryId!?
Не могли бы вы помочь или показать мне несколько примеров !?Еще раз спасибо ..

1 Ответ

0 голосов
/ 16 февраля 2012

FLashBuilder создал класс CRUD (Create, Read, Update, Delete) для вас.Это только на основе вашей таблицы одной категории.var $tablename = "category"; - таким образом, он возвращает только результаты для категории.Если вы хотите создать JOIN, у вас есть несколько вариантов:

  1. Пользовательский написать новый метод в сгенерированном классе с помощью оператора JOIN, удалить класс из проекта FlashBuilder и импортироватьобновленный файл в FlashBuilder как существующий класс PHP.

  2. Создайте второй сгенерированный класс PHP для таблицы фотографий и затем объедините результаты в приложении Flex.

  3. Используйте параметр «Объединить поля» для операции JOIN, которая возвращает данные, полученные из нескольких таблиц базы данных.(вероятно, лучший вариант)

Чтобы узнать больше о том, как это сделать, см .: http://help.adobe.com/en_US/Flex/4.0/AccessingData/WSbde04e3d3e6474c4-668f02f4120d422cf08-7ff7.html

...