Unable to pass 'is not null' query to server side - ios

Situation
I want to search data from database.
My logic
If my textfield length is zero then pass 'is not null' value to server side. Otherwise pass the textfield data to server side.
Client side:
UILabel *first=[[UILabel alloc]init];
UILabel *sec=[[UILabel alloc]init];
if (_zip.text.length==0) {
first.text=#"is not null";
}
else
if (_zip.text.length>0) {
first.text=_zip.text;
}
if (_par.text.length==0) {
sec.text=#"is not null";
}
else if (_par.text.length>0){
sec.text=_par.text;
}
NSString *selquery=[NSString stringWithFormat:#"http://localhost/filtering1.php?zipcode=%#&parking=%#",first.text,sec.text];
NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:selquery]];
NSString *str=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#",str);
Server Side
<?php
$host="localhost";
$username="root";
$password="";
$db_name='BuyAndSell';
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$zipcode=$_GET['zipcode'];
$parking=$_GET['parking'];
$sql="SELECT * FROM bas WHERE zipcode='$zipcode' and parking='$parking'";
if ($result = mysql_query($sql)){
$resultArray = array();
$tempArray = array();
while($row = mysql_fetch_object($result)){
$tempArray = $row;
array_push($resultArray, $tempArray);
}
echo json_encode($resultArray);
}
else{
echo "failed query";}
?>

In order to do it right, you need to do it on the server side. By the time your data reaches the server, the crucial bit of information about _zip.text.length being zero is gone. All the server knows is that $zipcode variable is set to a string is not null, so it runs the search
SELECT * FROM bas WHERE zipcode='is not null' and parking='is not null'
which does not find anything.
Move the code for length checking to the server side, and pass "raw" strings from the client. Then modify your PHP code to construct the query string based on the input. Start with the base string "SELECT * FROM bas WHERE ", then append either zipcode is not null when $zipcode is empty, or a comparison to $zipcode if it is not empty. After that append " AND ", and do the same for the $parking variable.
Note 1: Your server side implementation lends itself to an easy SQL injection attack. Refer to this Q&A for information on how to fix this problem by parameterizing your query.
Note 2: Using SELECT * in production code is not a good practice. See this Q&A for an explanation of what is wrong with it.

Related

Mysql loop return incorrect data

Good Afternoon All,
I am facing an issue and cant figure out what I am doing wrong in my myslq/php while/foreach loop.
Loop seems to be duplicating results.
////////////////////////Check which site have this app///////////////////
$query_t = "SELECT * FROM site WHERE app_id='2'";
$result_t = mysql_query($query_t) or die(mysql_error());
$rows = array();
while($r_t = mysql_fetch_array($result_t))
$rows[] = $r_t;
foreach($rows as $r_t){
$this_areport_site_id = $r_t['site_id'];
//////////////Search for user emails that have access to this app ////////
$query_t4 = "SELECT mail FROM $user_tbl WHERE arep_kitchen='1' AND site_id='$this_areport_site_id' ORDER BY id ASC";
$result_t4 = mysql_query($query_t4);
while ($r_t4 = mysql_fetch_array($result_t4)) {
$areport_kitchen_email .= $r_t4[mail].',';// append comma after each value you append to the string
}
echo 'Here: '.$this_areport_site_id.' - '.$areport_kitchen_email.'<br />';
}
Now it does return me following:
Here: AHROW - person1#email.com,
Here: AHROW - person1#email.com,person2#email.com,
Here: AHALEX - person1#email.com,person2#email.com,person3#email.com,
And I was expecting
Here: AHROW - person1#email.com,person2#email.com,
Here: AHLANG - No Records here
Here: AHALEX - person3#email.com,
I would appreciate suggestion what I am doing wrong there as I am sitting on this whole morning.
You should empty the string $areport_kitchen_email before appending emails to it:
$areport_kitchen_email = ''; // empty emails container string
while ($r_t4 = mysql_fetch_array($result_t4)) {
$areport_kitchen_email .= $r_t4[mail].',';// append comma after each value you append to the string
}
This will avoid duplicates.
I have fixed the issue by doing two loops one inside the other and resigning from comma separated string which seems to be an issue in first post.
Bozzy, thank you for an effort.
$query_t7 = "SELECT * FROM site WHERE app_id='2'";
$result_t7 = mysql_query($query_t7) or die(mysql_error());
while($r_t7 = mysql_fetch_array($result_t7)) {
$this_areport_site_id = $r_t7['site_id'];
$query_t8 = "SELECT * FROM admins WHERE arep_kitchen='1' AND site_id='$this_areport_site_id' ORDER BY id ASC";
$result_t8 = mysql_query($query_t8) or die(mysql_error());
while($r_t8 = mysql_fetch_array($result_t8)) {
$areport_kitchen_email = $r_t8['mail'];
}
}

Json post method in swfit 3 for the below php code

I have a PHP code that used to add user values to DB when the registration time. I need the swift codes to insert the values from the user like username, email, password to the data base. I did this once but that PHP code used POST method. How to post for this format.
<?php
function userReg($json_request){
//DB connection details
include 'connection.php';
$serviceId = $json_request['requestHeader']['serviceId'];
$fullname = $json_request['requestInput']['full name'];
$emailId = $json_request['requestInput']['email'];
$password = $json_request['requestInput']['password'];
$queryUser = "SELECT * FROM user_master WHERE email = '".$emailId."'";
$result_user = $conn->query($queryUser);
if($result_user->num_rows == 0){
$insertUserSql = "INSERT INTO user_master (user_name, email, password) VALUES ('".$fullname."', '".$emailId."', '".$password."')";
if (mysqli_query($conn, $insertUserSql)){
$getUserIdSql = "SELECT user_id FROM user_master WHERE email = '".$emailId."'";
$result_userId = $conn->query($getUserIdSql);
while($row_user = $result_userId->fetch_assoc()) {
$user_details[] = $row_user;
}
$userId = $user_details["0"]["user_id"];
$res['responseHeader']['serviceId'] = $serviceId;
$res['responseHeader']['status'] = "100";
$res['responseHeader']['message'] = "Success";
$res['registerUserOutput']['userID'] = $userId;
$res['registerUserOutput']['userInfo']['fullName'] = $fullname;
$res['registerUserOutput']['userInfo']['email'] = $emailId;
$res['registerUserOutput']['userInfo']['profilePic'] = "";
$json_user_output = json_encode($res, JSON_UNESCAPED_SLASHES);
echo $json_user_output;
}
}
else{
$res['responseHeader']['serviceId'] = $serviceId;
$res['responseHeader']['status'] = "99";
$res['responseHeader']['message'] = "Email ID already exists";
$res['registerUserOutput'] = "{}";
$json_user_output = json_encode($res, JSON_UNESCAPED_SLASHES);
echo $json_user_output;
}
}
?>
This answer covers the how to add parameters to a post request portion of URL session: POST Request in swift with key-value coding
Now I'd like to actually comment a bit on your PHP code. I see 2 problems with the way you do your SQL.
First I'd recommend using PDO instead ( helpful blog post here: PDO vs. MySQLi
Second and most importantly, you're directly interpolating your user generated values into your queries making you directly vulnerable to a SQL Injection attack.
The correct way to solve this would be to use prepared statements with PDO. Although you can use mysqli_real_escape_string() it is in general much easier and better to just use prepared statements. As these escaping functions ( most notably addslashes() ) can have vulnerabilities of their own and make your code a lot less readable than prepared statements do.
This would go something like this:
<?php
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);
Source: PDO Prepared statements
I haven't done any raw PHP in a while so this is as far as it goes for me, but should help you on your way.

Fast(est) way to get X-Forwarded-for in header with G-Wan?

Since this non-RFC header field isn't in HTTP_Env nor http_t struct, i wrote this snippet :
//Get reply buffer
xbuf_t *reply = get_reply(argv);
// Init & create json buffer
xbuf_t json_buf;
xbuf_init(&json_buf);
jsn_t *params = jsn_add_node(0, "params");
[...]
http_t *http = (http_t*)get_env(argv, HTTP_HEADERS);
xbuf_t *read_buf = (xbuf_t*)get_env(argv, READ_XBUF);
[...]
// Add remote ip (from X-Forwarded-for or REMOTE_ADDR)
char *xforward = xbuf_findstr(read_buf, "X-Forwarded-For:");
if(xforward) {
jsn_add_string(params, "ip", xforward);
} else {
jsn_add_string(params, "ip", get_env(argv, REMOTE_ADDR));
}
The json part is, of course, part of the application and irrelevant with the question.
Do you think it's a right way to do it or is xbuf_findstr() inefficient and there is a faster solution (without using ASM or cryptic code) ?
Thank you :)
EDIT : Wow, i forgot the strok() part to get rid of the first field, i just want the ip adress of course.
EDIT2 : Patched version with strtok
// Add remote ip (from X-Forwarded-for or REMOTE_ADDR)
char *xforward = xbuf_findstr(read_buf, "X-Forwarded-For: ");
if(xforward) {
gc_init(argv, 1024);
char *copy = gc_malloc(argv, strlen(xforward)+ 1);
memcpy(copy, xforward, strlen(xforward) + 1);
strtok(copy, ":");
char *ip = strtok(0,"\r");
while (*ip == ' ') ip++; // Trim leading space
jsn_add_string(params, "ip", ip);
} else {
jsn_add_string(params, "ip", get_env(argv, REMOTE_ADDR));
}
fastest way?
If this code is executed AFTER the HTTP request PARSING G-WAN state then you could start searching for "X-Forwarded-For: " from the closest place (another HTTP header) instead of doing it from the start of the REQUEST.
There is no way to be significantly faster than xbuf_findstr(). String search methods are faster than others depending on the length of the input data, and this is not significant here.
"X-Forwarded-For: " was parsed by G-WAN in the past but as we have implemented a proxy feature in G-WAN, and since the "X-Forwarded-For: " header can be a fake, we removed it from the parser.

Query SQLite database for a GUID in the form X'3D98F71F3CD9415BA978C010b1CEF941

I have an iOS project and data is written into an SQLite Database. For example, 'OBJECTROWID' in a table LDOCLINK stores info about a linked document.
OBJECTROWID starts of as a string with the format <3d98f71f 3cd9415b a978c010 b1cef941> but is cast to (NSData *) before being input into the database. The actual handling of the database insertion was written by a much more experienced programmer than myself. Anyway, as the image below shows, the database displays the OBJECTROWID column in the form X'3D98F71F3CD9415BA978C010b1CEF941'. I am a complete beginner with SQLite queries and cannot seem to return the correct row by using the WHERE clause with OBJECTROWID = or OBJECTROWID like.
SELECT * FROM LDOCLINK WHERE OBJECTROWID like '%';
gives all the rows (obviously) but I want the row where OBJECTROWID equals <3d98f71f 3cd9415b a978c010 b1cef941>. I have tried the following and none of them work:
SELECT * FROM LDOCLINK WHERE OBJECTROWID = 'X''3d98f71f3cd9415ba978c010b1cef941' no error - I thought that I was escaping the single quote that appears after the X but this didn't work
SELECT * FROM LDOCLINK WHERE OBJECTROWID like '%<3d98f71f 3cd9415b a978c010 b1cef941>%'
I cannot even get a match for two adjacent characters such as the initial 3D:
SELECT * FROM LDOCLINK WHERE OBJECTROWID like '%3d%' no error reported but it doesn't return anything.
SELECT * FROM LDOCLINK WHERE OBJECTROWID like '%d%' This is the strangest result as it returns ONLY the two rows that DON'T include my <3d98f71f 3cd9415b a978c010 b1cef941>, seemingly arbitrarily.
SELECT * FROM LDOCLINK WHERE OBJECTTYPE = '0' returns these same rows, just to illustrate that the interface works (SQLite Manager).
I also checked out this question and this one but I still could not get the correct query.
Please help me to return the correct row (actually two rows in this case - the first and third).
EDIT:
The code to write to database involves many classes. The method shown below is I think the main part of serialisation (case 8).
-(void)serializeValue:(NSObject*)value ToBuffer:(NSMutableData*)buffer
{
switch (self.propertyTypeID) {
case 0:
{
SInt32 length = 0;
if ( (NSString*)value )
{
/*
NSData* data = [((NSString*)value) dataUsingEncoding:NSUnicodeStringEncoding];
// first 2 bytes are unicode prefix
length = data.length - 2;
[buffer appendBytes:&length length:sizeof(SInt32)];
if ( length > 0 )
[buffer appendBytes:([data bytes]+2) length:length];
*/
NSData* data = [((NSString*)value) dataUsingEncoding:NSUTF8StringEncoding];
length = data.length;
[buffer appendBytes:&length length:sizeof(SInt32)];
if ( length > 0 )
[buffer appendBytes:([data bytes]) length:length];
}
else
[buffer appendBytes:&length length:sizeof(SInt32)];
}
break;
//depends on the realisation of DB serialisation
case 1:
{
Byte b = 0;
if ( (NSNumber*)value )
b = [(NSNumber*)value boolValue] ? 1 : 0;
[buffer appendBytes:&b length:1];
}
break;
//........
case 8:
{
int length = 16;
[buffer appendBytes:[(NSData*)value bytes] length:length];
}
break;
default:
break;
}
}
So, as pointed out by Tom Kerr, this post answered my question. Almost. The syntax wasn't exactly right. The form: SELECT * FROM LDOCLINK WHERE OBJECTROWID.Id = X'a8828ddfef224d36935a1c66ae86ebb3'; was suggested but I actually had to drop the .Id part.
Making:
SELECT * FROM LDOCLINK WHERE OBJECTROWID = X'3d98f71f3cd9415ba978c010b1cef941';

Need API for currency converting [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
Please advice API for currency converting which returns JSON or small size html.
I use http://www.google.com/finance/converter?a=1&from=RUB&to=USD that returns HTML of 11 kb.
I use it in my iOS app.
Thanks in advance!
free.currencyconverterapi.com returns results in JSON format.
The web service also supports JSONP. The API is very easy to use, and it lets you convert one currency to another.
Disclaimer, I'm the author of the website.
A sample conversion URL is: http://free.currencyconverterapi.com/api/v6/convert?q=USD_PHP&compact=ultra&apiKey=sample-api-key which will return a value in json format, e.g. {"USD_PHP":51.459999}
As mentioned in the comments this service was shut down in Nov 2013.
Googles calulator API can do this;
Request:
http://www.google.com/ig/calculator?hl=en&q=100EUR=?USD
Response:
{lhs: "100 Euros",rhs: "145.67 U.S. dollars",error: "",icc: true}
(More info)
Yahoo is no longer working. See comment below
Yahoo Finance Currency Converter.
This url format could be used to fetch conversion rates in different formats.
http://download.finance.yahoo.com/d/quotes.csv?s=AUDUSD=X&f=nl1d1t1
Substitute quotes.csv with appropriate format and parameters with the required codes
EDIT: Added Example Url formats
Now iGoogle has been killed off, Alex K's solution no longer works sadly.
In php, this is an alternative which works in the same way and is just as effective:
$amount = urlencode($amount);
$from_Currency = urlencode($from_Currency);
$to_Currency = urlencode($to_Currency);
$get = file_get_contents("https://www.google.com/finance/converter?a=$amount&from=$from_Currency&to=$to_Currency");
$get = explode("<span class=bld>",$get);
$get = explode("</span>",$get[1]);
$converted_amount = preg_replace("/[^0-9\.]/", null, $get[0]);
UPDATE: Yahoo API is not working anymore. Leaving this legacy answer just to provide information that this doesn't work anymore.
use yahoo api:
http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22USDLTL%22)&format=json&env=store://datatables.org/alltableswithkeys&callback=
it will return json format like:
{
query: {
count: 1,
created: "2013-12-04T13:52:53Z",
lang: "en-US",
results: {
rate: {
id: "USDLTL",
Name: "USD to LTL",
Rate: "2.5485",
Date: "12/4/2013",
Time: "8:52am",
Ask: "2.5486",
Bid: "2.5485"
}
}
}
}
Check out in the URL there is USDLTL now, so just change to what you need.
Also sometime the rate is so low, that you don't see it even with 4 numbers it shows:
Rate: 0.0006
Do not panic just make a reversal query, flip your currencies and make some simple math.
e.g. you got that the rate is from KRW to EUR 0.0006 but the real rate is something like 0.00000125 so ask API again, just flip the currencies: what is the ratio from EUR to USD. then you will get huge number like 12500000.xxx so make math to get the ratio you need: 1/12500000 and you will get ratio = 0.00000125
Hope that helps ;)
P.S. decoded URL which is easier to read looks like this:
http://query.yahooapis.com/v1/public/yql
?q=select * from yahoo.finance.xchange where pair in ("USDLTL")
&format=json
&env=store://datatables.org/alltableswithkeys
&callback=
I use a php-class to convert currency rates:
/**
* Yahoo currency rate import class
*
* #author Felix Geenen (http://www.geenen-it-systeme.de)
* #version 1.0.3
*/
class Yahoofinance {
public static $_url = 'http://download.finance.yahoo.com/d/quotes.csv?s={{CURRENCY_FROM}}{{CURRENCY_TO}}=X&f=l1&e=.csv';
public static $_messages = array();
/*
* converts currency rates
*
* use ISO-4217 currency-codes like EUR and USD (http://en.wikipedia.org/wiki/ISO_4217)
*
* #param currencyFrom String base-currency
* #param currencyTo String currency that currencyFrom should be converted to
* #param retry int change it to 1 if you dont want the method to retry receiving data on errors
*/
public static function _convert($currencyFrom, $currencyTo, $retry=0)
{
$url = str_replace('{{CURRENCY_FROM}}', $currencyFrom, self::$_url);
$url = str_replace('{{CURRENCY_TO}}', $currencyTo, $url);
try {
$handle = fopen($url, "r");
if($handle !== false) {
$exchange_rate = fread($handle, 2000);
# there may be spaces or breaks
$exchange_rate = trim($exchange_rate);
$exchange_rate = (float) $exchange_rate;
fclose($handle);
if( !$exchange_rate ) {
echo 'Cannot retrieve rate from Yahoofinance';
return false;
}
return (float) $exchange_rate * 1.0; // change 1.0 to influence rate;
}
}
catch (Exception $e) {
if( $retry == 0 ) {
# retry receiving data
self::_convert($currencyFrom, $currencyTo, 1);
} else {
echo 'Cannot retrieve rate from Yahoofinance';
return false;
}
}
}
}
Here is a simple adaptation of Felix Geenen's answer to use curl instead of fopen since a lot of servers have fopen turned off by default.
( I cleaned up some code and added a decrement value to retry. )
( Also remember to update the retry self reference depending on the scope you drop the function in to eg. static:: or $this-> )
function convert($from, $to, $retry = 0)
{
$ch = curl_init("http://download.finance.yahoo.com/d/quotes.csv?s=$from$to=X&f=l1&e=.csv");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_NOBODY, false);
$rate = curl_exec($ch);
curl_close($ch);
if ($rate) {
return (float)$rate;
} elseif ($retry > 0) {
return convert($from, $to, --$retry);
}
return false;
}
I was using iGoogle until it just went belly up, serves me right.
Thanks to Nerfair tho in his comment in response to hobailey's comment above, this works AWESOME. I thought I would post it here so you can fully see how it works!
http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.xchange where pair in ("USDCNY")&format=json&env=store://datatables.org/alltableswithkeys&callback=
Here is the link url encoded: http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20%28%22USDCNY%22%29&format=json&env=store://datatables.org/alltableswithkeys&callback=
Super nice, just change the currency pair. Thanks Nerfair!

Resources