Saturday, April 5, 2014

Connecting to Wordpress Database and manipulating post content using PHP

The sample code below covers the following:
1. Connecting to database using PHP.
2. File uploading and reading in PHP.
3. Parsing and splitting operations on Strings in PHP.
Sample Code


<?php
function replaceTitleWithHyperlink($content, $hospGuid, $title)
{
$parts = explode(" ", $content);
$arrlength = count($parts);

$inFound = False;
$asFound = False;
$hospitalName = "";

$indexOfFirstIn = 0;
$indexOfRequiredAs = 0;

for($i=0;$i<$arrlength;$i++)
{
if(strcmp($parts[$i],"in") == 0)
{
$inFound = True;
$indexOfFirstIn = $i;
}
else if($inFound == True and strcmp($parts[$i],"as") == 0)
{
$asFound = True;
$indexOfRequiredAs = $i;
}
else if($asFound == False and $inFound == True)
{
$hospitalName = $hospitalName . " " . $parts[$i];
}
else if($asFound == True and $inFound == True)
{
break;
}
}

$indexOfMatch=1;
$numberOfMatches = 0;

for($i=1;$i<count($hospGuid);$i++)
{
if(strcasecmp(trim($title[$i]), trim($hospitalName)) == 0)
{
$indexOfMatch = $i;
$numberOfMatches++;
}
}
echo "<br>numberOfMatches: " . $numberOfMatches . "<br>";

$finalDocPost = "";

if($numberOfMatches > 1)
{
return $finalDocPost;
}

$parts[$indexOfRequiredAs - 1] = "<a href=\"" . $hospGuid[$indexOfMatch] . "\">" . $hospitalName . "</a>";

for($i=0;$i<$arrlength;$i++)
{
if($i>$indexOfFirstIn and $i<$indexOfRequiredAs-1)
{
}
else
{
$finalDocPost .= " " . $parts[$i];
}
}

echo "<br> Final Doctor Post: " . $finalDocPost . "<br>";
return $finalDocPost;
}

//Fetch values from the form.
$db_url = $_POST["db_url"];
$db_user = $_POST["db_user"];
$db_password = $_POST["db_password"];
$db_name = $_POST["db_name"];
$file_name = $_POST["file"];
$csv_indices = $_POST["indices"];
$update_pref = $_POST["update_pref"];

// Create connection
$con=mysqli_connect($db_url,$db_user,$db_password,$db_name);

// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error() . "<br>";
}
else
{
echo "Successfully connected to the database<br>";
}

//Array of unique-ids.
$indices = array("dummy");

if(strlen($csv_indices) > 0)
{
$parts = explode(",", $csv_indices);
for($i=0; $i< count($parts); $i++)
{
array_push($indices, trim($parts[$i]));
}
array_push($indices, "");
}

else
{
echo $_FILES["file"]["name"] . "<br>";
$allowedExtensions = array("txt");
$temp = explode(".", $_FILES["file"]["name"]);

$extension = end($temp);

if(in_array($extension, $allowedExtensions))
{
if ($_FILES["file"]["error"] > 0)
{
echo "<p style=\"color:red;margin-left:20px;\">";
echo "Error: " . $_FILES["file"]["error"] . "</p><br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
$file = fopen($_FILES["file"]["tmp_name"], "r") or exit("<br>Unable to open file!");
echo "<br>";
while(!feof($file))
{
$line = fgets($file);
echo $line. "<br>";
array_push($indices, trim($line));
}
fclose($file);
}
else
{
echo "<p style=\"color:red;margin-left:20px;\">";
echo "<br>File type not supported</p><br>";
}
}

$arrlength = count($indices);
$hospGuid = "";

for($i=1;$i<$arrlength-1;$i++)
{
echo "<br>";
echo "The value in indices is: " . $indices[$i] . " is the value";
}
echo "<br>";
echo "<br>";

for($i=1;$i<$arrlength-1;$i++)
{
$docSelect = "select wp_postmeta.meta_key, wp_postmeta.meta_value, wp_posts.ID, wp_posts.guid, wp_posts.post_content from wp_posts inner join wp_postmeta on wp_posts.ID = wp_postmeta.post_id where wp_postmeta.meta_key='index' and wp_posts.post_status = 'publish' and wp_posts.post_type = 'post' and wp_postmeta.meta_value = '{$indices[$i]}' and wp_posts.ID in (select object_id from wp_term_relationships where term_taxonomy_id = (select term_taxonomy_id from wp_term_taxonomy inner join wp_terms on wp_term_taxonomy.term_taxonomy_id = wp_terms.term_id where wp_term_taxonomy.taxonomy='category' and wp_terms.name='Doctors'))";

$hospSelect = "select wp_postmeta.meta_key, wp_postmeta.meta_value, wp_posts.ID, wp_posts.guid, wp_posts.post_title from wp_posts inner join wp_postmeta on wp_posts.ID = wp_postmeta.post_id where wp_postmeta.meta_key='index' and wp_posts.post_status = 'publish' and wp_posts.post_type = 'post' and wp_postmeta.meta_value = '{$indices[$i]}' and wp_posts.ID in (select object_id from wp_term_relationships where term_taxonomy_id = (select term_taxonomy_id from wp_term_taxonomy inner join wp_terms on wp_term_taxonomy.term_taxonomy_id = wp_terms.term_id where wp_term_taxonomy.taxonomy='category' and wp_terms.name='Hospitals'))";

echo "<strong>Hospitals query: " . $hospSelect . "</strong>";

$hospSet = mysqli_query($con,$hospSelect);

echo "<table border='1'>
<tr>
<th>Hospital Post ID</th>
<th>GUID</th>
</tr>";

$hospTitle = array("");
$hospGuid = array("");
$numOfHospitals = 1;

while($row = mysqli_fetch_array($hospSet))
{
array_push($hospGuid, $row['guid']);
array_push($hospTitle, $row['post_title']);
echo "<tr>";
echo "<td>" . $row['ID'] . "</td>";
echo "<td>" . $hospGuid[$numOfHospitals] . "</td>";
echo "</tr>";
$numOfHospitals++;
}
echo "</table>";
echo "<br>";

echo "<strong>Doctors query: " . $docSelect . "</strong>";
$docSet = mysqli_query($con,$docSelect);

$numOfDoctors = 0;

echo "<table border='1'>
<tr>
<th>Doctor Post ID</th>
<th>GUID</th>
<th>Content</th>
</tr>";

while($row = mysqli_fetch_array($docSet) and $numOfDoctors < 1)
{
$post_content = $row['post_content'];
echo "<tr>";
echo "<td>" . $row['ID'] . "</td>";
echo "<td>" . $row['guid'] . "</td>";
echo "<td>" . $post_content . "</td>";
echo "</tr>";
$numOfDoctors++;

$finalDocPost = replaceTitleWithHyperlink($post_content, $hospGuid, $hospTitle);

if(strlen($finalDocPost) > 0)
{
$docUpdate = "update wp_posts set post_content = '" . $finalDocPost . "' where ID = " . $row['ID'];

echo "<br><br> The update statement is: " . $docUpdate;

if($update_pref == "Yes")
{
mysqli_query($con,$docUpdate);
}
}
else
{
echo "<p style=\"color:red;margin-left:20px;\">";
echo "<br>There was ambiguity found while matching hospitals.</p><br>";
}
}
echo "<br><br>Number of doctors found: " . $numOfDoctors . "<br>";

echo "</table>";
echo "<br>";
echo "<br>";
}
mysqli_close($con);
?>

Using TableLayout and dynamically populating views in Android

Useful links are follow: http://forum.codecall.net/topic/70354-tablelayout-programatically/

Sample Code:

public void drawScreen(ArrayList<Product> products) {
tl.removeAllViews();
sv.removeAllViews();

TableRow.LayoutParams params = new TableRow.LayoutParams();
params.gravity = Gravity.CENTER_VERTICAL;

for(int i=0;i<products.size();i++) {
TableRow tr = new TableRow(this);
//View v = (RelativeLayout)findViewById(R.layout.product_row);
TextView tv = new TextView(this);
ImageView iv = new ImageView(this);
CheckBox cb = new CheckBox(this);
cb.setOnClickListener(this);
checkboxes.add(cb);
iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_launcher));
cb.setLayoutParams(params);
//cb.setOnCheckedChangeListener(this);
tv.setText(products.get(i).getAsin());
tv.setGravity(Gravity.CENTER_VERTICAL);
tv.setWidth(200);
tr.addView(iv);
tr.addView(tv);
tr.addView(cb);
tr.setGravity(Gravity.CENTER);
tr.setBackground(getResources().getDrawable(R.drawable.rectangle));
tl.addView(tr);
}
TableRow tr = new TableRow(this);
tr.setGravity(Gravity.CENTER);
compareButton = new Button(this);
compareButton.setText("Compare");
compareButton.setOnClickListener(this);
tr.addView(compareButton);
tl.addView(tr);
sv.addView(tl);
setContentView(sv);
}

Communicating non-primitive data objects between Android Activities

Non-primitive types such as ArrayLists can be communicated between Activities in Android using Parcelable interface.
Sample Example:
Class Definition:


package com.example.comparisonapp;

import android.os.Parcel;
import android.os.Parcelable;

public class Product implements Parcelable{
private String asin;
private String imageUrl;
private String description;
private String title;
private Double rating = 0.0;

public String getAsin() {
return asin;
}
public void setAsin(String asin) {
this.asin = asin;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Double getRating() {
return rating;
}
public void setRating(Double rating) {
this.rating = rating;
}

public Product() {;}

public Product(Parcel in) {
this.asin = in.readString();
this.imageUrl = in.readString();
this.description = in.readString();
this.title = in.readString();
this.rating = in.readDouble();
}

@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void writeToParcel(Parcel arg0, int arg1) {
// TODO Auto-generated method stub
arg0.writeString(asin);
arg0.writeString(imageUrl);
arg0.writeString(description);
arg0.writeString(title);
arg0.writeDouble(rating);
}

public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public Product createFromParcel(Parcel in) {
return new Product(in);
}
public Product[] newArray(int size) {
return new Product[size];
}
};
}


Caution:
1. The order of reading data from the Parcel in Parcel argument constructor must be the same as order of writing the data in the Parcel in the writeToParcel method.

Initializing the objects of the class and sending as intent.

products = new ArrayList<Product>();
for(int i=0;i<3;i++) {
Product product = new Product();
product.setAsin("asin " + i);
product.setTitle("Title " + i);
product.setDescription("description " + i);
product.setRating(4.5);
product.setImageUrl("imageUrl");
products.add(product);
}
intent.putExtra("products", products);
startActivity(intent);


Reading the data from the intent

Intent intent = getIntent();
ArrayList<Product> products = intent.getExtras().getParcelableArrayList("products");
for(int i=0;i<products.size();i++) {
Toast.makeText(getApplicationContext(), "Got: " + String.valueOf(products.get(i).getAsin()), Toast.LENGTH_SHORT).show();
}