i am writing a java code that http post with a parameter.that parameter is a long variable that convert to string.
ArrayList<NameValuePair> parameters =new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("MAX_ID", String.valueOf(maxNewsId)));
String result = CustomHttpClient.executeHttpPost(NewsUrl,parameters);
and i want write a php code at the server. that code should get that long number and connect to Data base and select rows that have id greater than that parameter.
i write this code but not working. what should i do?
<?php
$db_host = "localhost";
$db_uid = "**********";
$db_pass = "**********";
$db_name = "**********";
$db_con = mysql_connect($db_host,$db_uid,$db_pass,$db_name) or die('could not connect');
mysql_select_db($db_name);
$maxId = $_POST['MAX_ID'];
mysql_query("set names utf8");
$sql = "SELECT * FROM News where Nid> ".mysql_real_escape_string($maxId);
$result = mysql_query($sql);
while($row=mysql_fetch_assoc($result))
{
$output[]=$row;
}
print(json_encode($output));
mysql_close();
?>
A few notes about your code:
First... please don't use mysql_query anymore. Use mysqli_query or PDO. In newer PHP versions mysql_xxx is deprecated and you should use the alternative.
Second... your code is very susceptible to attack. When you use a POST or GET variable you should check if it does not contain harmful code. If your MAX_ID could only be a number i would suggest the following (note the intval-part):
$maxId = 0;
if (isset($_POST['MAX_ID'])) $maxId = intval($_POST['MAX_ID']);
It also checks if MAX_ID is not set (if so your $max_id is 0) and $maxId could only result in a number.
And last... because with above $maxId could only result in a number you don't need the mysql_real_escape_string. So this would be enough:
$sql = "SELECT * FROM News where Nid > ".$maxId;
(please note the warning at the top of the manual of this function about mysql_xxx being deprecated).
if you want greated than: you should change the "<" see in bold
$sql = "SELECT * FROM News WHERE Nid < ".mysql_real_escape_string($maxId);
Related
I have a problem with retrofit in my android app (java) retrieving a boolean field from php/mysql webservice.
In my java model, I have a boolean field selected, declared as:
#SerializedName("selected")
#Expose
private boolean selected;
In my MySQL database, the field is declared as TINYINT
When I upload my object, it is correctly saved in the database (0 or 1).
But when I want to download the same object, I get an error:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException:
Expected a boolean but was NUMBER at line 11 column 22 path
$[0].selected
php code:
<?php
header('content-type:application/json');
if (isset($_GET['deviceName']) && $_GET['deviceName'] != "") {
$deviceName = $_GET['deviceName'];
$sql = "SELECT * FROM `ComList` WHERE deviceName = '$deviceName' ORDER BY clistId, ord, categOrd ASC;";
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$pdo_options[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES utf8';
$bdd = new PDO('mysql:host=localhost;dbname=bdd', 'user', 'password', $pdo_options);
$bdd->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$bdd->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, false);
$response = $bdd->query($sql);
$output = $response->fetchAll(PDO::FETCH_ASSOC);
echo(json_encode($output, JSON_PRETTY_PRINT));
?>
I can't modify the type of the field in the java model.
Any idea please?
Something to modify in the SQL request?
Modify the output in PHP?
The only way I found that give a good result is:
$output = $response->fetchAll(PDO::FETCH_ASSOC);
$tab = array();
foreach($output AS $value) {
$value['selected'] = $value['selected'] ? true : false;
array_push($tab, $value);
}
echo(json_encode($tab, JSON_PRETTY_PRINT));
But I think it's such a dirty process.
Here is my goal
1. I have only one ID send from the server with list of string separated comma
this how it look like: ID=1, names=blue,red,green,yellow
2. This is my attempt:
2.1 i try to change the names to arrays by using this code
$myString = "Red,Blue,Black";
$myArray = explode(',', $myString);
2.2 and i try my insertion like this:
$sql="INSERT INTO `cat_interest`(`id`,`categories`) VALUES (1,'".$myArray["categories"]."'";
if (!$result = $mysqli->query($sql)){
$message = array('Message' => 'insert fail');
echo json_encode($message);
}else{
$message = array('Message' => 'new record inserted');
echo json_encode($tempArray);
}
Here is my complete code view
<?php
define('HOST','serveraddress');
define('USER','root');
define('PASS','pass');
define('DB','dbname');
ini_set('display_errors',1);
//ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$mysqli = new mysqli(HOST,USER,PASS,DB);
$message= array();
$myString = "Red,Blue,Black";// incoming string comma names
$myArray = explode(',', $myString);
$sql="INSERT INTO `cat_interest`(`id`,`categories`) VALUES (1,'".$myArray["categories"]."'";
if (!$result = $mysqli->query($sql)){
$message= array('Message' => 'insertion failed');
echo json_encode($message);
}else{
$message= array('Message' => 'new record inserted');
echo json_encode($message);
} ?>
This is what i want to achieve below
TABLE
ID Categories
1 RED
1 Blue
1 Black
after insertion
Please help i don't know what i doing wrong
While that SQL is invalid, you never close the values. Explode also doesn't build an associated array.
A rough example of how you could build a valid SQL statement would be
$myString = "Red,Blue,Black";// incoming string comma names
$myArray = explode(',', $myString);
print_r($myArray);
$sql = "INSERT INTO `cat_interest`(`id`,`categories`) VALUES";
foreach($myArray as $value){
$sql .= " (1, '{$value}'),";
}
$sql = rtrim($sql, ',');
Demo: https://eval.in/587840
When in doubt about how an array in constructed use print_r or var_dump. When having an issue with a query in mysqli use error reporting, http://php.net/manual/en/mysqli.error.php.
Also in your current usage you aren't open to SQL injections but if $myString comes from user input, or your DB you could be. You should look into using parameterized queries; http://php.net/manual/en/mysqli.quickstart.prepared-statements.php.
I'm attempting to retrieve multiple values from a database through php to my android java in eclipse.
I'm managing to get all variations of json arrays except the one i need.
My database is:
**Aircraft** **Status**
A870_870 1
A870_871 1
A870_872 1
A870_873 1
A870_874 1
A870_875 1
A870_876 2
A870_877 1
A870_878 2
A870_879 2
A870_880 2
A870_881 0
A870_882 0
A870_883 0
A870_884 0
A870_885 0
The format I need so that my android app reads it is:
{"A70_870":"1","A70_871":"1","A70_872":"1","A70_873":"1","A70_874":"1",
"A70_875":"1","A70_876":"2","A70_877":"1","A70_879":"2","A70_878":"2",
"A70_880":"2","A70_881":"0","A70_882":"0","A70_883":"0","A70_884":"0",
"A70_885":"0"}
I've been attempting different 'while' loops all sorts of other variations and manage to get all sorts of combinations except the one i need. Surely there is a way...?
My closest PHP attemp is below:
<?php
$con = mysqli_connect("localhost","root","", "mytestdatabase");
if (mysqli_connect_errno()) {
echo 'Database connection error: ' . mysqli_connect_error();
exit();
}
$userdetails = mysqli_query($con, "SELECT *FROM aircraft_status");
$row = mysqli_fetch_row($userdetails) ;
$result_data = array(
'A70_870'=>$row[1],
'A70_871'=>$row[1],
'A70_872'=>$row[1],
'A70_873'=>$row[1],
'A70_874'=>$row[1],
'A70_875'=>$row[1],
'A70_876'=>$row[1],
'A70_877'=>$row[1],
'A70_879'=>$row[1],
'A70_878'=>$row[1],
'A70_880'=>$row[1],
'A70_881'=>$row[1],
'A70_882'=>$row[1],
'A70_883'=>$row[1],
'A70_884'=>$row[1],
'A70_885'=>$row[1],);
echo json_encode($result_data);
?>
It gives the correct format, but obviously only reads row 1. I can't access 3,5,7 etc..
If anyone can assist me in this it would be great!! :) I'm sure its something simple I'm not doing right....
I might be missing something but is it not just wrapping result extraction in a while loop:
$userdetails = mysqli_query($con, "SELECT *FROM aircraft_status");
$result_data = array();
if ($userdetails) {
while($row = mysql_fetch_array($userdetails)) {
// $row[0] being aircraft and $row[1] being status
array_push($result_data , $row[0], $row[1]);
}
}
else {
echo mysql_error();
}
echo json_encode($result_data);
My PHP is very rusty, so might need adjustments. Hope this gets you on the way.
Hey Ive run into a little problem in my SQL/PHP/JAVA application Im hoping you guys can help :)
I have a java application that when run is connected to my website when the java application validates that it is running it talks to my website and my website assigns a session Id to both the java application and the website itself.
cool we good so far?
alright my java application sends data at regular intervals to a page called Dashboard.php what I would like to do is save the data into my Mysql table then when new data is received by Dashboard.php from my java application where the sessionID is the same I would like the table to update to the new data that was just received
here is the php i have so far although it doesnt work.
function update($script_name, $version, $runtime, $status, $ranged, $attack, $defense, $strength, $magic, $sessionID, $username)
{
global $db;
$sql = "SELECT * FROM Dashboard WHERE session_id = '$sessionID'";
try {
$results = $db->query($sql);
if ($results->rowCount() <= 0) {
$query = "INSERT INTO Dashboard (script_name, version, runtime, status, ranged, attack, defense, strength, magic, session_id, username) VALUES ('$script_name', '$version', '$runtime', '$status', '$ranged', '$attack', '$defense', '$strength', '$magic', '$sessionID', $username)";
$db->exec($query);
} else {
foreach ($results as $row) {
$timerunnew = $row['runtime'] + $runtime;
$v4new = $row['ranged'] + $range;
$v5new = $row['attack'] + $attack;
$v6new = $row['defense'] + $defense;
$v7new = $row['strength'] + $strength;
$v8new = $row['magic'] + $magic;
}
$db->exec("UPDATE Dashboard SET `runtime` = $timerunnew, `ranged` = $v4new, `attack` = $v5new, `defense` = $v6new, `strength` = $v7new, `magic` = $v8new WHERE session_id = '$sessionID'");
}
} catch (PDOException $ex) {
echo "fail";
}
}
Ive also tried experimenting with ON DUPLICATE KEY UPDATE value = VALUES(value) however I have had no luck does anyone have a solution? any help would be much appreciated
If this is the only way that records can be inserted into the Dashboard table, then it is impossible for two records to share the same session_id (save for a race hazard occurring between the SELECT and INSERT commands). In which case, you should:
Ensure that there is a UNIQUE key defined on session_id:
ALTER TABLE Dashboard ADD UNIQUE KEY (session_id);
Use INSERT ... ON DUPLICATE KEY UPDATE, ideally with a properly parameterised prepared statement:
$qry = $db->prepare('
INSERT INTO Dashboard (
script_name, version, runtime, status, ranged, attack,
defense, strength, magic, session_id, username
) VALUES (
:script_name, :version, :runtime, :status, :ranged, :attack,
:defense, :strength, :magic, :session_id, :username
) ON DUPLICATE KEY UPDATE
runtime = runtime + VALUES(runtime),
attack = attack + VALUES(status),
defense = defense + VALUES(defense),
strength = strength + VALUES(strength),
magic = magic + VALUES(magic)
');
$qry->execute([
':script_name' => $script_name,
':version' => $version,
':runtime' => $runtime,
':status' => $status,
':ranged' => $ranged,
':attack' => $attack,
':$defense' => $defense,
':strength' => $strength,
':magic' => $magic,
':session_id' => $sessionID,
':username' => $username
]);
Spaces not changing to underscored when sent from Java-->PHP-->SQL
Java code:
String urlString = "http://www.mysite.com/auth/verifyuser.php?name="+name.toLowerCase().replace(" ","_");
PHP code:
$name = mysql_real_escape_string($_GET['name']);
$name = str_replace(' ', '_', $name);
$query = "select * from authinfo where name LIKE '$name'";
mysql_query($query);
$num = mysql_affected_rows();
if ($num > 0) {
echo '1';
} else {
echo '0';
}
when I implement a test log on the SQL database, it somehow still seems to show up with spaces instead of underscores(even though I replace it in Java and PHP) and the PHP file returns '0' rather than '1'. I've heard the issue might be whitespaces? It seems to happen to only certain users, mostly mac users.
If your php file is returning a 0, that means your query is not getting executed. Where are you establishing a connection with the database before executing the query?
Remark: where name = '$name'
mysql_affected_rows concerns INSERT, UPDATE and DELETE.
$r = mysql_query($query);
$num = mysql_num_rows($r);
It's unsafe to pass raw name into URL without encoding it.
String urlString = "http://www.example.com/auth/verifyuser.php?name=" + URLEncoder.encode(name.toLowerCase(), "UTF-8");
In PHP you can obtain data:
$name = urldecode($_GET['name']);