Friday, July 3, 2009

searching and updating a database

search.html is the search form. passes the data to dbsearch.php
dbsearch.php  searches the database and presents the found records. passes the records to view.php for viewing or editinfo.php to edit the record.
dbsearch.php takes the record Id, adds it to a link and passes it thus to the required programs.
For a full explanation of the programs editinfo and update info, check it’s source


---search.html-------
<body>     
<link href="style.css" type="text/css" rel="stylesheet" />     
<link rel="stylesheet" type="text/css" href="style.css" /> 
<form action="dbsearch.php" method="get">    
Keywoord uit Acteur of Titel: <input type="text" name="q" />     
<br>    
<input type="submit" />     
</form>     
<body> 
------dbsearch.php----------------
<?php     
    include 'db.php';    // Include the database     
    // Set the page, use one if the get page is not a number or is negative     
    if(!isset($_GET['page']) || !ctype_digit($_GET['page']))     
        $page = 1;     
    else     
        $page = $_GET['page'];     
    // Set the maximum number of results     
    $max = 10;     
    // Set the start location (when viewing the next page)     
    $limit = ($page * $max) - $max;     
    $q = trim(mysql_real_escape_string($_GET['q'])); // Make a safe string     
    // Make a query, (change "code" and "name" to your column names)     
    $query = "SELECT SQL_CALC_FOUND_ROWS *,     
            MATCH(Titel) AGAINST ('$q' IN BOOLEAN mode) AS score1,     
            MATCH(Acteur) AGAINST ('$q' IN BOOLEAN mode) AS score2     
            FROM DVD     
            WHERE  
            MATCH(Titel,Acteur) AGAINST ('$q' IN BOOLEAN mode)     
            ORDER BY score1 DESC, score2 DESC LIMIT $limit, $max";     
    // Perform the query     
    $sql = mysql_query($query); 
    // Find how many results would have been returned if there wasn't a limit     $result_count = mysql_query("SELECT FOUND_ROWS()")or die(mysql_error());     // Get the number     $total = mysql_fetch_array($result_count);     // Search the array for the total     $totalrows = $total[0];     // Calculate the number of pages, if it is a decimal, then there are     // more reusults, but that number is less than our $max (total number of results     // to display on the page)     $pages = ceil($totalrows / $max);     // Display the results...     if(mysql_num_rows($sql) > 0){         echo '<p>Found <b>'.$totalrows.'</b> results for <b>"'.htmlentities($_GET['q']).'"</b></p>';         $i = $limit + 1;         while($row = mysql_fetch_array($sql)){             echo '<p>'.$i.'. <a href="view.php?id='.$row['x'].'">'.$row['Titel'].'</a>';             echo ' <b ><a href="editinfo.php?id='.$row['x'].'">Edit Data</a></b></p>';             $i++;         }     }else{         // No results were found         echo '<h2>No Results Found!</h2>';     }     // Display the page numbers (if there is more than one page)     if($pages > 1){         echo '<div style="padding:10px;">';             for($i = 1;$i<$pages+1;$i++){                 if($i == $page)                     echo '<span class="page" style="padding:10px;">'.$i.'</span>';                 else                     echo '<a style="padding:10px;" href="'.$_SERVER['PHP_SELF'].'?q='.$_GET['q'].'&amp;page='.$i.'">'.$i.'</a>';             }             echo '<span style="clear:both;display:block;font-size:1px;">&nbsp;</span>';         echo '</div>';     } // Sluit de database echo mysql_error(); mysql_close($db); ?>
-------view.php-------------------------
<?     
$id = trim(mysql_real_escape_string($_GET['id'])); // Make a safe string     
//echo $id;     
include 'db.php';    // Include the database     
$query=("SELECT * FROM DVD WHERE x=$id ORDER BY Titel ASC ")  or die (mysql_error());     
//echo $query;     
$result=mysql_query($query);     
//echo $result;     
$row = mysql_fetch_array($result);     
$x= $row[0];     
$titel= $row[1];     
$acteur = $row[2];     
$taal= $row[3];     
$jaar= $row[4];     
$imdb = $row[5];     
$summary=$row[6];     
$foto=$row[7];     
?> 
<div class="example1">    
<?php     
echo '<b>';     
echo $titel;     
echo '</b><br /><em>';     
echo $acteur;     
echo '</em><br />';     
echo $taal;     
echo '<br />';     
echo $jaar;     
echo '<br />';     
echo "<a href='{$row['IMDB']}'>$titel at imdb</a>";     
echo '<br />';     
echo $summary;     
echo '<br />';     
echo "<img src='{$row['Foto']}' >"; 
// Sluit de database    
echo mysql_error();     
mysql_close($db); 
?>    
</div> 
-------------- editinfo.php---------
This file is a slight alteration from the file found Here
<?php    
$id = trim(mysql_real_escape_string($_GET['id'])); // Make a safe string     
//replace usernaem,password, and yourdb with the information for your database     
mysql_connect("localhost","zz","zz") or die("Error: ".mysqlerror());     
mysql_select_db("DVD"); 
//replace TestTable with the name of your table    
//also in a real app you would get the id dynamically     
$sql = "select * from `DVD` where x = $id";     
$query = mysql_query($sql); 
while ($row = mysql_fetch_array($query)){ 
    $id = $row['x'];    
    $titel = $row['Titel'];     
    $acteur = $row['Acteur'];  
    $taal = $row['Taal'];     
    $jaar = $row['Jaar'];     
    $imdb = $row['IMDB'];  
    $summary =  $row['Summary'];     
    $foto = $row['Foto']; 
    //we will echo these into the proper fields 
}    
mysql_free_result($query);     
?> 
<html>    
<head>     
<title>Edit DVD Info</title>     
</head> 
<body> 
<form action="updateinfo.php" method="post"> 
id:<br/>    
<input type="text" value="<?php echo $id;?>" name="x" disabled />     
<input type="hidden" value="<?php echo $id;?>" name="x"  />     
<br/> 
-------------updateinfo.php-----------
see here for full description
Titel:<br/>     
<input type="text" value="<?php echo $titel;?>" name="Titel" size=60/> 
<br/> 
Acteur:<br/>    
<input type="text" value="<?php echo $acteur;?>" name="Acteur" size=60/> 
<br/> 
Taal:<br/>    
<input type="text" value="<?php echo $taal;?>" name="Taal"/> 
<br/> 
Jaar:<br/>    
<input type="text" value="<?php echo $jaar;?>" name="Jaar" size=10/> 
<br/> 
IMDB:<br/>    
<input type="text" value="<?php echo $imdb;?>" name="IMDB" size=38/> 
<br/>    
Summary:<br/>     

<TEXTAREA NAME="Summary"  ROWS=6 COLS=45>     
<?php echo $summary;?>     
</TEXTAREA>     
<br/> 
Foto locatie:<br/>    
<input type="text" value="<?php echo $foto;?>" name="Foto" size=59/> 
</br> 
<input type="submit" value="submit changes"/> 
</form>    
</body>     
</html>

Sunday, June 7, 2009

Rename file if exists in PHP

function rename_if_exists($dir, $filename) {
    $ext = strrchr($filename, '.');
    $prefix = substr($filename, 0, -strlen($ext));
    $i = 0;
    while(file_exists($dir . $filename)) { // If file exists, add a number to it.
        $filename = $prefix . ++$i . $ext;
    }

    return $filename;
}

Download youtube video’s with PHP

<?
//example string for the function
get_youtube_download_link("http://www.youtube.com/watch?v=8yOa-7fHNwo&feature=rec-HM-r2");

function str_between($string, $start, $end){ $string = " ".$string;
$ini = strpos($string,$start); if ($ini == 0) return ""; $ini +=
strlen($start); $len = strpos($string,$end,$ini) - $ini; return
substr($string,$ini,$len); }
function get_youtube_download_link($url){
if( $url !== "")
{
$youtube_link = $url;
//$url = get_post_meta($post->ID, 'url', true);
if ( file_get_contents($youtube_link) !== "")
{
$youtube_page = file_get_contents($youtube_link);
$v_id = str_between($youtube_page, "&video_id=", "&");
$t_id = str_between($youtube_page, "&t=", "&");
$flv_link = "http://www.youtube.com/get_video?video_id=$v_id&t=$t_id";
$hq_flv_link = "http://www.youtube.com/get_video?video_id=$v_id&t=$t_id&fmt=6";
$mp4_link = "http://www.youtube.com/get_video?video_id=$v_id&t=$t_id&fmt=18";
$threegp_link = "http://www.youtube.com/get_video?video_id=$v_id&t=$t_id&fmt=17";
echo "\t\tDownload (right-click &gt; save as)&#58;\n\t\t";
echo "<a href=\"$flv_link\">FLV</a>\n\t\t";
echo "<a href=\"$hq_flv_link\">HQ FLV (if available)</a>\n\t\t";
echo "<a href=\"$mp4_link\">MP4</a>\n\t\t";
echo "<a href=\"$threegp_link\">3GP</a><br><br>\n";
}
}
}
?>

Show the last x number of posts on Wordpress in PHP

This code shows the last x-number of posts (15 in this example) in your wordpress blog. Make sure you put in the proper directory in the ‘require()’  string. This code can be on a completely seperate page, fully outside of wordpress

<?php
// Include Wordpress
define('WP_USE_THEMES', false);
require('./wordpress/wp-blog-header.php');
query_posts('showposts=15');
?>

<ul>
<?php while (have_posts()): the_post(); ?>
    <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; ?>
</ul>

Copy an image from a remote URL to a local file

 

This code copies the remote image to your local server. it is pretty basic as it does not check if the file already exists. For that, use the rename if exist function.

<?
//original image
$img = "http://www.images.com/anyimage.jpg";
//isolate the filename from the URL
$fname= basename($img); 
//directory to copy to (must be CHMOD to 777)
$copydir = "/var/www/upload/";   // change as required
$data = file_get_contents($img);
$file = fopen($copydir . $fname, "w+");
fputs($file, $data);
fclose($file);
?>

Other possibility:


// example usage: download_file('whatever.jpg');
function download_file($filename, $mimetype = 'application/octet-stream')
{
  if (!file_exists($filename) || !is_readable($filename)) return false;
  $base = basename($filename);
  header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  header("Content-Disposition: attachment; filename=$base");
  header("Content-Length: " . filesize($filename));
  header("Content-Type: $mimetype");
  readfile($filename);
  exit();
}

-------------------------------------

A third possibility:

<?php
$handle = fopen(“http://content8.flixster.com/photo/10/89/19/10891930_tml.jpg”, "rb");
$contents = '';
while (!feof($handle)) {
  $contents .= fread($handle, 8192);
}
fclose($handle);
?>

De $contents can then be saved

 

Or even simpler:

<?
getfile('http://content8.flixster.com/photo/10/89/19/10891930_tml.jpg','upload' );

// $url is the url of the file
// $dir is the directory to save the file to relative to the current working directory
function getfile($url, $dir){
file_put_contents($dir.substr($url,strrpos($url,'/'),strlen($url)), file_get_contents($url));
}
?>

Obviously this works for non-image files as well

Tuesday, May 12, 2009

Hosting various websites on one server with PHP

If you want to host various websites that have their own domain name on your own server then this is how you do that with PHP.

Suppose you have two domainnames blog.serveftp.com and wiki.serveftp.com. You want your server to redirect incoming calls to the proper website that you host yourself. You have set up 2 domains called: www.my_blog.com and www.my_wiki.com. On your server you have set up 2 directories in the root that contain your blog software and your wiki software.

Create an index.php file in your root that goes as follows

<?php
if ( getenv("HTTP_Host") == "www.my_blog.com" ) {
header("Location: http://your_ip/wordpress");
} elseif (getenv("HTTP_Host") == "www.my_wiki.com") {
header("Location: http://your_ip/wiki");
}
?>

depending on how you set up your blog and wiki software, you may need to include a startup file to your redirect address.

This is also possible if your connection with the internet is a dynamic IP number:

In that case take out a free account on http://www.no-ip.com e.g. http://my_name.serveblog.com and install their agent.

 

Your redirects in the above code then become http://my_name.serveblog.com/wordpress and http://my_name.serveblog.com/wiki

Alternating colors in MySQL tabel with PHP

This code changes the color of alternating rows of a database output. There is a difference in results if used with Firefox as opposed to IE. In the former, no white grid will be visible while in the latter, a white grid will be visible as shown below

 

<?php
$dbhost = 'localhost'; // choose as needed 
$dbuser = 'xxx';  // choose as needed 
$dbpass = 'yyyy';  // choose as needed 
$dbname = 'DVD';  // choose as needed 
$tablename = 'DVD';  //choose as needed

//Connect to server and select database
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die("No connection");
//mysql_connect($dbhost, $dbuser, $dbpass) or die("No Connection");
mysql_select_db($dbname);

//Do the SQL
$query=("SELECT * FROM $tablename  ORDER BY Titel ASC ")  or die (mysql_error());
$result=mysql_query($query);

//variables for the table
$count=1;

// for greyish table
$akleur1="#CCCCCC";
$akleur2="#C0C0C0";

// uncomment and use for colorfull table 
// $akleur1="#C6FF00";
// $akleur2="#FFC600";

$kleur=$akleur1;

//Table heading and loop
echo"<table border='0'><tbody>";
echo"<tr><td><b>Nr</b></td><td><b>Titel</b></td><td><b>Acteur</b></td><td><b>Jaar</b></td><td><b>Summary</b></td><td>IMDB</td></tr>";
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{

    echo "<tr bgcolor=$kleur><td>$count</td><td>{$row['Titel']}</td>" .
         "<td><em>{$row['Acteur']}</em></td>" .
         "<td>{$row['Jaar']}</td>" .
         "<td>{$row['Summary']}</td>" .
         "<td><a href='{$row['IMDB']}'>imdb</a><td></tr>";

$count=$count+1;

if($kleur==$akleur1){
$kleur=$akleur2;
}
else {
$kleur=$akleur1;
}
}
echo "</tbody></table>";

// Close database
echo mysql_error();
mysql_close($conn);
?>