Compare a String-Value to a MySQLi Database-Value (VarChar/BigInt..) - java

I need to receive all entries from a MySQLi database with a certain value (in my case: The Facebook-ID).
First im sending the value which im searching for in the database (fb_id):
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("fb_id", fb_id));
JSONObject json = jParser.makeHttpRequest(url_your_events, "GET", params);
Receiving it in PHP:
if (isset($_GET['fb_id'])) {
$fb_id = $_GET['fb_id'];
Then having the query:
$result = mysqli_query($con, "SELECT * FROM UserEvents WHERE fb_id == $fb_id");
I already used different types for the fb_id column. BigInt (the ID would not fit in normal int) and VarChar do not work - i'm not getting any results.
How do i get the query to work properly?
I'm grateful for any advice!
EDIT:
I also tried different comparisons in the query: = / == / === but none worked.

Related

Script in Groovy to update and insert Initial_Range and Final_Range

Im new on Groovy and need some help.
I have that table called RANGE with :
ID_RANGE - Integer
Year - Integer
six_Month - Integer
Initial_Range - String
Final_Range - String
Last_Update - TimeStamp
I have to do a script to update/insert Initial_Range and Final_Range.
I will receive the new data from a map called "df_map" with the following data:
df_map.Update_date -> String
df_map.six_Month -> Integer
df_map.Initial_range -> String (Format "AA-123456678")
df_map.Final_range -> String (Format "AA-123456678")
That script have to validate some requirements,
if it doesn't, it can´t continues:
the date have to be a valid timeStamp (yyyy-MM-dd HH:mm:ss.SSS)
there must be 1000 values ​​between Initial_Range and Final_Range
Only can update or insert a future date
When check all this, have to search if the register to modify exits, if not exits, have to create it.
that script has helpers to do 2 actions:
sqlQuery -
Make a query against the bbdd and show and array with the data. It get parameters like bbdd,query and parameters maps.
EXAMPLE:
query = "SELECT * FROM RANGE WHERE ID_RANGE = :RANGE"
params = [:]
params.RANGE = 1
outcome = sqlQuery(bbdd,query,params)
-sqlUpdate -
It make an insert or an update against the database and returns an array with the result. It receives as parameters the database, query, parameter map.
EXAMPLE:
query = "UPDATE RANGE SET Initial_Range = :Initial_Range WHERE ID_RANGE = :RANGE"
params = [:]
params.RANGE = 1
outcome = sqlUpdate(bbdd,query,params)
I work with sql but never before with groovy.....
Thanks in advance ;)

java.lang.String can't be converted to JSONObject

I've got a database which I use in my android app (accounts).
I want the user to be able to change his/her password.
I'm using java, mySQL, PHP and JSON.
The username needs to be updated by their id, I just created the code to do this but I get an error...: "Error parsing data org.json.JSONException: Value < br>< table of type java.lang.String cannot be converted to JSONObject".
Here are some lines of code, I use:
PHP
$query = "UPDATE users SET username = :username WHERE id = :id";
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
I also need to check if the username is succesfully updated, but I'll do that later.
I just use:
$response["success"] = 1;
$response["message"] = "Username is succesfully changed!";
die(json_encode($response));
JAVA
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
id = sp.getInt("id", 1);
EditText newUsername = (EditText)findViewById(R.id.etNewUsername);
username = newUsername.getText().toString();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", Integer.toString(id)));
params.add(new BasicNameValuePair("username", username));
Log.d("request!", "starting");
JSONObject json = jsonParser.makeHttpRequest(url, "POST", params);
Log.d("After updating username", json.toString());
But the Tag: "After updating username" doesn't appear after the error in the LogCat.
So I know the error is within the HttpRequest.
Maybe it's the id? Because it will be converted to a String and in the database the id is an integer?
Every help will be appreciated!
Thanks.
Error parsing data org.json.JSONException: Value < br>< table of type java.lang.String cannot be converted to JSONObject
Notice the value- "<br> <table". You're trying to treat HTML as JSON. That doesn't work, so the JSONParser is throwing an exception. You don't catch the exception, so you crash.

send String[] b httprequest and get in php b $_GET

I want to send a String[] by an HTTP request and get the values in PHP with the $_GET method.
The total number of values in the String[] is variable.
I have tried so far:
List<NameValuePair> params = new ArrayList<NameValuePair>();
String[] dropdowns = {"1st item","2nd item","3rd item","4th item"};
for (int i = 0; i < dropdowns.length; i++) {
params.add(new BasicNameValuePair("pid", dropdowns[i]));
}
In PHP I want to get all values and query based on them.
$pid = $_GET['pid'];
And use them like:
$result = mysql_query("SELECT *FROM Apps WHERE pid[0] = $pid" AND pid[1] = $pid"
AND ...);
But I know this way is wrong.
How can I do that?
This
$result = mysql_query("SELECT *FROM Apps WHERE pid[0] = $pid" AND pid[1] = $pid" AND ...);
Is very wrong and unsafe. (Columns wrong syntax, SQL injection, wrong quotation, wrong SQL syntax,...)
Must be something like
$result = mysql_query("
SELECT * FROM Apps WHERE pid
IN(" . implode(',', mysql_real_escape_string($pid)) . ")
");
You can create a serialized reprezentation of the values you want to send in the url. It has limitations such as the max length of the url.
'http://domain.com/data_handler.php?data=' . urlencode(serialize($array1));
Getting back your array:
$array1 = unserialize($_GET['data']);
Its even better to create a post request and use this syntax:
pid[]=1
pid[]=2
http://www.php.net/manual/en/faq.html.php
You cannot send an array through HTTP request UNLESS you have an array of inputs such as:
<input type='text' name='manyOfThese[]' />
To send an array you have two options. One is to use serialize() and unserialize() to turn your array into a string. And the other is to use session variables:
$_SESSION['pid'] = $pid;
Then on the next script
$pid = $_SESSION['pid'];
unset($_SESSION['pid']);
foreach($pid as $element){
echo $element //or do whatever you need to do to that variable
}
Also at the beginning of your scripts you will want to include:
session_start();
And then when your php application is exited (upon logoff for example):
session_destroy();
There are two parts to this and both involve loops. First, when you are sending the data, put the brackets in the name to send it as an array:
for (int i = 0; i < dropdowns.length; i++) {
params.add(new BasicNameValuePair("pid[]", dropdowns[i]));
}
Second, on the php end this array is stored in $_GET['pid'] or $_POST['pid'] depending on how you sent it, so you would loop through the array and add the items to your sql query. Just make a separate variable to store the sql statement so you can add to it:
$x = 0;
foreach($_GET['pid'] as $value) {
$yourSQLString .= " AND pid[". $x ."] = '" . $value . "'";
$x++;
}
And obviously you should do something else with the actual value to avoid sql injections.

Get an array of user photos using FQL

I'm to get a list of the users photos (one's they've been tagged in) using FQL.
Basically I've go an array object like so: _imageAddressArray.
I can retrieve the users' photos using graphApi so I know it works, problem with graphAPi is that it's too slow (+15 seconds min for 100 photos).
So far I've got:
//New Stuff
FQL fql = new FQL(facebook);
String FQLResult = null;
try
{
_userGallery = graphApi.getPhotosMy(_noOfPhotos);
FQLResult = fql.fqlQuery("SELECT object_id, src_small FROM photo");
}
catch (EasyFacebookError e)
{
e.printStackTrace();
}
System.out.println("FQL Result" + FQLResult);
This returns the error: 601, any ideas anyone?
Of course ideally FQLResult will be a string[] (string array)
You're getting an error because you don't have a WHERE clause in your FQL statement that references one of the indexed columns -- shown with a "*" here
To get the photos using FQL that your user has been tagged in, try this:
SELECT object_id, src_small FROM photo WHERE object_id IN
(SELECT object_id FROM photo_tag WHERE subject = me())

How to get multiple rows of JSON data and put it into some sort of Array?

I tried to retrieve multiple rows of JSON data and display it but im not able to retrieve all the rows,im only getting the top(first) row of the database table.And im confused about how can i put the retrieved JSON data into some sort of array and access the individual rows?
I have provided the code relevant to the problem.
Yes i have done enough research before posting this question.I actually found one question which was some what similar to mine but nobody has answered it so i'm making this post.
Thank You
Below is the code from my Freebies.java class where i'm trying to retrieve JSONdata by calling getAllFreebies function from UserFunctions.java class
UserFunctions uf = new UserFunctions();
JSONObject json = uf.getAllFreebies();
System.out.println(json);
Below is the code of the function getAllFreebies() in the class UserFunctions.java
public JSONObject getAllFreebies(){
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", getAllFreebies_tag));
JSONObject json = jsonParser.getJSONFromUrl(getAllFreebiesURL,params);
return json;
}
Below is the code from index.php where im calling getFreebies() function from DB_Function.php file
else if($tag = 'getAllFreebies'){
$getAllFreebies = $db->getFreebies($username,$catagory,$subcatagory,$title,$condition,$description,$address,$city,$state,$country,$zipcode,$posted_on);
if($getAllFreebies)
{
$response["success"] = 1;
$response["getAllFreebies"]["username"] = $getAllFreebies["username"];
$response["getAllFreebies"]["catagory"] = $getAllFreebies["catagory"];
$response["getAllFreebies"]["subcatagory"] = $getAllFreebies["subcatagory"];
$response["getAllFreebies"]["title"] = $getAllFreebies["title"];
$response["getAllFreebies"]["item_condition"] = $getAllFreebies["item_condition"];
$response["getAllFreebies"]["description"] = $getAllFreebies["description"];
$response["getAllFreebies"]["address"] = $getAllFreebies["address"];
$response["getAllFreebies"]["city"] = $getAllFreebies["city"];
$response["getAllFreebies"]["state"] = $getAllFreebies["state"];
$response["getAllFreebies"]["country"] = $getAllFreebies["country"];
$response["getAllFreebies"]["zipcode"] = $getAllFreebies["zipcode"];
$response["getAllFreebies"]["posted_on"] = $getAllFreebies["posted_on"];
echo json_encode($response);
}else {
$response["error"] =1;
$response["error_msg"] = "Error in getAllFreebies";
echo json_encode($response);
}
}// end of getAllFreebies tag
Below is the code of my getFreebies() function of DB_function.php which is responsible for performing queries on MySQL database.
public function getFreebies(){
$result = mysql_query("SELECT * FROM freebie") or die(mysql_error());
return mysql_fetch_array($result);
}
Below is the logcat:
05-30 00:13:23.960: E/JSON(318): {"tag":"getAllFreebies","success":1,"error":0,"getAllFreebies":{"username":"viking","catagory":"Art","subcatagory":"Potrait","title":"Potrait","item_condition":"Good","description":"potarit","address":"Blah St","city":"lalaland","state":"NA","country":"NA","zipcode":"blah","posted_on":"2012-05-27"}}
mysql_fetch_array() only returns a single row of the query result set as an array. It does not fetch ALL of the rows. Since you're returning the results of the fetch from your getFreebies method, instead of the result handle itself, it is impossible for the calling code to get any other results from the query, other than the one row you've fetched.
As such, you should have:
public function getFreebies() {
$result = ...
return($result);
}
and
$getAllFreebies = $db->getFreebies(...);
$data = array();
while($row = mysql_fetch_assoc($getAllFreebies)) {
$data[] = array(
.... your variable assignments here ...
);
}
echo json_encod($data);

Categories