Passing String Arrays into PHP file with Android - php

I'm trying to use retrofit and PHP to store values in MySQL. I will pass in to the PHP a single postid string (postid) and a string array. For each index in the string array (called tags) I will make a unique row in the database. It will have the following form:
--------------------
|postid | tags |
--------------------
| postid | tags[0]|
| postid | tags[1]|
| postid | tags[2]|
....................
--------------------
The issue I am having is that for the string array, only the last value in the array is being stored.
Here is the retrofit interface
#FormUrlEncoded
#POST("create_recipe.php")
Call<Void> createRecipe(
#Field("postid") String postid,
#Field("tags") String[] tags
);
and the retrofit client call
Retrofit retrofit = ApiClient.getClient();
ApiInterface apiService = retrofit.create(ApiInterface.class);
Call<Void> call = apiService.createRecipe(postid, tags);
call.enqueue(new Callback<Void>() {
#Override
public void onResponse(Call<Void> call, Response<Void> response) {
}
#Override
public void onFailure(Call<Void> call, Throwable t) {
}
});
Here is what the PHP that handles this looks like (excluding some of the init code)
if (isset($_POST['postid']) && isset($_POST['tags']){
$uid = $_POST['postid'];
$tags = array($_POST['tags']);
$tags_new = str_replace(array('[', ',', ']'), '' , $tags);
foreach ($tags_new as $value){
mysql_query("INSERT INTO Tags(postid, tag) VALUES('$postid', '$value')");
}
}
If I pass in postid = 30 and tags = {"milk", "cheese", "bread"} I want it to look like
--------------------
|postid | tags |
--------------------
| 30 | milk |
| 30 | cheese |
| 30 | bread |
....................
--------------------
but instead only bread will be stored.
How do I handle the string array passed in as a parameter in PHP?
What is the form of the array when I pass it onto $tags?

I had the same problem some time back and found no clear solution for it. However I built a simple solution for something similar. I hope this solution helps.

Actually, you can print it out in the PHP work sheet, you can add the following to log the input here.
file_put_contents("test.log",json_encode($_POST)."--".json_encode($_GET));
Only then will you be able to determine whether the array is correctly delivered to the php script.

you might want to reconsider about this, because the following line is basically just removing all the barriers in the string($tags, which is now interpreted as a String instead of an array):
$tags_new = str_replace(array('[', ',', ']'), '' , $tags);
and change it into
$tags_new = split(',' , $tags);

Related

PHP List function when response is in multiline or single

I use CURL method to post and receive response from the SMS aggregator.
$url = "https://www.smsgatewaycenter.com/library/send_sms_2.php?".$request;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$curl_scraped_page = curl_exec($ch);
curl_close($ch);
list ($status, $returnmobileno, $statusdetails) = split('\|', $curl_scraped_page);
Now my aggregator gives response in single when I send single SMS like this
$curl_scraped_page = "success | 919********** | 659613958369444158-117942947553648183"; //THIS IS EXAMPLE
So I use list function to get unique id 659613958369444158 before the hyphen. I am all good until I get a single response but when I get response as under, am not able to get the first unique id from the response.
Multiline Response
success | 917*********| 3287615453600499019-106346209426268709
success | 919********* | 3287615453600499019-483762398162272572
success | 9196********** | 3287615453600499019-204615952244351373
Or Single Line Multi Response
success | 917*********| 3287615453600499019-106346209426268709 success | 919********* | 3287615453600499019-483762398162272572 success | 9196********** | 3287615453600499019-204615952244351373
From above given multi-line or single line multi response. I just need to catch success/error and 3287615453600499019 and store it in my DB.
Somehow lost it even with preg_match().
How should I be able to achieve it?, I finally gave up after trying for 3 hours and seeking help here.
/(\d+)-/ should work just fine to put the desired number into a capture group:
<?php
$str = "success | 917*********| 3287615453600499019-106346209426268709 success | 919********* | 3287615453600499019-483762398162272572 success | ";
if (preg_match("/(success|error) \|.*?\| (\d+)-(\d+)/", $str, $matches)) {
echo "$matches[1] - $matches[2]";
} else {
// no match
}
Output:
3287615453600499019

php multi dimensional array's

I am pulling data out of a table that has these fields:
zipcode,city,state,county
My question is that some zip codes are in multiple cities, and some cities are in multiple zip codes... so is there a way to have all the data put into an array, then group all of the zip codes in order, then build a table out of that, so that it puts them in order, but if the data is redundant, like the zip, city, state and county are already in the array, then it skips it?
so then I can print it to the browser using echo, into a table like this:
74801 | Shawnee, Oklahoma | Pottawatomie
74801 | Bethel, Oklahoma | Pottawatomie
74801 | Johnson, Oklahoma | Pottawatomie
74851 | McLoud, Oklahoma | Pottawatomie
74851 | Dale, Oklahoma | Pottawatomie
etc.
But in the case of these:
74015 | CATOOSA, Oklahoma | Rogers
74015 | COTOOSA, Oklahoma | Rogers
Because those are duplicates in those fields (not in the rest of the table), I need it to skip showing it twice.
I think it is something like this:
$zipArray = array();
$zipCode = $dbhhandle->zip;
$cityName = $dbhhandle->city;
$countyName = $dbhhandle->county;
if($zipArray[$zipCode][$cityName] != $countyName) {
$zipArray[$zipCode][$cityName] = $countyName;
}
but I'm not sure if that is the right way to do it.
Then once I have the array built, how do I build the table?
Your code looks pretty close, but it's missing the state. So change the elements of the array into associative arrays with state and county elements.
Also, you need to check whether there's an entry for the zip code at all, before checking whether it's a duplicate, otherwise you'll access an undefined index.
$zipArray = array();
$zipCode = $dbhhandle->zip;
$cityName = $dbhhandle->city;
$countyName = $dbhhandle->county;
$stateName = $dbhandle->state;
if(!isset($zipArray[$zipCode][$cityName]) || $zipArray[$zipCode][$cityName]['county'] != $countyName) {
$zipArray[$zipCode][$cityName] = array('county' => $countyName, 'state' => $stateName);
}
To display the table, you use nested loops.
foreach ($zipArray as $zip => $cities) {
foreach ($cities as $city => $cityData) {
echo "<tr><td>$zip</td><td>$city, {$cityData['state']}</td><td>{$cityData['county']}</td></tr>";
}
}

getting child id's from database dynamically?

I try to get the child id's of products dynamically.Below is my table structure.
parent|child
---------------------
44 | 35,6,47,5,50
---------------------
47 | 8,9
---------------------
50 | 12, 15
am going to pass only one parent id and get the child ids, and if anyone of child ids having again child, then i have to fetch that record also.example 44->35,6,47,5,50 in this 47 and 50 is having child ids, so my final output should be like this 44-> 35,6,47,8,9,5,50,12,15.
I tried below this,
$sql=mysql_fetch_assoc(mysql_query("select * from chain_product where parent='44'"));
$parent=$sql['parent'];
$child=$sql['child'];
$ex=explode(",",$child);
$count=sizeof($ex);
for($i=0;$i<$count;$i++)
{
$list=add_child($ex[$i],$child);
$check=explode(",",$list);
$chck_count=sizeof($check);
if($chck_count>$count)
{
$exit=add_child($ex[$i],$list);
print_r($exit);
}
}
function add_child($main,$ch)
{
$find=mysql_query("select * from chain_product where parent='$main'");
$res=mysql_fetch_assoc($find);
if($res)
{
$replace=$main.",".$res['child'];
$alter=str_replace($main,$replace,$ch);
echo $alter;
}
}
but i get the result like this,
35,6,47,8,9,5,5035,6,47,5,50,12,15
but i need output should be like this..
35,6,47,8,9,5,50,12,15.
can anyone help me to do this..
Your database structure isnt optimal for this, this would be better:
id | parent
1 | 0
2 | 1
3 | 1
4 | 2
5 | 2
This way you can do something recursive:
function getChilds($parent=0, $depth=0){
// Select the items for the given $parent
$query = $conn->mysqli_query("SELECT id WHERE parent=".$parent); // mysqli is better, but mysql will do fine
// get the items by the parent giving as input:
while($fetch = $query->fetch_assoc() ){
echo str_repeat('-', $depth) . " ".$fetch['id'];
getChilds($fetch['id'], $depth+1); // Use id of this line to find its childs
echo "<br />";
}
}
getChilds(0); // And start it. The 0 is optional, I personaly prefer -1. Whatever rows your boat
This is called a tree structure and should give something like this:
1
- 2
- - 4
- - 5
- 3
In this example I use an echo for display purposes, you can return the values via an array, same principle
To answer a bit better, your current structure could support a similar method, but because you use strings, it will be allow slower and alot less flexible. You can see the difference in the code you are using, and the amount I just used. If you would remove the echo's and only return arrays, it will be even smaller :)

PHP + PDO, my escaped characters won't show when displayed

First, I'd like to apologize, I'm still a beginner.
For learning purposes I'm creating a blog engine and I just noticed that when I list the comments, escaped characters like carriage return (pressing enter) are shown in the database correctly, but only a whitespace character when displaying the comments.
I'm using PostgreSQL 8.3.
Here you can see an example database entry:
fema=> select * from comments where id = 54;
-[ RECORD 1 ]-------------------------
id | 54
authorid | 1
text | This new line won't show.\r
: No\r
: \r
: new\r
: \r
: \r
: \r
: lines.
time | 1341417673
postid | 15
answerid | 0
Here you can see what var_dump() shows:
string(50) "This new line won't show. No new lines."
This is how I'm getting the data:
$stmt = db::$db->prepare("select comments.id as commentid ,authorid,text,time,postid,answerid,users.* from comments left join users on users.id = comments.authorId where postid = :postId");
$stmt->execute(array('postId' => $_GET['p']));
$commentRslt = $stmt->fetchAll();
Then foreach to iterate through them and replace the mark I'm using to identify things I have to replace:
$currComment = str_replace('{{{cms:comment:text}}}', $commentRslt[$key]['text'], $currComment);
This is how I insert the new comment to the DB:
$stmt = self::$db->prepare('INSERT INTO comments (authorId, text, time, postId, answerId) VALUES (:authorId, :text, :time, :postId, :answerId)');
$stmt->execute(array( 'authorId' => $_SESSION['userId'],
'text' => str_replace(array('<','>'), array('&lt','&gt'), isset($_POST['newCommentArea']) ? $_POST['newCommentArea'] : $_SESSION['newCommentArea']),
'time' => time(),
'postId' => isset($_POST['commentNew']) ? $_POST['commentNew' ] : $_SESSION['postId'],
'answerId' => $answerId));
Sorry for the many code samples, but I don't even know where the problem is and I wanted to be thorough.
So could anyone please tell me how to solve the problem? If only just by telling me where I made the mistake. I really have no clue.
Thanks.
Jut guessing here, but:
Consecutive whitespace is collapsed to a single space by HTML/the browser. Replace newlines with <br> tags if you want to keep them, using nl2br.

Parse JSON Freebase results in PHP

I'm really sorry if this is too basic, but I really don't know how to do this.
I'm using this jquery Autocomplete plugin: http://devthought.com/wp-content/projects/jquery/textboxlist/Demo/
EDIT: This is the jquery code i use for the autocomplete:
$(function() {
var t = new $.TextboxList('#form_topick_tags', {unique: true, plugins: {autocomplete: {
minLength: 2,
queryRemote: true,
remote: {url: 'autocomplete2.php'}
}}});
The plugin uses a PHP for autocomplete, this is an example, it returns this output: "id, text, null (html I don't need), some html"
$response = array();
$names = array('Abraham Lincoln', 'Adolf Hitler', 'Agent Smith', 'Agnus', 'Etc');
// make sure they're sorted alphabetically, for binary search tests
sort($names);
$search = isset($_REQUEST['search']) ? $_REQUEST['search'] : '';
foreach ($names as $i => $name)
{
if (!preg_match("/^$search/i", $name)) continue;
$filename = str_replace(' ', '', strtolower($name));
$response[] = array($i, $name, null, '<img src="images/'. $filename . (file_exists('images/' . $filename . '.jpg') ? '.jpg' : '.png') .'" /> ' . $name);
}
header('Content-type: application/json');
echo json_encode($response);
I need a similar PHP to process this results: http://www.freebase.com/private/suggest?prefix=beatles&type_strict=any&category=object&all_types=false&start=0&limit=10&callback=
...being "beatles" the $search value, and getting this output:
guid,"name",null,"name<span>n:type name</span>"
So, the first result would be:
0,"The Beatles",null,"The Beatles<span>Band</span>"
Of course I would need to query freebase.com from that PHP. I mean:
+---------------+ +-----------+ +------------+
| | | | | |
| TextboxList +-------->| PHP +------->| Freebase |
| | | | | |
+---------------+ +-----------+ +------+-----+
|
JSON JSON |
TextboxList <--------+ freebase <----------+
Is this possible? Thanks!
Try this:
$response = array();
$search = isset($_REQUEST['search']) ? $_REQUEST['search'] : '';
$myJSON = file_get_contents('http://www.freebase.com/private/suggest?prefix=' . urlencode($search));
$musicObj = json_decode($myJSON); // Need to get $myJSON from somewhere like file_get_contents()
foreach ($musicObj->result as $item)
{
$response[] = array($item->guid, $item->name, null, $item->name . '<span>'.$item->{'n:type'}->name.'</span>');
}
header('Content-type: application/json');
echo json_encode($response);
The first JSON-escaped result then gives:
["#9202a8c04000641f800000000003ac10","The Beatles",null,"The Beatles<span>Band<\/span>"]
But despite all this, you really don't need to use PHP at all to do this. You can do this all from JavaScript and avoid an extra trip to your server. If you supply the callback argument to freebase, it can create JSONP (which is JSON wrapped in a call to a function, using a function name of your choice) which you can obtain in jQuery and then manipulate further in JavaScript to your liking. But the above is per your original approach in using PHP.

Categories