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);
?>

No comments:

Post a Comment