PHP - Rest Api Responses When Deleting Records
I have the following tables: department id course id department_id CASCADE DELETE student id student_courses course_id CASCADE DELETE student_id CASCADE DELETEI also have the following REST API endpoints: DELETE department/123 (deletes targeted department and associated courses as well as the list of students in the course) DELETE course/321 (deletes targeted course as well as the list of students in the course) DELETE student/111 (deletes targeted student as well as the list of students in the course)The user should be informed before deleting a given record if that record will affect other tables. For instance, if deleting a department which has some courses or deleting a student which belows to a course. One option is to respond to DELETE department/123 with 400 {recordUsed: {courses:[bla, bla], student_courses:[bla, bla]}} if used. For this option, the client would then prompt the user of the implications and if desired repeat the request but include a "force" parameter of TRUE in the request which will delete the record regardless of being used. Another option is to add some new endpoints which will return the resources which are associated with the to be deleted entity. If empty, a DELETE request would automatically be made and if not empty the user will first be prompted whether the DELETE request should be made and the server would delete the record(s) regardless of being used. GET department/utilized/123 GET course/utilized/321 GET student/utilized/111Any thoughts on which approach should be used? Or maybe some other strategy? Thanks Similar TutorialsThis topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=355218.0 I have a bad way with words, so if the title doesnt make much sense nor my post, I apolagize! But I am using a while loop and mysql_fetch_array to echo all information in a table in mysql. With each entry, I have included a button that executes a delete query for that entry. Code: [Select] $delquery="DELETE FROM requests WHERE user = '".$row['user']."'"; mysql_query($delquery,$link2); echo "<font size='19px' color='#009933'>User deleted from request database.When I click the button, the message is echod in every entry listed on the page, and nothing happens. I figured Id use delete from the username, so that way mysql will know which one to delete... but Idk when I think about it thats dumb and makes no sense. Im stuck. This side of the application im trying to make is the admin side where I can process requests. After I process the request I delete it from the database so I know I processed it. I have no idea what query to use for this. Anybody know how I could do this? Thanks Hello All, running into a situation that I have not seen before. I have been seeing in multiple areas of my application that the response received from the server has 2 JSON responses in it. Here is a sample function: private function getCatalogItems(){ $start = ($_REQUEST["start"] == null)? 0 : $_REQUEST["start"]; $count = ($_REQUEST["limit"] == null)? 20 : $_REQUEST["limit"]; $q = "SELECT c.`id`, c.`catalog_number`, c.`long_description`, CONCAT(c.`catalog_number`, ' - ', c.`long_description`) AS `display` FROM catalog c"; if(!empty($_REQUEST['query'])){ $q .= " WHERE c.`catalog_number` LIKE '%".$_POST['query']."%'"; } $q .= " ORDER BY c.`catalog_number` ASC LIMIT ".$start.",".$count; $rs = $this->db->get_results($q); $total = $this->db->num_rows; $buff = '{"total":"'.$total.'","data":'.json_encode($rs).'}'; $this->c->returnJSON($buff); } The "returnJSON" function looks like this. public function returnJSON($json){ $contentType = "application/json; charset=utf-8"; header("Content-Type: {$contentType}"); header("Content-Size: " . strlen($json)); echo $json; } As you can see this simply sets the headers of the response. It has been a real head scratcher. Anyone come across something like this before? I am having trouble showing reports for a given date range. Currently if I specify something like 11/03/2010 to 11/05/2010 I get results for all years within that month and day such as I may get results for 11/03/2008 11/03/2009 11/03/2010 11/04/2008 11/04/2009 11/04/2010 11/05/2008 11/05/2009 11/05/2010. I am using the following code $result = mysql_query("SELECT * FROM report WHERE date>='$date_begin' and date<='$date_end' ORDER BY 'date'",$db); I use the following format in my date feild mm/dd/yyyy My script is finally working as intended, but I want to add some additional data results. I am trying to resolve how I can display a count of ONLY the records updated by my query: // START :: Query to replace matches mysql_query("UPDATE orig_codes_1a AS a JOIN old_and_new_codes_1a AS b ON concat(a.orig_code_1, a.orig_code_2) = concat(b.old_code_1, b.old_code_2) SET a.orig_code_1 = b.new_code_1, a.orig_code_2 = b.new_code_2") or die(mysql_error()); // END :: Query to replace matches In this query I count ALL records selection: // START :: Create query to be displayed as final results of original codes table. $result = mysql_query("SELECT * FROM orig_codes_1a") or die(mysql_error()); I want to display a count on this part of the query: ....concat(a.orig_code_1, a.orig_code_2) = concat(b.old_code_1, b.old_code_2).... I am using Guzzle as a HTTP client, and the following script results in the following error: $response = $this->httpClient->request('GET', "http://$this->host:$this->port/query", ['query' => $data]); $body = $response->getBody(); $rs=json_decode($body, true); Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 136956008 bytes) in /var/www/vendor/guzzlehttp/psr7/src/Stream.php on line 80 What are the work arounds? Instead of trying to convert it into an array all at once, how can I do so in pieces? I know the expected format so it seems I will need to read just the appropriate amount of bytes and then decode parts at a time. Seems like a pain. Are there any classes designed to do so, or can any of the following Guzzle built in methods be used? Thanks Guzzle Response methods: __construct getStatusCode getReasonPhrase withStatus getProtocolVersion withProtocolVersion getHeaders hasHeader getHeader getHeaderLine withHeader withAddedHeader withoutHeader getBody withBodyGuzzle Body methods: __construct __destruct __toString getContents close detach getSize isReadable isWritable isSeekable eof tell rewind seek read write getMetadataHow to make a form using HTML/PHP with conditional responses based on zip code? What I want to do exactly... zip codes 91900-92600 go to URL www.example.com after submit. All others go to URL www.example.com/page after submit. Any help would be much appreciated. Hi everyone... I would like to implement a questionnaire/survey system that has only two Answers (Yes /No). Basically, this questionnaire system will be widely used on Mobile Phones. It will be looking something like this below: http://awardwinningfjords.com/2009/06/16/iphone-style-checkboxes.html Lets say a user selects a response as No (Using the above slider button for a question). That response should be recorded in the database with User Details + Time Stamp. Also, I would like to generate a report for each question (Responses of Multiple Users) and a report at a User Level for the entire questionnaire/survey (s). Can some one guide me the fastest & easiest way to achieve this? I'm a new learner of PHP. Regards Sandeep Hi guys. I'm new to php and struggleing with the REST POST for some reason.... I need to insert a contact into this accouting system http://help.saasu.com/api/#toc-http-post search for Example: Insert Contact. the data strcutre looks like: Code: [Select] <?xml version="1.0" encoding="utf-8"?> <tasks> <insertContact> <contact uid="0"> <salutation>Mr.</salutation> <givenName>John</givenName> <familyName>Smith</familyName> <organisationName>Saasy.tv</organisationName> <organisationAbn>777888999</organisationAbn> <organisationPosition>Director</organisationPosition> <email>john.smith@saasy.tv</email> <mainPhone> 02 9999 9999 </mainPhone> <mobilePhone> 0444 444 444 </mobilePhone> <contactID>XYZ123</contactID> <tags>Gold Prospect, Film</tags> <postalAddress> <street>3/33 Victory Av</street> <city>North Sydney</city> <state>NSW</state> <postCode>2000</postCode> <country>Australia</country> </postalAddress> <otherAddress> <street>111 Elizabeth street</street> <city>Sydney</city> <state>NSW</state> <postCode>2000</postCode> <country>Australia</country> </otherAddress> <isActive>true</isActive> <acceptDirectDeposit>false</acceptDirectDeposit> <directDepositAccountName>John Smith</directDepositAccountName> <directDepositBsb>000000</directDepositBsb> <directDepositAccountNumber>12345678</directDepositAccountNumber> <acceptCheque>false</acceptCheque> <customField1>This is custom field 1</customField1> <customField2>This is custom field 2</customField2> <twitterID>Contact twitter id</twitterID> <skypeID>Contact skype id</skypeID> </contact> </insertContact> </tasks> I only have to insert 3 mandatory fields whcih are in the below code snipit im using but nothings working... Code: [Select] //set POST variables $service_url = 'https://secure.saasu.com/webservices/rest/r1/tasks?wsaccesskey=<key removed>'; $curl = curl_init($service_url); $fileds = array( 'insertContact' => array( 'contact' => array( 'givenName' => urlencode('John'), 'familyName' => urlencode('Smith'), 'organisationName' => urlencode('Saasy.tv') ) ) ); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data); $curl_response = curl_exec($curl); curl_close($curl); $xml = new SimpleXMLElement($curl_response); Please help, I'm not sure what I'm doing wrong.... Here is the scenario. I created a niche market API which provides environmental data. The data is obtained by industrial controllers which don't monitor anything by default, and the API has additional endpoints which are used to instruct the industrial controllers to start monitoring some parameter so the API can then start storing the trend data. The API primarily responds with JSON, however, a couple of endpoints support CSV data. For humans/webclients to access the data, I also created a webserver application which can be added to a Concrete5 (C5) CMS. I tried to make as many of its endpoints do nothing except receive the webclient's request, add a JSON Web Token to it which contains a unique identifier, forward it to the API using cURL, and return the response as is to the webclient. To limit the scope which needed to be created for the C5 application, the API has endpoints to return JSON which is used by JavaScript on the webclient for client-side validation, endpoints (actually, a different domain) to return static JavaScript/CSS/etc, and endpoints to restructure the JSON data to some more suitable format. I now am looking at creating different applications which does not use C5, but either are 100% custom or use some other CMS such as Drupal, etc. While I tried to limit the scope implemented on the C5 application, I have much more than I desire and will need to duplicate much for any future application. The primary scope I would like to remove from the webserver application relates to the HTML views and consists of templates which create HTML from JSON, the JavaScript which interacts with the HTML, and to a lesser degree controllers to determine the type of view (i.e. a list of records or one specific detail record). While the API will only be managed by myself, the intent is that the C5, 100% custom, etc webserver apps are installed and managed by others. Ideally, there is some existing Composer package for transforming JSON to HTML which is CMS agnostic, however, I don't know whether such exists. Also, while not 100% necessary, ideally this functionality could exist on my server and not the individual web application's server. Whether I build it myself or use some existing package, I expect it will need to do something like the following: The various webserver apps will have some routing table to proxy the request either to my JSON API server (complete) or my new "HTML API Server" (remaining discusses this portion). This HTML API server would generate the content either by making a cURL request to the main JSON API, or better yet since likely located on the same server have routing functional to make direct calls to the JSON API's methods, and return something like the following: { "html": "<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Pharetra massa massa ultricies mi quis hendrerit dolor. Leo integer malesuada nunc vel risus commodo viverra.</div>", "javascript_files": [ "https://resources.myserver.com/someFile.js", "https://resources.myserver.com/someOtherFile.js" ], "css_files": [ "https://resources.myserver.com/someFile.css", "https://resources.myserver.com/someOtherFile.css" ] } The various applications would then take the HTML and resource files and insert them using their proprietary methods. EDIT. Also, thinking of using an IFRAME, however, definitely have concerns with doing so. My day job has nothing to do with software, however, am hoping to make it so. Before embarking on this task, I would like to know whether some existing framework exists and if not what general strategy (organization, caching, etc) I should take to develop it. Thanks Edited January 18 by NotionCommotionAdded IFRAME idea I want to create a REST API for my website. What I want to do is to display advertisements from my database on websites that I sell to clients. Their website will call my database for advertisements to display on their websites. Also, I am performing a site validity check where the client's site would send the site URL, site name, and site token to my database for validation. If it returns false then the site will not display as it will be invalid according to my database. I've been Googling this topic all day, but cannot seem to get my head around it. I want to set an API key on my website so that not just anybody can be querying my database. For the advertisement query, no parameters need to be sent from the client websites to my database. Can anyone offer some advice on how to do this? <?php $myData = file_get_contents(""); $myObject = json_decode($myData); $myObjectMap = $myObject->result; ?> can i somehow build in that it only request every 5 minutes because if there are many users on the site it request too much? Hi, I have used the following script to consume REST webservices provided by Commission Junction. I'm able to get the response but the response is not in xml format. <?php $targeturl="https://support-services.api.cj.com/v2/countries"; $CJ_DevKey= "xxxxxxxxx"; // return xml feed from CJ $ch = curl_init($targeturl); curl_setopt($ch, CURLOPT_POST, FAlSE); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: '.$CJ_DevKey)); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); $response = curl_exec($ch); curl_close($ch); echo $response; // will print in browser all country codes in an xml format /* ADD YOUR OWN CODE HERE TO DO WHAT YOU WANT WITH THE RESPONSE. MAYBE SAVE RESULTS TO A FILE OR THE PARSE THE RESULTS INTO A DATABASE? */ ?> I'm just confused. Isn't that the response when using REST webservices is always in xml format. Please correct me if I'm wrong. Would someone please have a look at this script and suggest me what I need to do in order to get the response in xml ? I want to save the response in xml file and then process it later. please see my current sample output here. www(dot)uedeals(dot)com/cj/cj3.php Do you use the OS userids or do you keep them separate in MYSQL? Must users login to a website and request a token to use for REST API requests? Did you use a framework provided method? I need something ultra-simple I tried to find working tutorial for REST API and with these two frameworks but nothing what i found worked.Basicly i want to attach REST API
to a simple CRUD application.
So if anyone have links with good explanation that would be good.
I actually have two parts to this post. One which describes just my understanding on how a multipart request should look with a REST API and gives a little context, and the second how to actually implement it using Sympony and api-platform. Part 1 Looking to simultaneously upload a file, some file meta data, and identifier of the uploading user to a REST API, and will do so using a multipart request. Based on swagger, looks like the request should look something like the following: POST /upload HTTP/1.1 Content-Length: 428 Content-Type: multipart/form-data; boundary=abcde12345 --abcde12345 Content-Disposition: form-data; name="id" Content-Type: text/plain 123e4567-e89b-12d3-a456-426655440000 --abcde12345 Content-Disposition: form-data; name="address" Content-Type: application/json { "street": "3, Garden St", "city": "Hillsbery, UT" } --abcde12345 Content-Disposition: form-data; name="profileImage "; filename="image1.png" Content-Type: application/octet-stream {…file content…} --abcde12345-- Background noise... The above example shows three parts which include the text ID, JSON address and octet-stream file. Doing so doesn't make sense to me and I will probably just have two parts for the meta data JSON. Note that potentially, I will be removing the user from the JSON payload and including it in some JWT header. Also, showing resources as links such as /api/users/1 in the request and response JSON is new to me, but I guess makes sense. Regardless, my meta data JSON will look like: { "projectId": 1234, "documentDescription": "bla bla bla", "specification": "230903.2.4.D", "user": "/api/users/1" } and the response will look like: { "projectId": 1234, "documentDescription": "bla bla bla", "specification": "230903.2.4.D", "uploadAt": "2021-01-27 08:41:17", "fileName": "pressuresensor.pdf". "user": "/api/users/1". "file": "/api/uplodaed_files/1234" } Am I somewhat going down the right path? Part 2 Wow, should have looked into Sympony before now! Entities, validation, the API, etc were a breeze. Still confused with some of the "magic", but understanding what is under the hood more and more. As stated initially, I am utilizing api-platform and am looking at api-platform's file-upload. I guess the first question is whether my POST request with both the file and JSON meta data can be performed in a single request. Per making-a-request-to-the-media_objects-endpoint: QuoteYour /media_objects endpoint is now ready to receive a POST request with a file. This endpoint accepts standard multipart/form-data-encoded data, but not JSON data. What? Am I reading this correct? Do I first need to make a multipart requests using either a standard HTML form or a XMLHttpRequest which just sends the file, receive the document locator, and then send a second request with the location and my meta data? If so, I guess I have enough to go forward. I would rather, however, perform the work in a single request. My previous mentioned swagger multipart-requests shows both in the same request. symfonycasts's api-uploads also describes doing so, but not with api-platform. Is there a way to do so with api-platform? Does it make sense to use api-platform for all other routes but then make a custom route for document with meta data uploads? Any recommendations are much appreciated. Thanks I implemented an endpoint which receives name/value pairs: PUT someresource/123 {"name": "description", "value": "Some new description"} I think I made a mistake, and should have implemented it as: PUT someresource/123 {"description": "Some new description"} The reason I think so is updating multiple properties is only (easily) possible using the later: PUT someresource/123 {"description": "Some new description", "otherProperty": "bla bla bla"} Assuming I am not using some 3rd party client library which only works with name/value pairs, any compelling reason why one shouldn't default to the later approach with key/values? Hi, I am using the Google map API to display some businesses on a map - the sequence is map and below it a list of the establishments from a DB. Before I put the google map in, the list of establishments in the while table loop worked correctly. Now the map is there - that works, but the looping table doesnt display - I feel that it may be something to do with Code: [Select] <?php while ($row = mysql_fetch_array($result2, MYSQL_ASSOC)) { ?> new google.maps.LatLng(<? echo $row['latitude'] ?>, <? echo $row['longitude']?>), <?php ; } ?> and the second fetch array - Code: [Select] while ($row = mysql_fetch_array($result2, MYSQL_ASSOC)) Any Advice? Code: [Select] <?php // *******************************below is bit that selects hotels based on outcode of postcode and prints table with links to details pages $sql2 = "SELECT * FROM hotels WHERE (SUBSTRING_INDEX(est_postcode, ' ', 1)) IN ('$matches') "; $result2 = mysql_query($sql2) or die('query failed: ' . mysql_error()); $num_rows = mysql_num_rows($result2); echo "<p> Your search has found ".$num_rows . " establishment(s) </p>"; ?> <script type="text/javascript"> var berlin = new google.maps.LatLng(<? echo $lat2 ?>, <? echo $lng2 ?>); var neighborhoods = [ <?php while ($row = mysql_fetch_array($result2, MYSQL_ASSOC)) { ?> new google.maps.LatLng(<? echo $row['latitude'] ?>, <? echo $row['longitude']?>), <?php ; } ?> ]; var markers = []; var iterator = 0; var map; function initialize() { var mapOptions = { zoom: 12, mapTypeId: google.maps.MapTypeId.ROADMAP, center: berlin }; map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions); } function drop() { for (var i = 0; i < neighborhoods.length; i++) { setTimeout(function() { addMarker(); }, i * 200); } } function addMarker() { markers.push(new google.maps.Marker({ position: neighborhoods[iterator], map: map, title:"Hello World!", draggable: false, animation: google.maps.Animation.DROP })); iterator++; } </script> <div id="map_canvas" style="width: 614px; height: 400px;">map div</div> <button id="drop" onclick="drop()">Drop Markers</button> <?php echo "<table id ='results' border=0>"; while ($row = mysql_fetch_array($result2, MYSQL_ASSOC)) { echo "<tr>"; echo "<td><a class='blueboldtitle' href='bandb.php?id=". $row["id"] . "'>" . ucwords(strtolower($row["est_name"])) ."</a></td><td>" . $row["est_postcode"] ."</td><td> ". $row["est_areacode"]." ". $row["est_landline"] ."</td><td><a href='bandb.php?id=". $row["id"] . "'>[More Info] </a></td>"; echo "</tr>"; } echo "</table>"; ?> Specific question with general application here. i am having some trouble with a loop and am getting some odd timing results specifically this is a WMI query on a hyper-v server retrieving disk information but im not sure the context of the query is relevant here. The main question is how come the first iteration of the loop is so much slower than the other iterations, it just doesnt seem to make sense to me unless ive done something stupid here i cannot see. any ideas ? Code: [Select] <?php $diskstart = microtime(true); // get the hard disk size try { $resultDisk = $wmi->ExecQuery("SELECT BlockSize,NumberOfBlocks FROM msvm_LogicalDisk where systemname like '%" . $guid . "%' and name='Hard Disk Image'"); $ct=0; $start1 = microtime(true); $start = microtime(true); foreach($resultDisk as $itemDisk) { $end = microtime(true); echo "<BR>FOREACH: [" . Round($end-$start,3) . "] seconds"; $vm[$name]['disks'][$ct] = ($itemDisk->BlockSize * $itemDisk->NumberOfBlocks)/1024; // format the disk size into KB $ct++; $start = microtime(true); } $end1 = microtime(true); echo "<br> ALLLOOP: [" . Round($end1-$start1,3) . "] "; } catch(exception $e) { } $diskend = microtime(true); echo "<br>DISK: [" . ($diskend-$diskstart) . "] seconds"; ?> and here are the results Code: [Select] FOREACH: [1.236] seconds FOREACH: [0.001] seconds FOREACH: [0.001] seconds FOREACH: [0.001] seconds FOREACH: [0.002] seconds FOREACH: [0.001] seconds FOREACH: [0.001] seconds FOREACH: [0.001] seconds FOREACH: [0.001] seconds FOREACH: [0.001] seconds FOREACH: [0.001] seconds ALLLOOP: [2] DISK: [2.1837468147278] seconds |