Ретельний add message php PHP AJAX CRUD: створення, видалення, редагування записів у БД MySQL

Зрештою я зрозумів: краще за дружину нікого не знайти. Залишилось тільки знайти дружину

PHP AJAX CRUD: створення, видалення, редагування записів у БД MySQL

У цій статті ми дізнаємося про те, як додавати, редагувати та видаляти записи у базі даних MySQL, використовуючи PHP. Ми використовували обробник JQuery, який надсилає AJAX запит до серверного скрипту. Обробник оновлює список записів.

AJAX форма для надсилання запитів на створення, видалення, редагування

При додаванні запису форма надсилає дані PHP скрипту через запит AJAX. У разі успішного додавання список записів перезавантажується.

JQuery AJAX функції для запиту до бази даних CRUD

У функції JQuery AJAX ми маємо перемикач випадки додати редагувати і видаляти. Ці випадки генерує різні рядки запиту та відповіді-дані в залежності від дій бази даних.

function showEditBox(id) ( $("#frmAdd").hide(); var currentMessage = $("#message_" + id + " .message-content").html(); var editMarkUp = ""+currentMessage+" SaveCancel"; $("#message_" + id + " .message-content").html(editMarkUp); ) function cancelEdit(message,id) ( $("#message_" + id + " .message-content") .html(message); $("#frmAdd").show(); ) function callCrudAction(action,id) ( $("#loaderIcon").show(); var queryString; switch(action) ": queryString = "action="+action+"&txtmessage="+ $("#txtmessage").val(); break; case "edit": queryString = "action="+action+"&message_id="+ id + " &txtmessage="+ $("#txtmessage_"+id).val(); break; case "delete": queryString = "action="+action+"&message_id="+ id; break; ) jQuery.ajax(( url: "crud_action.php", data:queryString, тип: "POST", success:function(data)( switch(action) ( case "add": $("#comment-list-box").append(data); break; case "edit": $("#message_" + id + ".message-content").html(data); $("#frmAdd").show(); break; case "delete": $("#message_"+id).fadeOut(); break; ) $("#txtmessage").val(""); $("#loaderIcon").hide(); ), error:function ()() )); )

PHP скрипт для операцій CRUD

Наступний код виконує запити до бази даних. Цей PHP-скрипт після виконання CRUD дії оновлює записи в результаті відповіді AJAX.

require_once("dbcontroller.php"); $db_handle = новий DBController(); $action = $_POST["action"]; if(!empty($action)) ( switch($action) ( case "add": $result = mysql_query("INSERT INTO comment(message) VALUES("".$_POST["txtmessage"]."")" ); if($result)($insert_id = mysql_insert_id(); echo " Edit Delete " . $_POST["txtmessage"] . " "; ) break; case "edit": $result = mysql_query("UPDATE comment set message = "".$_POST["txtmessage"]."" WHERE id=".$_POST["message_id"]); if($result) echo $_POST["txtmessage"]; break; (!empty($_POST["message_id"])) ( mysql_query("DELETE FROM comment WHERE id=".$_POST["message_id"]); ) break;

Overview

Будівля в notification system, перша в Joomla, дозволяє вашому довіднику натиснути на користувача (або групу користувачів) позначитися на різних аспектах. Примітка, що повідомлення є важливими вимогами, що користувачі можуть бути зацікавлені в read and keep track of it.
Notifications може бути створена будь-яка. У вашому компоненті або plugins і останній відтворюється всередині JomSocial notification system.
Цей літературу буде показано, що, але ні в якому разі нема idea of ​​third-party component we could use:)
Якщо ви не знаєте, як створювати інструмент, який буде захищений на цьому місці, ми робимо це, щоб виконати цей контроль.

Implementing it in your component anyway

Як зазначено в перегляді цього літератури, ми будемо створювати notifications з використанням plugin community.
Ви будете робити, щоб створювати повідомлення всередині свого компонента, або ваш plugin. Наслідуючи літературу буде працювати в будь-якому випадку. Ви повинні тільки визначити, на якому рівні в вашому коді notification буде створено і just load the JomSocial Core Libraries file.

require_once JPATH_ROOT . "/components/com_community/libraries/core.php" ;

Зробивши tutorial explained bellow will work just fine for your extension too

Preparing the Development Environment

1. We will assume that you"re already created community type example plugin which will be triggered when user changes its profile
Якщо ви не можете скакнути empty example plugin from , install it in Joomla and enable the plugin. It is named Community - Notifications Example
2. Навігація до вашого database і empty these два tables, so they dont have any records at all

A) prefix_community_notification
b) prefix_community_mailq

3. Будьте на двох двох (2) користувачах на ваших тестових роботах і знають свої ID"s

У попередніх версіях Joomla, user ID's буде завжди переглянуто з визначеного номера (62, 42) У Joomla 3, цей номер буде бути рівним, денним, зображення з нашого тестування навколишнього середовища, щоб його було певним чином.

The First Notification

Open the plugin php file which will be located в ROOT/plugins/community/example
З функцією onAfterProfileUpdate() replace the

CNotificationLibrary:: add ($cmd, $actor, $target, $subject, $body, $template, $params);

Як показано на прикладі, notification add api have 7 parameters

  • $cmd - це notification type. Ви можете додати всі зміни типів в цьому файлі. ROOT/components/com_community/libraries/notificationtypes.php starting from, or line 53. We recommend using system_messaging notification type.
  • $actor - is the person who carry out the action
  • $target - це людина, або група людей, які будуть отримувати повідомлення
  • $subject - is notification subject, in both, notification popup window and the email title
  • $body - is the body of email notification message
  • $template - якщо ви потребуєте конкретний template для використання, ви можете визначити його. Іншийwise, цей параметр може бути empty
  • $params - custom defined parameters
  • Knowing all this, lets define the variables we will use
    Change your plugin code to:

    $user = CFactory:: getUser(); $cmd = "system_messaging"; // first param, тип діяльності $actor = $user -> id ; //second param - get the id of $actor $target = "965" ; // Third param. Who receive notification? У нашому середовищі, його admin user with id 965. На вашому environment, ви будете найбільш добре, щоб отримати ID від вашого об'єкта або від array of users. $subject = "Notification Subject" ; // Subject of both, email and popup notifications $body = ; // Body message in emails. $template = ""; // Якщо ви потрібні для використання specific jomsocial template file, ви можете define it here. $params = new CParameter("" ) ; // We want to create an additional params object, and assign data to it, without having to formally define a class CNotificationLibrary:: add ( $cmd , $actor , $target , $subject , $body , $template , $params ) ;

    Новий підпис з будь-яким користувачем і зміна profile information. Lets go to database to see what happened.
    Navigate to prefix_community_notifications table and observe the new record

    Navigate to prefix_community_mailq table, і бачите новий рекорд

    Congratulations! - Ви успішно створили свою першу пряму власні notification, які були розповсюджені за допомогою електронної пошти та міжнародного JomSocial notification system


    Potential Code Bloat

    Above example is fine, and it works, але це не є спільним для використання це як це. Instead, it could be written like this

    $actor = CFactory:: getUser(); $params = new CParameter("") ; CNotificationLibrary:: add ( "system_messaging" , $actor -> "This is the notification body message" , "" , $params ) ;

    Це є дуже чутливим і підготовленим до тих пір, коли basically doing absolutely самої thing as a code shown above.

    Custom Notification Parameters

    Примітка API може бути розширена з будь-яким рівнем для вас, щоб бути прийнятим.
    Ці рекомендації можуть бути прописані до її email template, notification, і of course, language file.

    $actor = CFactory:: getUser(); $link = "http://www.google.com"; $params = new CParameter("" ) ; $params -> set ("actor", $actor -> getDisplayName()); // can be used as (actor) tag $params -> set ("actor_url", "index.php?option=com_community&view=profile&userid=". $actor -> id); // Link for the (actor) tag $params -> set("url", $link); //url of the whole activity. Використовується, коли їзда над avatarом в notification window. Можна використовувати як (url) tag in outgoing emails too. Make sure that you have defined $link variable:) CNotificationLibrary:: add ( "system_messaging" , $actor -> id , "965" , "Notification Subject" , "Цей є повідомлення повідомлень message" , "" , $params ) ;

    • $params = новий CParameter( ); - Ви будете створювати новий персоналізований об'єкт, і оцінити його, без будь-якого умовно визначеного класу.
    • $params->set("actor", $actor->getDisplayName()); - Your notification should always have an actor. Цей парадокс може бути прописаний до мітки як (actor) tag. У notification window, it defines the user that carries an action.
    • $params->set("actor_url", "index.php?option=com_community&view=profile&userid=" . $actor->id); - Actor URL is usually the url of an actor. In notification popup, it adds the link to the (actor) element
    • $params->set("url", $link); - Це є найбільш важливим paramater you must always set properly. У notification window, ця парам використовується за допомогою зображення. У електронній повітрі, це все, що місце, де діяльність відбувається.

    Для цього example, we will set variable $link to lands on www.google.com so you can see how it works

    Adding Language String and Use Params

    Маючи params, як тільки налаштовуються, можна використовувати в наших мовних файлах як добре.
    Lets define the language keys by altering the " CNotificationLibrary::add() API

    CNotificationLibrary:: add ( "system_messaging" , $actor -> id , "965" , JText:: sprintf ("PLG_COMMUNITY_EXAMPLE_SUBJECT" ) , JText:: sprintf ("PLG_COMMUNITY_EXAMPLE_BODY" ), "

    The language file should look like this

    PLG_COMMUNITY_EXAMPLE_SUBJECT = "(actor) updated profile" PLG_COMMUNITY_EXAMPLE_BODY = "Hi Admin \n Це є електронна пошта, щоб дізнатися, що (actor) updated profile \n\n Якщо ви хочете, щоб Google, click here \n (url)" _QQ_">(url)"

    У цьому прикладі, ми використовуємо tag (actor) and (url) для прослуховування ваших дзвінків, notification, і email templates. Lets see how does that look.
    У повідомленні повідомлень, коли ходьба над avatarом, повідомити про (url) param клацнути в і зняти link to google over avatar. It is intentional , because we made it that way:)


    ]

    У той самий window, коли ходьба над actor link. This is the part where (actor) echoed the user that carries an action, while (actor_url)" taken care that object is linked properly


    Lets see what happens in the email queue


    І, наприкінці, поточний електронний лист, що є для отримання кінцевого користувача


    Success
    Till now, we created three (3) parameters that are successfully used in notification window, and emails.

  • (actor) - Відкрийте username of the user which carries the action
  • (actor_url) - Gives the attribute to the (actor)
  • (url) - Це не mandatory, але ви повинні будь-який він у вашій заяві. Це є головною URL-адресою, де рішення, що ми не зараховані про happened.
  • По-перше, ви можете define "

    • (target) - if you need it
    • (target_url) if you need it in your notification.
    • (title) - Commonly used to refer to object that generated notification. Example: "User X оновлений фото в Album Y ." Album Y is title here
    • (title_url) - Як з попередньою цією адресою, що генерує повідомлення.
    • (Message) - Цей парадокс може бути використаний для набору (і echo) message in body of JomSocial email.

    у моєму Zend-додатку я пишу трохи API для мобільних додатків. Щоб спростити роботу з мобільними розробниками, я використовую Swagger. Досі все працює чудово, за винятком одного GET-запиту.

    Коли я викликаю /user/messages/(sessionToken)? NumMessages = (numMessages) & pageNr = (pageNr) у браузері, я отримую результати, які хочу, але коли я намагаюся дозволити Swagger виконати цей запит, передається лише sessionToken. Я спробував ці інструкції для Swagger:

    /** * @SWG\Api(path="/user/messages/(sessionToken)?numMessages=(numMessages)&pageNr=(pageNr)", * @SWG\Operation(* method="GET", * summary=" Gets messages paged", * notes="", * type="string", * nickname="getUsermessagesPaged", * authorizations=(), * @SWG\Parameter(* name="sessionToken", * description="The token from an active user session", * required=true, * type="string", * paramType="path", * allowMultiple=true *), * @SWG\Parameter(* name="numMessages", * description=" номер messages на сторінці (numMessages & pageNr ignored if not both are set)", * required=true, * type="string", * paramType="query", * allowMultiple=true *), * @SWG\Parameter (* name="pageNr", * description="pagenumber (numMessages & pageNr є не вказано, якщо немає вибору)", * required=true, * type="string", * paramType="query", * allowMultiple=true *), * @SWG\ResponseMessage(code=200, message="json (messages => "user_messages")"), * @SWG\ResponseMessage(code=400, message="json with error "не надав") ) *) *) */

    Хтось бачить мою помилку?

    Будь-яка допомога вітається.

    З повагою

    Відновлення. Як було запропоновано, я змінив обидва paramTypes на "query" і змінив шлях:

    @SWG\Api(path="/user/messages/(sessionToken)",

    але не працював винищувач.

    xdebug в eclipse PDT показує:

    RequestURI => /ias/public/user/messages/(sessionToken)

    QueryParams => Zend\\Stdlib\\Parameters - *ArrayObject*storage => Array - =>

    чванство JSON:

    ( "apiVersion": "1.0.0", "swaggerVersion": "1.2", "apis": [ ( "path": "\/user", "description": "Operations about users" ) ], "info" : ( "title": "Mobile access api", "description": "This is the xxx mobile access api.", "termsOfServiceUrl": null, "contact": "xxx", "license": null, "licenseUrl" : null, "_partialId": null, "_partials": , "_context": ( "comment": "\/**\ * @SWG\\Info(\ * title="Mobile access api",\ * description="This is the xxx mobile access api.",\ * contact="xxx",\ *)\ *\/", "line": 3 } } } !}

    Ось вихід /user:

    ( "basePath": "http://localhost/ias/public", "swaggerVersion": "1.2", "apiVersion": "1.0.0", "resourcePath": "/user", "apis": [ ( "path": "/user/balance/(sessionToken)", "operations": [ ( "method": "GET", "summary": "Gets userbalance", "nickname": "getUserdata", "type": "string", "parameters": [ ( "paramType": "path", "name": "sessionToken", "type": "string", "required": true, "allowMultiple": false, "description": "The token from an active user session" ) ], "responseMessages": [ ( "code": 200, "message": "json (balance => "user_balance")" ), ( "code": 400, "message ": "json with error "not logged in"" ) ], "notes": "", "authorizations": () ) ] ), ( "path": "/user/login", "operations": [ ( "method": "POST", "summary": "Logs user in the system", "nickname": "loginUser", "type": "string", "parameters": [ ( "paramType": "form", 'name': 'email', 'type': 'string', 'required': true, 'allowMultiple': false, 'description': 'The user email for login' ), ( "paramType": "form", "name": "password", "type": "string", "required": true, "allowMultiple": false, "description": "The password for login in clear text" ) ], "responseMessages": "code": 200, "message": "json with session_id, user_id, user_balance" ), ( "code": 400, "message": "json with error "no user with given email and password") ), ( " code": 400, "message": "json with error "invalid input"" ), ( "code": 400, "message": "json with error "no post request"" ) ], "notes": "" , "authorizations": () ) ] ), ( "path": "/user/logout", "operations": [ ( "method": "POST", "summary": "Logs user out", "nickname") : "logoutUser", "type": "string", "parameters": [ ( "paramType": "form", "name": "sessionToken", "type": "string", "required": true, " allowMultiple": false, "description": "The token from an active user session" ) ], "responseMessages": [ ( "code": 200, "message": "json (result => "deleted")" ), ( "code": 400, "message": "json with error "no user_session with given sid"" ), ( "code": 400, "message": "json with error "invalid input"" ), ( "code ": 400, "message": "json with error "no post request"" ) ], "notes": "", "authorizations": () ) ] ), ( "path": "/user/messages/( sessionToken)", "operations": [ ( "method": "GET", "summary": "Gets new messages", "nickname": "getUsermessages", "type": "string", "parameters": [ ( "paramType": "path", "name": "sessionToken", "type": "string", "required": true, "allowMultiple": false, "description": "The token from an active user session" ], "responseMessages": [ ( "code": 200, "message": "json (messages => "user_messages")" ), ( "code": 400, "message": "json with error" not logged in "" ) ], "notes": "", "authorizations": () ), ( "method": "GET", "summary": "Gets messages paged", "nickname": "getUsermessagesPaged", "type" : "string", "parameters": [ ( "paramType": "path", "name": "sessionToken", "type": "string", "required": true, "description": "The token from an active user session" ), ( "paramType": "query", "name": "numMessages", "type": "string", "required": true, "description": "number messages on page (numMessages & pageNr не звільняється, якщо не вистачає)) ), ( "paramType": "query", "name": "pageNr", "type": "string", "required": true, "description": "pagenumber ( numMessages & pageNr are ignored if not both are set)" ) ], "responseMessages": [ ( "code": 200, "message": "json (messages => "user_messages")" ), ( "code": 400 , "message": "json with error "не входить в"" ) ], "notes": "", "authorizations": () ) ] ), ( "path": "/user/userdata", "operations" : [ ( "method": "POST", "summary": "Posts userdata", "nickname": "postUserdata", "type": "string", "parameters": [ ( "paramType": "form", "name": "sessionToken", "type": "string", "required": true, "allowMultiple": false, "description": "The token from an active user session" ), ( "paramType": "form ", "name": "password", "type": "string", "required": false, "allowMultiple": false, "description": "new password" ), ( "paramType": "form", " name": "address", "type": "string", "required": false, "allowMultiple": false, "description": "new address" ), ( "paramType": "form", "name": "housenr", "type": "string", "required": false, "allowMultiple": false, "description": "new housenr" ), ( "paramType": "form", "name": "zip" , "type": "string", "required": false, "allowMultiple": false, "description": "new zip" ), ( "paramType": "form", "name": "city", "type ": "string", "required": false, "allowMultiple": false, "description": "new city" ), ( "paramType": "form", "name": "email", "type": " string", "required": false, "allowMultiple": false, "description": "new email" ) ], "responseMessages": [ ( "code": 200, "message": "json (user => "userdata ")" ), ( "code": 400, "message": "json with error

    Здається, що помилка, що мій swagger-ui не надсилає жодних параметрів запиту? Ось приклад з одним параметром query-param, sessionToken: (контролюється FireBug 2.0.6)

    GET /ias/public/user/balance HTTP/1.1 Host: localhost User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:33.0) Gecko/20100101 Firefox/33.0 Accept: application/json Accept-Language en-US;q=0.7,en;q=0.3 Accept-Encoding: gzip, deflate Content-Type: http://localhost/ias/swagger/ Cookie: __utma=111872281.581414660.1376736 55; uvts=sB5Dda3cZBNdaTk; searchpanel-close=set Connection: keep-alive

    Відповідь була:

    HTTP/1.1 400 Bad Request Date: Tue, 25 Nov 2014 14:58:20 GMT Server: Apache/2.4.9 (Win32) PHP/5.5.12 X-Powered-By: PHP/5.5.12 Content-Length: 25 Connection: close Content-Type: application/json; charset=utf-8

    Відповідь була вірною, тому що не було передано sessionToken.

    Це вимагає роботи, але це не походить від swagger-ui:

    GET /ias/public/user/balance?sessionToken=HTTP/1.1 Host: localhost User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:33.0) Gecko/20100101 Firefox/33.0 Accept: text/html,application/ xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: de,en-US;q=0.7,en;q=0.3 Accept-Encoding: gzip, deflate Cookie: __utma=111872281.581414660 .1366700677.1394721873.1394723866.255; uvts=sB5Dda3cZBNdaTk; searchpanel-close=set Connection: keep-alive



    Подібні публікації