Send an integer into a server with GET method - mysql

I've been researching this problem for a while now and have been trying to use the POST method until recently when I figured out that the GET method will be sufficient for what I need to do.
My objective:
Take an integer from my app and send it into a php server to save it
For now, I just need to send one integer to get it working and to have a starting point to work from. Once I start getting the ball rolling and things start working, I will be sending maybe 20 integers maximum at a time, so I don't believe that I will have a problem with the data amount restrictions on the GET method.
I am working with a friend on this project right now because I am not as fluent in php, I have been exposed to it several times though, so I should know most of the terminology involved. ANYWAY, here is my php code that my friend wrote for me...
<?php
// A sample php file to demo passing parameters and getting POST data.
// This simply appends the specified value to the end of the 'sample' table.
// Call it like this: sample.php?val=4
// where 4 is the value you want to append to the table
// The code returns whether or not the sql query was performed with success or not.
// If successful, a boolean true (or 1) is returned.
// If not, then an error message is returned with the sql error.
include 'dbConnect.php';
$val = $_GET["val"]; // value to set to
$sql=
"INSERT INTO sample (`test`)
VALUES ('" . $val . "')
";
$result = mysql_query($sql,$con);
if(!$result){
die('Error: ' . mysql_error());
}
echo $val+1;
mysql_close($con);
?>
This code takes the sent value for the variable "val" and echoes that value plus one (so that the setting and the getting values are different from the site so I can more easily tell if my code works) This should work right?
Next, I believe I haven't quite finished the Xcode portion of the project yet, but I have a successful connection happening, I just haven't been able to change the value of the variable in the php server. In my project, I have an NSInteger variable called "num" and its value, set by the text field in my app, is the one I want to send in to the server. I also am using a button (called "postPressed") to initiate the function of the sending process. So here is my code...
NSURLRequest *request;
NSURLConnection *connection;
NSURL *url;
NSInteger num;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
- (IBAction)valueChange:(id)sender {
num = [_valueTF.text intValue];
}
- (IBAction)postPressed:(id)sender {
url = [NSURL URLWithString: [NSString stringWithFormat: #"http://jrl.teamdriven.us/source/scripts/2013/sample.php?val=%d", num]];
request = [NSURLRequest requestWithURL:url];
if (request) {
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
_returnLbl.text = #"success!";
}
}
My returnLbl does change to be "success", so I know the connection works, I just think I'm missing some code on the setting the variable part. Please help me out, this has been a thorn in my side for about a month now. Also, I apologize for the length of this question, I'm just trying to get in all the details so that there doesn't have to be any clarifications.

So, it turns out that my code worked the whole time, it's just that when I looked up the data table generated by phpMyAdmin, I did not happen to notice that there was a page two of data because I had tested it so much in my browser. The integers were sent and saved successfully with the code above. I apologize for posting something like this and finding out how dumb of a mistake it truly was, but if anyone would like to give me any kinds of improvements, I am open to them. Thank you for taking your time to view this question.

Related

Find call returning outdated info immediately after Save

In my application, an action takes some user generated input and uses it to update an entry in the database.
The relevant code resembles the following:
$this->Model->save($data);
$result = $this->Model->findById($id);
The problem is that the contents of $result are outdated. That is, $result contains the record as it was before the save.
I'm assuming that the entry just isn't updated until the function returns. However, I can't do the obvious
$result = $this->Model->save($data);
because this method does not preserve relationships. In this case, the model belongs to another model. I need to be able to get the updated record and the record it belongs to.
See if
$result = $this->Model->findById($id);
is loading from the cache, not the database.
Take a look at:
http://fredericiana.com/2007/09/05/cakephp-delete-cached-models-on-database-change/
http://snook.ca/archives/cakephp/delete_cached_models/
Personally, I've never liked Cake's magic find functions. I find them difficult to add extra conditions/joins/etc to and I much prefer to type a few more lines and get something specific that I can easily adjust.
Sounds in this case like the magic find function is returning from the cache, and you should try a regular find call instead:
$this->Model->save($data);
$result = $this->Model->find('first', array('conditions' => array('id' => $id)));
However, you should try and narrow down your problem and find out exactly what it is for future reference. You could try manually clearing the cache before you do your magic find and see if you get the correct response:
$this->Model->save($data);
Cache::clear();
$result = $this->Model->findById($id);
Another unlikely yet possible option is that your $id variable may not be pointing to the correct model row, and your save might be creating a new one so that when you findById($id) the $id is different to the ID of the row you've just saved/created. In this case, it's worth doing a debug($id) or $this->log('ID is: ' . $id, 'my_test_log'); before and after your safe or at intervals through your code to work out what is happening and where.

Accessing the Database Row of the Current User

I manually added fields to my "_User" table on Parse. Specifically, a Twitter Handle that is a string and has the key "TwitterHandle." For some reason, when I execute the following statement (and the Twitter Handle is non-null), I receive null:
NSLog(#"%#", [[PFUser currentUser] objectForKey:#"TwitterHandle"]);
Instead, I have to execute the following code, querying the backend to find the current user's fields, and their twitter handle specifically, which seems redundant and overly complicated:
PFUser *currentUser = [PFUser currentUser];
PFQuery *query = [PFQuery queryWithClassName:#"_User"];
[query whereKey:#"username" equalTo:currentUser.username];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
// do some stuff here with the current user's row in the User table, the only object in
// the NSArray of *objects
NSLog(#"%#", [[PFUser currentUser] objectForKey:#"TwitterHandle"]); --> (non-null)
}];
Is it because of the way I set up the field, manually? Otherwise, I'm not sure why my code is exhibiting this behavior.
The currentUser object is populated at login and cached, if the data is changing you will need to fetch the latest copy:
[[PFUser currentUser] fetchInBackground];
As mentionned by Timothy [[PFUser currentUser] fetchInBackground]; will get new column at the expense of a request to Parse.
However, while developping, Logout from the app and log back in. This will clear the cache and retrieve all USER info.

How to manage many openAsync() calls in a big Flex application?

I used openAsync() function many times in my application to open SQLite connection with a success. But lately I added more code that also uses openAsync() and now I obtain this error:
Error: Error #3110: Operation cannot be performed while SQLStatement.executing is true.
at Error$/throwError()
at flash.data::SQLStatement/checkReady()
at flash.data::SQLStatement/execute()
at Function/com.lang.SQL:SQLErrorStack/deleteAllRecordsFromErrorStackTable/com.lang.SQL:connOpenHandler()[C:\work\Lang\trunk\actionscript\src\com\lang\SQL\SQLErrorStack.as:466]
It looks like the previous code didn't finish executing while another has started.
My question is: Why the execution of code in the second connection was rejected? I expected that some kind of a queue mechanism is used but it isn't. I looked everywhere for a solution how to cope with this problem but I failed. Can you help?
Can one opened DB connection solve the problem? What changes to my code should I apply then?
This is the code similar to this, that appears a few times in my application.
var SQLquery:String;
SQLquery = "DELETE FROM ErrorStackTable";
var sqlConn:SQLConnection = new SQLConnection();
sqlConn.addEventListener(SQLEvent.OPEN, connOpenHandler);
var dbFile:File = new File();
dbFile.nativePath = FlexGlobals.topLevelApplication.databaseFullPath_conf+"\\"+FlexGlobals.topLevelApplication.databaseName_conf;
sqlConn.openAsync(dbFile); // openDB
sqlSelect = new SQLStatement();
sqlSelect.sqlConnection = sqlConn;
sqlSelect.text = SQLquery;
function connOpenHandler(event:SQLEvent):void
{
sqlSelect.addEventListener(SQLEvent.RESULT, resultSQLHandler);
sqlSelect.addEventListener(SQLErrorEvent.ERROR, errorHandler);
sqlSelect.execute();
}
In Big Flex Applications Try To Avoid openAsync(db) calls because of the reusablity of the SQL code , if u have many sql statments to be executed then you should define more and more sql statments . and if you have dynamic result [Array] getting from web service (RPC ) then you will surely get an error although it is successful Execution and array insertion in the database will be fail .. Just Look at
the link Click Here You Will Get your answer
I just changed conn.openAsync(db); to conn.open(db); and it worked
Thanks

How can i reduce load on browser?

I am using multiple databases on cloud and css framework twitter bootstrap to grab the suggession on textfield using "typeahead" with ajax.
now on every keyup event one ajax call get fire and fires a query as below:
public function prod_identifier_typeahead($value) {
$db = ConnectionManager::getDataSource('incident_mgmt');
$list = $db->rawQuery('select id, identifier from products where identifier like "'.$value.'%";');
$options = array();
while ($row = $db->fetchRow()) {
$options[] = array('id' => $row["products"]["id"],'name' => $row["products"]["identifier"]);
}
$this->set('options', $options);
$this->set('_serialize', 'options');
}
Every ajax call uses the connection object .Now, Can anyone help me to reduce load on this ajax call query processing ?
Cake has caching which can be used to store data that has been retrieved from the database. Thus duplicate requests will not hit the database, however, you need to be careful that you don't fill your cache with data that will never be used again.
I would try to optimize for common usage patterns. For example, a user types 'abdc', hits backspace twice, then types 'cd'. In this case, you'll get a cache hit on 'ab' and 'abd' almost immediately but 5 minutes later its probably safe to clear everything associated with this query.

Get Facebook Status from Fan Page using API

I've been trying to get the most recent Facebook Status for a fan page via the API for a while now and can't seem to get what I'm after. I'm really trying to avoid using RSS for it. I can get the full list from the feed via https://graph.facebook.com/174690270761/feed but I want only the last status posted by the page admin, not by anyone else.
Is their an easy way to get it without having to authenticate?
Thanks in advance
edit:
https://graph.facebook.com/174690270761/statuses seems to be what I'm looking for but I need an OAuthAccessToken for this but can't see how to without involving the user, as I'm trying to access through my own credentials/application
Facebook has changed the api and now requires you to provide an access token.
You can use Facebooks PHP sdk for that but i found a much quicker way to go:
<?
$appid = '1234567890';
$secret = 'db19c5379c7d5b0c79c7f05dd46da66c';
$pageid = 'Google';
$token = file_get_contents('https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id='.$appid.'&client_secret='.$secret);
$feed = file_get_contents('https://graph.facebook.com/'.$pageid.'/feed&'.$token);
print_r(json_decode($feed));
?>
Update 15/12/12
app access tokens nosist of the id and secret now - use this request:
$feed = file_get_contents('https://graph.facebook.com/Saxity/feed?access_token='.$appid.'|'.$secret);
I finally found out that this doesn't have to be done through the API, or require any authentication at all.
Basically you can access the data via a JSON feed:
$pageID = "ID of Page" //supply the Id of the fan page you want to access
$url = "https://graph.facebook.com/". $pageID ."/feed";
$json = file_get_contents($url);
$jsonData = json_decode($json);
foreach($jsonData->data as $val) {
if($val->from->id == $pageID) { //find the first matching post/status by a fan page admin
$message = $val->message;
echo $message;
break; //stop looping on most recent status posted by page admin
}
}
I don't think there's a good way to do this. You can process the JSON pretty easily though from the looks of it. You can limit the number of results by using the since query parameter. For instance:
https://graph.facebook.com/174690270761/feed?since=last%20Monday
You can also use limit on that, but I don't think that filters by user. If the administrator is the only one allowed to post, then you may be able to get away with using limit=1.