PHP - Creating Image Links From Database
Hi there
I've been working with some code to display a single record on page. This all works fine and I'm able to pull what I want from the database. My problems is trying to use that data and turning it into something else like a link. I have a field in the database called image url which contains rows of image urls. So here is the problem area of the code: Code: [Select] <?php //////Displaying Data///////////// $id=$_GET['id']; // Collecting data from query string if(!is_numeric($id)){ // Checking data it is a number or not echo "Data Error"; exit; } $fetch=mysql_query("select * from productfeeds where ProductID=$id "); $row=mysql_fetch_object($fetch); echo mysql_error(); echo "<table>"; echo " <tr><td><b>ProductID</b></td><td>$row->ProductID</td></tr> <tr><td><b>ProductName</b></td><td>$row->ProductName</td></tr> <tr><td><b>ProductPrice</b></td><td>$row->ProductPrice</td></tr> //problem area for me <tr><td><b>Image</b></td><td>$row->ImageURL</td></tr> echo "</table>"; I'm trying to edit this part of the code: <tr><td><b>Image</b></td><td>$row->ImageURL</td></tr> I've tried this: <tr><td><b>Image</b></td><td><a href='{$row['URL']}'> <img src='{$row['ImageURL']}'></a> and <tr><td><b>Image</b></td><td><a href='$row['URL']'> <img src='$row['ImageURL']'></a> //removed brackets but I'm just getting errors. Can you guys help please? Thank you very much. Similar TutorialsGreetings, What I'm trying to do is have users upload their event information into a database which would include a flyer. I don't want the image file to go into the database (other than the filename) rather I'd like it to be dropped into a directory. In the same script I'd like to dynamically generate a thumbnail. I have the two scripts and separately they work fine, but I can't get them to work together. I'm guessing the conflict because the thumbnail script is using $_POST and the mysql script is using $_SESSION. If so how can I modify them to both use $_SESSION? The thumbnail script is goes from line 1 - 146 and the mysql portion is the rest. The results of processing this look something like this. QUERY TEXT: INSERT INTO td_events (eventgenre_sel, eventname, eventvenue, eventdate, eventgenre, eventprice, eventpromoter, eventflyer) VALUES ('12', 'spooky times', 'Ironwood Stage & Grill', '2010-12-17 22:36:00', 'DNB', '5000', 'me', '174366-1.jpg') <?php $debug = FALSE; /********************************************************************************************** CREATES THUMBNAIL **********************************************************************************************/ //define a maxim size for the uploaded images define ("MAX_SIZE","1024"); // define the width and height for the thumbnail // note that theese dimmensions are considered the maximum dimmension and are not fixed, // because we have to keep the image ratio intact or it will be deformed define ("WIDTH","500"); define ("HEIGHT","650"); // this is the function that will create the thumbnail image from the uploaded image // the resize will be done considering the width and height defined, but without deforming the image function make_thumb($img_name,$filename,$new_w,$new_h) { //get image extension. $ext=getExtension($img_name); //creates the new image using the appropriate function from gd library if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext) || !strcmp("JPG",$ext)) $src_img=imagecreatefromjpeg($img_name); if(!strcmp("png",$ext) || !strcmp("PNG",$ext)) $src_img=imagecreatefrompng($img_name); //gets the dimmensions of the image $old_x=imageSX($src_img); $old_y=imageSY($src_img); // next we will calculate the new dimmensions for the thumbnail image // the next steps will be taken: // 1. calculate the ratio by dividing the old dimmensions with the new ones // 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable // and the height will be calculated so the image ratio will not change // 3. otherwise we will use the height ratio for the image // as a result, only one of the dimmensions will be from the fixed ones $ratio1=$old_x/$new_w; $ratio2=$old_y/$new_h; if($ratio1>$ratio2) { $thumb_w=$new_w; $thumb_h=$old_y/$ratio1; } else { $thumb_h=$new_h; $thumb_w=$old_x/$ratio2; } // we create a new image with the new dimmensions $dst_img=ImageCreateTrueColor($thumb_w,$thumb_h); // resize the big image to the new created one imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y); // output the created image to the file. Now we will have the thumbnail into the file named by $filename if(!strcmp("png",$ext)) imagepng($dst_img,$filename); else imagejpeg($dst_img,$filename); //destroys source and destination images. imagedestroy($dst_img); imagedestroy($src_img); } // This function reads the extension of the file. // It is used to determine if the file is an image by checking the extension. function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } // This variable is used as a flag. The value is initialized with 0 (meaning no error found) // and it will be changed to 1 if an error occurs. If the error occurs the file will not be uploaded. $errors=0; // checks if the form has been submitted if(isset($_POST['Submit'])) { //reads the name of the file the user submitted for uploading $image=$_FILES['eventflyer']['name']; // if it is not empty if ($image) { // get the original name of the file from the clients machine $filename = stripslashes($_FILES['eventflyer']['name']); // get the extension of the file in a lower case format $extension = getExtension($filename); $extension = strtolower($extension); // if it is not a known extension, we will suppose it is an error, print an error message // and will not upload the file, otherwise we continue if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "JPG") && ($extension != "PNG") && ($extension != "png")) { echo '<h1>Unknown extension!</h1>'; $errors=1; } else { // get the size of the image in bytes // $_FILES[\'image\'][\'tmp_name\'] is the temporary filename of the file in which // the uploaded file was stored on the server $size=getimagesize($_FILES['eventflyer']['tmp_name']); $sizekb=filesize($_FILES['eventflyer']['tmp_name']); //compare the size with the maxim size we defined and print error if bigger if ($sizekb > MAX_SIZE*500) { echo '<h1>You have exceeded the size limit!</h1>'; $errors=1; } //we will give an unique name, for example the time in unix time format $image_name=$filename; //the new name will be containing the full path where will be stored (images folder) $newname="flyers/".$image_name; $copied = copy($_FILES['eventflyer']['tmp_name'], $newname); //we verify if the image has been uploaded, and print error instead if (!$copied) { echo '<h1>Copy unsuccessfull!</h1>'; $errors=1; } else { // the new thumbnail image will be placed in images/thumbs/ folder $thumb_name='flyers/thumb_'.$image_name; // call the function that will create the thumbnail. The function will get as parameters // the image name, the thumbnail name and the width and height desired for the thumbnail $thumb=make_thumb($newname,$thumb_name,WIDTH,HEIGHT); }} }} //If no errors registred, print the success message and show the thumbnail image created if(isset($_POST['Submit']) && !$errors) { echo "<h1>Thumbnail created Successfully!</h1>"; echo '<img src="'.$thumb_name.'">'; } /************************************************************ Adjust the headers... ************************************************************/ header("Expires: Thu, 17 May 2001 10:17:17 GMT"); // Date in the past header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified header ("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 header ("Pragma: no-cache"); // HTTP/1.0 /***************************************************************************** Check the session details. we will store all the post variables in session variables this will make it easier to work with the verification routines *****************************************************************************/ session_start(); if (!isset($_SESSION['SESSION'])) require_once( "../include/session_init.php"); $arVal = array(); require_once("../include/session_funcs1.php"); reset ($_POST); while (list ($key, $val) = each ($_POST)) { if ($val == "") $val = "NULL"; $arVals[$key] = (get_magic_quotes_gpc()) ? $val : addslashes($val); if ($val == "NULL") $_SESSION[$key] = NULL; else $_SESSION[$key] = $val; if ($debug) echo $key . " : " . $arVals[$key] . "<br>"; } /********************************************************************************************** Make sure session variables have been set and then check for required fields otherwise return to the registration form to fix the errors. **********************************************************************************************/ // check to see if these variables have been set... if ((!isset($_SESSION["eventname"])) || (!isset($_SESSION["eventvenue"])) || (!isset($_SESSION["eventdate"])) || (!isset($_SESSION["eventgenre"])) || (!isset($_SESSION["eventprice"])) || (!isset($_SESSION["eventpromoter"])) || (!isset($_SESSION["eventflyer"]))) { resendToForm("?flg=red"); } // form variables must have something in them... if ($_SESSION['eventname'] == "" || $_SESSION['eventvenue'] == "" || $_SESSION['eventdate'] == "" || $_SESSION['eventgenre'] == "" || $_SESSION['eventprice'] == "" || $_SESSION['eventpromoter'] == "" || $_SESSION['eventflyer'] == "") { resendToForm("?flg=red"); } /********************************************************************************************** Insert into the database... **********************************************************************************************/ $conn = mysql_connect($_SESSION['MYSQL_SERVER1'],$_SESSION['MYSQL_LOGIN1'],$_SESSION['MYSQL_PASS1']) or die ('Error connecting to mysql'); mysql_select_db($_SESSION['MYSQL_DB1']) or die("Unable to select database"); $eventgenre_sel = addslashes($_REQUEST['eventgenre_sel']); $eventname = addslashes($_REQUEST['eventname']); $eventvenue = addslashes($_REQUEST['eventvenue']); $eventdate = addslashes($_REQUEST['eventdate']); $eventgenre = addslashes($_REQUEST['eventgenre']); $eventprice = addslashes($_REQUEST['eventprice']); $eventpromoter = addslashes($_REQUEST['eventpromoter']); $eventflyer = addslashes($_REQUEST['eventflyer']); $sqlquery = "INSERT INTO td_events (eventgenre_sel, eventname, eventvenue, eventdate, eventgenre, eventprice, eventpromoter, eventflyer) " ."VALUES ('$eventgenre_sel', '$eventname', '$eventvenue', '$eventdate', '$eventgenre', '$eventprice', '$eventpromoter', '$eventflyer')"; echo 'QUERY TEXT:<br />'.$sqlquery; $result = MYSQL_QUERY($sqlquery); $insertid = mysql_insert_id(); /*** This following function will update session variables and resend to the form so the user can fix errors ***/ function resendToForm($flags) { reset ($_POST); // store variables in session... while (list ($key, $val) = each ($_POST)) { $_SESSION[$key] = $val; } // go back to the form... //echo $flags; header("Location: /user_registration.php".$flags); exit; } mysql_close($conn); ?> Hello, I am completely new to php so please forgive me ahead of time. I am trying to create a link button on a website for a client that only directs to a certain external website on certain days and hours. Specifically, this is a web radio button that the client only wants to link to the web radio site when their live broadcast is on the air during certain hours on the weekend (i.e. Sundays 8-10 PM). Any other time, the client wants the web radio button to link to a default page since the web radio station plays unrelated music all other hours of the week. Does anyone know the best way to create such a time sensitive link for a button on a webpage? Thanks. Hi guys, I'm currently in the process of making a simple social networking type site for a uni project and have basically everything i want except the ability to use AJAX to link to my profiles in the search bar. I have this code to generate my XML: Code: [Select] <?php // create simplexml object $xml = new SimpleXMLElement('<rss version="2.0"></rss>'); // add channel information $xml->addChild('channel'); $xml->channel->addChild('title', 'The Social Network'); $xml->channel->addChild('link', 'http://reecesayer.com/projects/template/XML/news.rss'); $xml->channel->addChild('description', 'example'); // query database for article data include("phpfunctions.php"); db_connect(); $link = "www.reecesayer.com/projects/template/testprofile.php?id="; $select='SELECT email, id FROM users'; $result = mysql_query($select) or die(mysql_error()); while ($row = mysql_fetch_assoc($result)) { // add item element for each article $item = $xml->channel->addChild('item'); $item->addChild('email', $row['email']); $item->addChild('link', $row['id']); //I wanted to add a link before the $row['id'] } // save the xml to a file $xml->asXML('profiles.xml'); header ('Location: http://reecesayer.com/projects/template/XML/profiles.xml'); ?> I need to add a partial URL (http://reecesayer.com/projects/template/testprofile.php?id=) before the row is called so that when the email is searched it provides a link to the profile depending upon the id (http://reecesayer.com/projects/template/testprofile.php?id=8) Is there an easier way to do this or am i going the long way around? I'm only storing the data in XML as i saw a tutorial for a livesearch script on another site. Cheers, Reece Hi Everyone, I'm semi-new to php and trying to create a site where I have only one includes file for my navigation (main_nav.inc) and 2-3 includes files (main_template.inc) that act as templates. I then call the the nav and the template in my index.php file. Everything was working fine until I decided I should use php have my links appear active depending on which page the user is on. Everything works totally fine if I insert the code for my nav (including both the html and php) into my main_template.inc file but when I make that code into it's own includes file (main_nav.inc), I get an error. I believe the issue is with using both single and double quotes in my code and wrapping that code in single quotes in my main_nav.inc file. Here is the code from my main_nav.inc file: <?php $main_nav = ' <div id="mainNav"><ul id="mainNav"> <li><a href="index.php" <?php if ($page=='index.php') { ?> class="active" <?php } ?>>Welcome</a></li> <li><a href="healthcare.php" <?php if ($page=='healthcare.php') { ?> class="active" <?php } ?>>Healthcare</a></li> </ul></div> '; // end main_nav ?> I think that since the code is wrapped in single quotes, I can only use double quotes in my code. This is the only difference I can figure out between inserting the code into the template directly (which works perfectly fine) and inserting it as a separate inc file. When I use the main_nav.inc file I get the following error: Parse error: syntax error, unexpected T_STRING in /home/content/k/a/l/kalilaks3/html/includes/main_nav.inc on line 11 I tried changing the quotes around ($page=='index.php') to ($page=="index.php") but that causes the browser to literally read the name of the link a class="active">Welcome I also tried variations of escaping quotes such as ($page==\"index.php\") and even escaping the other quotes and wrapping everything in double quotes as opposed to single quotes. Here is my code for my main_template.inc file <?php $page = basename($_SERVER['SCRIPT_NAME']); $page_title = "Welcome"; include_once ("includes/main_nav.inc"); // sets variable include_once ("home_template.inc"); // sets all variables ?> And here is my index.php file: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta content="healthcare" name="keywords"></meta> <meta content="healthcare" name="description"></meta> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title><?php echo $page_title; ?></title> <link rel = "stylesheet" href = "_css/layout.css"></link> <script type="text/javascript" src="scripts/script.js"></script> </head> <body> <div id = "header"><div id = "globalHeader"> <?php echo $main_nav; ?> </div></div> </body> </html> Any help or suggestions would be greatly appreciated!!! I would love to get this figured out so that I only have to create my navigation once for all my sites! I have a array for example: Code: [Select] $item = array( "Great <em>Bittern</em>"=>"Botaurus stellaris", "Little <em>Grebe</em>"=>"Tachybaptus ruficollis", "Black-necked Grebe"=>"Podiceps nigricollis"); which will output Code: [Select] Array ( [Great Bittern] => Botaurus stellaris [Little Grebe] => Tachybaptus ruficollis [Black-necked Grebe] => Podiceps nigricollis ) how can I input data from a database so it comes out as the array assuming I have $row[3] and $row[0] as the data? for example Code: [Select] while($row=mysql_fetch_array($result)){ //$item.=array($row[3],$row[0]); //array_push($item,array($row[3]=>$row[0])); //$item.=array($row[3]=>$row[0]); $item.="[".$row[3]."]=>".$row[0]; } which of course doesnt work?? Hello, I've created a page search to return results from my database inventory. On top of these results I would like to display a seperate list of five products not included in the search results but share the same sub_category_b (a column in my SQL table). Posted below is my primary query of the database. If anyone can help me out with this it would be appreciated. Code: [Select] $colname_product = "-1"; if (isset($_GET['title'])) { $colname_product = $_GET['title']; } mysql_select_db($database_inventory, $inventory); $query_product = sprintf("SELECT * FROM inventory WHERE item_name LIKE %s OR item_desc LIKE %s ", GetSQLValueString("%" . $colname_product . "%", "text"),GetSQLValueString("%" . $colname_product . "%", "text")); $product = mysql_query($query_product, $inventory) or die(mysql_error()); $row_product = mysql_fetch_assoc($product); I've fooled around with this one for some time and haven't come up with a clear cut answer. Thank you in advance! Here is the sample page: http://hoosierhoopsreport.com/pg-test/ Trying to create a table that has three sections (groupings). That part I have figured out. The first grouping is sorted numerically. The second group is sorted alphabetically based on what part of the state they live in. It's breaking down this second part that I can't seem to get. (The third group is just what's left over, sorted alphabetically.) So it needs to look like this: (Each group and region have their own header row. Only Group 2 is broken down into Regions.) Group 1 Group 2 -Region 1 -Region 2 -Region 3 -Region 4 -Region 5 Group 3 The sample page above, in Group 2, it just shows Region 1 header. Code: [Select] $query = 'SELECT * FROM a_playerRank WHERE year="2015" and position="1" ORDER BY grouping DESC,rankPos,region,nameLast'; $results = mysql_query($query) or trigger_error('MySQL error: ' . mysql_error()); $currentGrouping = false; $currentRegion = false; while($line = mysql_fetch_assoc($results)) { if($currentGrouping != $line['grouping']) { //Status has changed, display status header $currentGrouping = $line['grouping']; if($line['grouping']==2) { echo '<thead> <tr> <th class="num">#</th> <th class="top">Top 10</th> <th class="height">HT</th>'; if (current_user_can("access_s2member_level4")){ echo '<th class="level">Level</th>'; } echo' <th class="school">City (School)</th>'; if (current_user_can("access_s2member_level4")){ echo '<th class="summer">Summer Team</th>'; } echo' <th class="college">College</th> </tr> </thead>'; } if($line['grouping']==1) {echo '<tr><th colspan="7">Best of the Rest</th></tr>'; if($currentRegion != $line['region']) { $currentRegion = $line['region']; echo '<tr><th colspan="7">Region' .$line['region'] . '</th></tr>';} } if($line['grouping']==0) echo '<tr><th colspan="7">Names to Know</th></tr>'; } Hello, I have found the following code which creates a sitemap from the home directory of files. Please could you point me in the right direction for changing this so that it looks up from my sql database and for each name within the database creates an entry in the sitemap (e.g. www.mysite.com/[NAME]). Thanks for your help, Stu Code: [Select] <?php /******************************************************************************\ * Author : Binny V Abraham * * Website: http://www.bin-co.com/ * * E-Mail : binnyva at gmail * * Get more PHP scripts from http://www.bin-co.com/php/ * ****************************************************************************** * Name : PHP Google Search Sitemap Generator * * Version : 1.00.A * * Date : Friday 17 November 2006 * * Page : http://www.bin-co.com/php/programs/sitemap_generator/ * * * * You can use this script to create the sitemap for your site automatically. * * The script will recursively visit all files on your site and create a * * sitemap XML file in the format needed by Google. * * * * Get more PHP scripts from http://www.bin-co.com/php/ * \******************************************************************************/ // Please edit these values before running your script. //////////////////////////////////// Options //////////////////////////////////// $url = "http://www.WEBSITE_NAME.com/"; //The Url of the site - the last '/' is needed $root_dir = ''; //Where the root of the site is with relation to this file. $file_mask = '*.php'; //Or *.html or whatever - Any pattern that can be used in the glob() php function can be used here. //The file to which the result is written to - must be writable. The file name is relative from root. $sitemap_file = 'sitemap.xml'; // Stuff to be ignored... //Ignore the file/folder if these words appear in the name $always_ignore = array( 'local_common.php','images' ); //These files will not be linked in the sitemap. $ignore_files = array( '404.php','error.php','configuration.php','include.inc' ); //The script will not enter these folders $ignore_folders = array( 'Waste','php_uploads','images','includes','lib','js','css','styles','system','stats','CVS','.svn' ); //The default priority for all pages - the priority of all pages will increase/decrease with respect to this. $starting_priority = ($_REQUEST['starting_priority']) ? $_REQUEST['starting_priority'] : 70; /////////////////////////// Stop editing now - Configurations are over //////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// function generateSiteMap() { global $url, $file_mask, $root_dir, $sitemap_file, $starting_priority; global $always_ignore, $ignore_files, $ignore_folders; global $total_file_count,$average, $lowest_priority_page, $lowest_priority; /////////////////////////////////////// Code //////////////////////////////////// chdir($root_dir); $all_pages = getFiles(''); $xml_string = '<?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.google.com/schemas/sitemap/0.84" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.google.com/schemas/sitemap/0.84 http://www.google.com/schemas/sitemap/0.84/sitemap.xsd"> <?php # '; $modified_priority = array(); for ($i=30;$i>0;$i--) array_push($modified_priority,$i); $lowest_priority = 100; $lowest_priority_page = ""; //Process the files foreach ($all_pages as $link) { //Find the modified time. $handle = fopen($link,'r'); $info = fstat($handle); fclose($handle); $modified_at = date('Y-m-d\Th:i:s\Z',$info['mtime']); $modified_before = ceil((time() - $info['mtime']) / (60 * 60 * 24)); $priority = $starting_priority; //Starting priority //If the file was modified recently, increase the importance if($modified_before < 30) { $priority += $modified_priority[$modified_before]; } if(preg_match('/index\.\w{3,4}$/',$link)) { $link = preg_replace('/index\.\w{3,4}$/',"",$link); $priority += 20; } //These priority detectors should be different for different sites :TODO: if(strpos($link,'example')) $priority -= 30; //If the page is an example page elseif(strpos($link,'demo')) $priority -= 30; if(strpos($link,'tuorial')) $priority += 10; if(strpos($link,'script')) $priority += 5; if(strpos($link,'other') !== false) $priority -= 20; //Priority based on depth $depth = substr_count($link,'/'); if($depth < 2) $priority += 10; // Yes, I know this is flawed. if($depth > 2) $priority += $depth * 5; // But the results are better. if($priority > 100) $priority = 100; $loc = $url . $link; if(substr($loc,-1,1) == '/') $loc = substr($loc,0,-1);//Remove the last '/' char. $total_priority += $priority; if($lowest_priority > $priority) { $lowest_priority = $priority;//Find the file with the lowest priority. $lowest_priority_page = $loc; } $priority = $priority / 100; //The priority is given in decimals $xml_string .= " <url> <loc>$loc</loc> <lastmod>$modified_at</lastmod> <priority>$priority</priority> </url>\n"; } $xml_string .= "</urlset>"; if(!$hndl = fopen($sitemap_file,'w')) { //header("Content-type:text/plain"); print "Can't open sitemap file - '$sitemap_file'.\nDumping result to screen...\n<br /><br /><br />\n\n\n"; print '<textarea rows="25" cols="70" style="width:100%">'.$xml_string.'</textarea>'; } else { print '<p>Sitemap was written to <a href="' . $url.$sitemap_file .'">'. $url.$sitemap_file .'></a></p>'; fputs($hndl,$xml_string); fclose($hndl); } $total_file_count = count($all_pages); $average = round(($total_priority/$total_file_count),2); } ///////////////////////////////////////// Functions ///////////////////////////////// // File finding function. function getFiles($cd) { $links = array(); $directory = ($cd) ? $cd . '/' : '';//Add the slash only if we are in a valid folder $files = glob($directory . $GLOBALS['file_mask']); foreach($files as $link) { //Use this only if it is NOT on our ignore lists if(in_array($link,$GLOBALS['ignore_files'])) continue; if(in_array(basename($link),$GLOBALS['always_ignore'])) continue; array_push($links, $link); } //asort($links);//Sort 'em - to get the index at top. //Get All folders. $folders = glob($directory . '*',GLOB_ONLYDIR);//GLOB_ONLYDIR not avalilabe on windows. foreach($folders as $dir) { //Use this only if it is NOT on our ignore lists $name = basename($dir); if(in_array($name,$GLOBALS['always_ignore'])) continue; if(in_array($dir,$GLOBALS['ignore_folders'])) continue; $more_pages = getFiles($dir); // :RECURSION: if(count($more_pages)) $links = array_merge($links,$more_pages);//We need all thing in 1 single dimentional array. } return $links; } //////////////////////////////// Display ///////////////////////////// ?> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.1 Transitional//EN"> <html> <head> <title>Sitemap Generation Using PHP</title> <style type="text/css"> a {color:blue;text-decoration:none;} a:hover {color:red;} </style> </head> <body> <h1>PHP Google Search Sitemap Generator Script</h1> <?php if($_POST['action'] == 'Create Sitemap') { generateSiteMap(); ?> <h2>Sitemap Created...</h2> <h2>Statastics</h2> <p><strong><?php echo $total_file_count; ?></strong> files were found and indexed.<br /> Lowest priority of <strong><?php echo $lowest_priority; ?></strong> was given to <a href='<?php echo $lowest_priority_page; ?>'><?php echo $lowest_priority_page; ?></a></p> Average Priority : <strong><?php echo $average; ?></strong><br /> <h2>Redo</h2> <?php } else { ?> <p>You can use this script to create the sitemap for your site automatically. The script will recursively visit all files on your site and create a sitemap XML file in the format needed by Google. </p> <p>You can customize the result by changing the starting priorities.</p> <h2>Set Starting Priority</h2> <?php } ?> <form action="create_sitemap.php" method="post"> Starting Priority : <input type="text" name="starting_priority" size="3" value="<?php echo $starting_priority; ?>" /> <input type="submit" name="action" value="Create Sitemap" /> </form> </body> </html> I'm trying to create a website, that echo's out a bunch of groups, where each group contains a group of checkboxes, containing A value, and a label for the checkbox, the way it is created right now, is foreach that echo's out a bunch of php arrays, which was easier than the static way before - But still, it's static in some way, or not very user friendly at the moment.. My problem is that I really want to write it in a database when I have the option. Is there anyone that can give some tips how to do? At the moment, my foreach looks like this: Code: [Select] echo '<form method="post" action="'.$_SERVER['PHP_SELF'].'">'; /* NEXT WE CREATE OUR FOREACH LOOPS TO ECHO THE HTML FOR LOOKS AND CHECKBOXES */ $totalID=0; // this is a counter we use to build our check box names foreach ($items as $list){ $totalID++; // add one to the checkbox name counter echo "<h2>{$list['title']}</h2>\n"; // and echo out our section header foreach ($list['items'] as $cbox){ // now for each item in the list, call it $cbox // $cbox now holds the item name, and point value echo "<label class='checkbox'><input type='checkbox' name='totals[$totalID][]' value='{$cbox[1]}'> {$cbox[0]}</label>\n"; } } echo "</form>"; And my array is something like this: Code: [Select] $items['computers']['title']='Computer Brand'; $items['computers']['items'][]=array('Apple iMac',1); $items['computers']['items'][]=array('Apple Macbook',.5); $items['phones']['title']='Phone Brand'; $items['phones']['items'][]=array('iPhone',1); $items['phones']['items'][]=array('HTC',1); As said, I can write this, but takes time. I want to get it into a database, that data above, but I'm having problems about echo'ing it out, I really can't see how I should do. My current database looks like this: Thank you! hello, i am hoping someone can help, i have a form that has a body and title fields and then sends to this function below. it all works fine, but when i add a image or a link it stores it in the text field of the db like this: <IMG alt=\"\" src=\"/public/images/231781538234094.jpg\" width=796></P> this is what it should be /public/images/231781538234094.jpg so when i view the image it doesent show it and i right click the image and goto image properties and i get this: http://test.cyberglide.co.uk/%22public/images/231781538234094.jpg/%22 Code: [Select] function content_update() { $title = mysql_real_escape_string($_POST['title']); $body = mysql_real_escape_string($_POST['body']); $page = mysql_real_escape_string($_POST['page']); $location = mysql_real_escape_string($_POST['location']); $id = mysql_real_escape_string($_POST['id']); $sql = "UPDATE content SET title = '$title', body = '$body', page = '$page', location = '$location' WHERE id = '$id'"; $res = mysql_query($sql) or die(mysql_error()); echo "<script>window.location='content.php'</script>"; } if i manually edit it on the db it works fine please help, many thanks. I have a php page where I have posts about different topic. I have a menu listing all this categories of topics . Some topics may belong to more than one category. So when i click on a particular menu item, the topic belonging to that category will be displayed. While displaying it is in this format---Topic Heading,Belongs to which all categories,date posted and the description. All this are taken from database. Now my actual issue is I am not able to give links to the categories dispalyed ,if the category exceeds more than 1. For eg: Global Warming Posted on March 11,2011 in News, Issue -----------description of global warming goes here. In the above eg: News and issue are the two categories,when i click on News it should display all the items in news category,and when i click on issue it should display all items of issue category. But I am not able to give this link to the categories. Code: [Select] while($row = mysql_fetch_array($q)) { if($row[6]=='News'){ $c='<a href="category_disp.php?category=news">News</a>'; } if($row[6]=='Issues'){ $c='<a href="category_disp.php?category=issues">Issues</a>'; } echo "<tr><td><p >$row[1]</p><br></td></tr>"; echo "<tr><td> <div >". "<p><span>$row[4]</span> <span>". "<a href='$row[6]' >$row[6]|<a href='$row[5]'> Post Comments</a></span></p>". "<p> </p></div><br></td></tr>"; echo "<tr><td><p >$row[2]</p><br></td></tr>"; echo "<tr><td><p ><a href='$row[3]' >Click Here to read more...</a></p></td></tr>"; echo "</div></td></tr>"; } echo" </table> Okay, I'll make this short and sweet, and all side comments are irrelevant. I'm doing this for my own happies So using Facebook.com's API you can extract all of a specific user's friends in an array. Well I'm making a array check to see who on that users friend list was removed or deleted them that week using array_dif(); in this method: 1) User allows the application 2) Application catches the user's friends_id's in an array and stores them // this is where i'm having trouble, i'll come back to it 3) User then waits a few days and notices their friend count is no longer 400, it's now 399! 4) User logs into my application, and checks the previously uploaded array against their current array of friends. Okay now to the part i'm struggling with is, what would you do? Should i store them each uniquely in a database? Because some users have 4,000+ friends and that gets quite strenuous. OR! Should i save them into a txt file unique to that person's user_id. I kind of like the 2nd option, however it's less ( to my newbish mind ) customizable versus the sql_queries. Once again, i'd like to reiterate, i don't care that this is again Facebooks terms of service, it's for my own personal gain and just enjoy taking on projects in my spare time that force my brain to work hard. That's all, hope you excuse the typos and poor grammar. Typed this pretty quickly, any questions - feel free to ask! Hello to all phpfreaks out there I need help with sorting some database columns. I ve been searching all day but i didnt found something nice to implement (or my mind is too tired to think right at this specific time) I have a table and inside it i display a picture and some other data.Above the table i inserted a div and inside it i have 5 links which when clicking on them i want to change the display order of the data being displayed in the table, and if clicked again to change again the state for ASC to DESC and so on... Is there any short solution that do the trick? With an array maybe? PS:I have also a pagination which i would like to keep the sorted order from the above table so not to mess around with the results. Thanks in advance I want to add some text onto an image. Sometimes I either get nothing returned or I get a shit load of garbage returned. Garbage in the form of little question mark symbols and other crap like that. PHP File - show Tickets Code: [Select] include("createImage.php"); while( $row = mysql_fetch_array( $r ) ){ echo generateTicket( $row['ticketNumber'] ) . "<br /><br />"; } PHP - createImage.php Code: [Select] <? header("Content-type: image/jpeg"); function generateTicket( $ticketNum ){ $imageFile = "images/ticket.jpeg"; if( file_exists( $imageFile ) ){ $im = @imagecreatefromjpg( $imageFile ); $text_color = imagecolorallocate( $im, 0, 0, 0 ); imagestring( $im, 6, 25, 150, $ticketNum, $text_color ); imagejpeg( $im ); }else echo 'error'; } ?> Hi, I've read a lot of places that it's not recommended to store binary files in my db. So instead I'm supposed to upload the image to a directory, and store the link to that directory in database. First, how would I make a form that uploads the picture to the directory (And what kinda directories are we talking?). Secondly, how would I retrieve that link? And I guess I should rename the picture.. I'd appreciate any help, or a good tutorial (Haven't found any myself). Hello,
I have a website called http://flappycreator.com/ where users can upload multiple images to create their own version of Flappy Bird. As a result of this I created a PHP page that takes a GET param to create a preview image of their game to display in various locations on the website.
Here is an example:
http://flappycreator...d=5305a9ad9dc30
http://flappycreator...d=5305a9ad9dc30
http://flappycreator...d=5305a9ad9dc30
My issue is, I have given my users the ability to upload PNGs or JPGs and trying to figure out reliable code to display the preview has become a huge hassle. In the example above the Pac-Man character shows a white background but when you play the game, it is actually transparent. In other situations I am getting extremely bad color distortion. The code I have provided is my final attempt after a ton of trial-and-error and the PNG imagealphablending() and imagesavealpha() commands have shown me the best results, however I don't know what they do.
Please help! Thanks.
<?php $bird_picture = "default/bird.png"; $tube1_picture = "default/tube1.png"; $tube2_picture = "default/tube2.png"; $ground_picture = "default/ground.png"; $bg_picture = "default/bg.png"; // If an id is set, then reset values if (isset ( $_GET ['id'] )) { require ('XXX.php'); $db = new DBAccess (); $query = "SELECT * FROM XXX WHERE XXX = '{$_GET['id']}'"; $result = $db->query ( $query ); $num_results = $result->num_rows; $row = mysqli_fetch_array ( $result ); if ($num_results != 0) { if ($row ['bird_picture'] != "") { $bird_picture = "instances/" . $row ['folder_dir'] . "/" . $row ['bird_picture']; } if ($row ['tube1_picture'] != "") { $tube1_picture = "instances/" .$row ['folder_dir'] . "/" . $row ['tube1_picture']; } if ($row ['tube2_picture'] != "") { $tube2_picture = "instances/" .$row ['folder_dir'] . "/" . $row ['tube2_picture']; } if ($row ['ground_picture'] != "") { $ground_picture = "instances/" . $row ['folder_dir'] . "/" . $row ['ground_picture']; } if ($row ['bg_picture'] != "") { $bg_picture = "instances/" . $row ['folder_dir'] . "/" . $row ['bg_picture']; } } } $temp = explode(".", $bg_picture); $extension = end($temp); if ($extension == "jpeg" || $extension == "jpg") { $background = imagecreatefromjpeg($bg_picture); } else { $background = imagecreatefrompng($bg_picture); // Turn off alpha blending and set alpha flag imagealphablending($background, true); imagesavealpha($background, true); } $temp = explode(".", $ground_picture); $extension = end($temp); if ($extension == "jpeg" || $extension == "jpg") { $ground = imagecreatefromjpeg($ground_picture); } else { $ground = imagecreatefrompng($ground_picture); // Turn off alpha blending and set alpha flag imagealphablending($ground, false); imagesavealpha($ground, true); } $temp = explode(".", $bird_picture); $extension = end($temp); if ($extension == "jpeg" || $extension == "jpg") { $bird = imagecreatefromjpeg($bird_picture); } else { $bird = imagecreatefrompng($bird_picture); // Turn off alpha blending and set alpha flag imagealphablending($bird, false); imagesavealpha($bird, true); } $temp = explode(".", $tube1_picture); $extension = end($temp); if ($extension == "jpeg" || $extension == "jpg") { $tube1 = imagecreatefromjpeg($tube1_picture); } else { $tube1 = imagecreatefrompng($tube1_picture); // Turn off alpha blending and set alpha flag imagealphablending($tube1, false); imagesavealpha($tube1, true); } $temp = explode(".", $tube2_picture); $extension = end($temp); if ($extension == "jpeg" || $extension == "jpg") { $tube2 = imagecreatefromjpeg($tube2_picture); } else { $tube2 = imagecreatefrompng($tube2_picture); // Turn off alpha blending and set alpha flag imagealphablending($tube2, false); imagesavealpha($tube2, true); } imagecopymerge($background, $tube1, 200, -200, 0, 0, 52, 320, 100); imagecopymerge($background, $tube2, 200, 200, 0, 0, 52, 320, 100); imagecopymerge($background, $ground, 0, 320, 0, 0, 336, 112, 100); imagecopymerge($background, $bird, 70, 190, 0, 0, 36, 26, 100); header('Content-Type: image/png'); imagepng($background); # Destroy imagedestroy($background); imagedestroy($ground); imagedestroy($bird); imagedestroy($tube1); imagedestroy($tube2); ?>Attached Files preview.php 3.31KB 1 downloads Hi, I need help in my code. I have written a CAPTCHA code, but it is not appearing when I test run in my website. My code is below, could anyone highlight to me my error? Any problems to those that were highlighted in red? Thanks <?php session_start(); // Set some important CAPTCHA constants define('CAPTCHA_NUMCHARS', 6); // number of characters in pass-phrase define('CAPTCHA_WIDTH', 100); // width of image define('CAPTCHA_HEIGHT', 25); // height of image // Generate the random pass-phrase $pass_phrase = ""; for ($i = 0; $i < CAPTCHA_NUMCHARS; $i++) { $pass_phrase .= chr(rand(97, 122)); //chr(), convert a number to its ASCII character equivalent } // Store the encrypted pass-phrase in a session variable $_SESSION['pass_phrase'] = SHA($pass_phrase); // Create the image $img = imagecreatetruecolor(CAPTCHA_WIDTH, CAPTCHA_HEIGHT); // Set a white background with black text and gray graphics $bg_color = imagecolorallocate($img, 255, 255, 255); // white $text_color = imagecolorallocate($img, 0, 0, 0); // black $graphic_color = imagecolorallocate($img, 64, 64, 64); // dark gray // Fill the background imagefilledrectangle($img, 0, 0, CAPTCHA_WIDTH, CAPTCHA_HEIGHT, $bg_color); // Draw some random lines for ($i = 0; $i < 5; $i++) { imageline($img, 0, rand() % CAPTCHA_HEIGHT, CAPTCHA_WIDTH, rand() % CAPTCHA_HEIGHT, $graphic_color); } // Sprinkle in some random dots for ($i = 0; $i < 50; $i++) { imagesetpixel($img, rand() % CAPTCHA_WIDTH, rand() % CAPTCHA_HEIGHT, $graphic_color); } // Draw the pass-phrase string imagettftext($img, 18, 0, 5, CAPTCHA_HEIGHT - 5, $text_color, 'Courier New Bold.ttf', $pass_phrase); // Output the image as a PNG using a header header("Content-type: image/png"); imagepng($img); // Clean up imagedestroy($img); ?> Hey all, I'm trying to upload multiple image(which works great) but the problem I'm having is when an image is uploaded it over-rights a previous image if they are the same name and the old one is gone. Solution: create a unique name for each image before it's uploaded, change the name and then upload it. I can't seem to figure the correct syntax. My thought was to take the image name and add a random number to the front of it. Am i going about this the right way? thanks for the replies in advance. code below Code: [Select] if (isset($_POST['Submit'])) { $number_of_file_fields = 0; $number_of_uploaded_files = 0; $number_of_moved_files = 0; //creating my random number $random_digit=rand(0000,9999); $uploaded_files = array(); $upload_directory = dirname(__file__) . '/car-images/'; //set upload directory for ($i = 0; $i < count($_FILES['images']['name']); $i++) { $number_of_file_fields++; if ($_FILES['images']['name'][$i] != '') { //check if file field empty or not $number_of_uploaded_files++; $uploaded_files[] = $_FILES['images']['name'][$i]; if (move_uploaded_file($_FILES['images']['tmp_name'][$i], $upload_directory . $_FILES['images']['name'][$i])) { $number_of_moved_files++; } } } $image0 = $uploaded_files[0]; $image1 = $uploaded_files[1]; $image2 = $uploaded_files[2]; $image3 = $uploaded_files[3]; $image4 = $uploaded_files[4]; Hello, Five images will be displayed inside a division. There will be a previous and next button/link. If someone click the next button the next image will be added in that div and the first image will be gone from that div. The previous button/link will do the same thing. Is it possible with php? I am confused if it's a javascript or ajax question. Thanks. Been just trying to test out some basic code that utilizes gd. In Chrome i receive a blank page. In firefox I get "The image "image.php" cannot be displayed because it contains errors". There is no whitespace before or after the php tags, which seems to cause this error sometimes. $image = imagecreate(200,20); $background = imagecolorallocate($image, 0, 0, 0); $foreground = imagecolorallocate($image,255,255,255); imagestring($image, 5, 5, 1, "Test", $foreground); header("Content-type: image/jpeg"); $imagejpeg($image); I am just following a tutorial, and at this point in the tutorial i should get at least some garbled text, if not an image. I looked at other common causes. gd2 is un-commented in php.ini. phpinfo shows: GD Support enabled GD Version bundled (2.0.34 compatible) FreeType Support enabled FreeType Linkage with freetype FreeType Version 2.4.3 GIF Read Support enabled GIF Create Support enabled JPEG Support enabled libJPEG Version 6b PNG Support enabled libPNG Version 1.2.46 WBMP Support enabled XBM Support enabled gd.jpeg_ignore_warning 0 0 I have not found any other solutions to try, or maybe I have made an error is checking these solutions. Any advice with be great! Thank you for your time. |