PHP - Getimagesize() On Php File Outputting A Image
Hi,
It's been a while since I've been on here... I've got a script that takes an image url and resizes it, then outputs it to the screen (using image headers etc). I've then got a htaccess file that changes my nice url, such as: 'images/thumb/50-70/logo.jpg' to: 'incudes/resize.php?width=50&height=70&img=logo.jpg' Which is the resize script, so I can use a nice url in img tags. The width and height are just the maximum allowed, so sometime the image will be smaller. Now, this all works correctly, but I am now trying to find out the width and height of the thumbnailed image, from outside of the resize.php script. I thought that I could use getimagesize, but this doesn't seem to work... I first tried it using the 'nice' url: '/images/thumb/50-70/logo.jpg' Thinking that .htaccess would re-direct, but no. I then tried a direct link to the resize file: '/incudes/resize.php?width=50&height=70&img=logo.jpg' But that returns a file not found error... Although I can access the file directly. Trying the direct url without the get variables, however, successfully finds the file, but it doesn't seem to be able to detect the image dimensions. I just get a blank result.. Is PHP able to recognise htaccess re-directs? Is PHP able to parse a php file that outputs as an image? (I have all the correct headers etc set!) Thanks Similar TutorialsMy images generator comprises
an array of image names extracted form an images table from a database using a select statement
a random number generator,
and a string that builds the correct pathname for the selected file.
To select one of the images for display, i generate a random number between 1 and the length of the array.
Though the generator is working, I noticed one of the random numbers is throwing up this error:
Warning: getimagesize(images/): failed to open stream: No such file or directory in
An inspection of the array reveals 2 array elements (representing my number of images) but one array element is NULL ( the first entry in the banner table
image_generator.php
require_once('connection.inc.php'); $sql = 'SELECT `filename` FROM banner'; $result = $mysqli->query($sql, MYSQLI_STORE_RESULT) or die(mysqli_error()); $row = $result->fetch_array(MYSQLI_ASSOC);//an array of image names $count = $result->num_rows; for ($i = 1; $i <= $count; ++$i) { $row[$i] = $result->fetch_array(MYSQLI_ASSOC); } $i = rand(1, $count); //a random number generator, //The random number is used in the final line to build the correct pathname for the selected file. $selectedImage = "images/{$row[$i]['filename']}"; if (file_exists($selectedImage) && is_readable($selectedImage)) { $imageSize = getimagesize($selectedImage); }var_dump($row) array (size=1) 'filename' => string 'ginsomin2.jpg' (length=13) nullRANDON IMAGE DISPLAY require_once 'image_generator.php'; <div id="banner" class="wrapper clearfix"> <img src="<?php echo $selectedImage; ?>" alt="banner"> </div>Kindly advice how i may proceed from here? Thanks. Hi all, I'm iterating 4 images out in a loop. All 4 images exist (definitely), and using an earlier script, have been resized to a width of 200px, so they are not large. I'm finding that if I use the following code: Code: [Select] $image_info = getimagesize($filename); $type = $image_info['mime']; echo $type; .. some of the images come up with no mime type. Is this normal? As a (possible) result of / link to having no mime type assigned to it, I'm getting: [function.getimagesize]: failed to open stream: No such file or directory .. but I am positive the image exists. Viewing the image info in a browser gives "image/jpeg", so I'm a bit weirded out as to how the script queries the image for a mime type, and it returns nothing. Has anybody else seen this, can anyone help? All the best, WoolyG Hi, I am trying to make a simple thumbnail gallery where you upload an image, the image gets resized, a thumbnail is created in the "images/small/" directory, and the main images are in the "images/" directory. I need to somehow read from both directories, and do an image link with the thumbnail linking to the larger image. I think that means displaying from two directories, I don't know how to do that, please any help greatly appreciated. Thank you. here is my code so far Code: [Select] <?php error_reporting(0); $change=""; $abc=""; define ("MAX_SIZE","400"); function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } $errors=0; if($_SERVER["REQUEST_METHOD"] == "POST") { $image =$_FILES["file"]["name"]; $uploadedfile = $_FILES['file']['tmp_name']; if ($image) { $filename = stripslashes($_FILES['file']['name']); $extension = getExtension($filename); $extension = strtolower($extension); if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) { $change='<div class="msgdiv">Unknown Image extension </div> '; $errors=1; } else { $size=filesize($_FILES['file']['tmp_name']); if ($size > MAX_SIZE*1024) { $change='<div class="msgdiv">You have exceeded the size limit!</div> '; $errors=1; } if($extension=="jpg" || $extension=="jpeg" ) { $uploadedfile = $_FILES['file']['tmp_name']; $src = imagecreatefromjpeg($uploadedfile); } else if($extension=="png") { $uploadedfile = $_FILES['file']['tmp_name']; $src = imagecreatefrompng($uploadedfile); } else { $src = imagecreatefromgif($uploadedfile); } echo $scr; list($width,$height)=getimagesize($uploadedfile); //**Original**// //$newwidth=60; //$newheight=($height/$width)*$newwidth; //**Modified to use height instead of width**// //$newheight=350; //$newwidth=($width/$height)*$newheight; // **IF NOT resizing full image then just pass variables.**// $newheight=$height; $newwidth=$width; //***adjust tmp***// $tmp=imagecreatetruecolor($newwidth,$newheight); //Thumbs $newheight1=180; $newwidth1=($width/$height)*$newheight1; //**Original**// //$newwidth1=25; //$newheight1=($height/$width)*$newwidth1; $tmp1=imagecreatetruecolor($newwidth1,$newheight1); imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height); imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,$width,$height); $filename = "images/". $_FILES['file']['name']; $filename1 = "images/small/". $_FILES['file']['name']; imagejpeg($tmp,$filename,100); imagejpeg($tmp1,$filename1,100); imagedestroy($src); imagedestroy($tmp); imagedestroy($tmp1); }} } //If no errors registred, print the success message if(isset($_POST['Submit']) && !$errors) { // mysql_query("update {$prefix}users set img='$big',img_small='$small' where user_id='$user'"); $change=' <div class="msgdiv">Image Uploaded Successfully!</div>'; } ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml" lang="en"><head> <meta content="text/html; charset=UTF-8" http-equiv="Content-Type"> <meta content="en-us" http-equiv="Content-Language"> <title>picture demo</title> <link href=".css" media="screen, projection" rel="stylesheet" type="text/css"> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script> <script type="text/javascript" src="js/jquery_002.js"></script> <script type="text/javascript" src="js/displaymsg.js"></script> <script type="text/javascript" src="js/ajaxdelete.js"></script> <style type="text/css"> .help { font-size:11px; color:#006600; } body { color: #000000; background-color:#999999 ; background:#999999 url(<?php echo $user_row['img_src']; ?>) fixed repeat top left; font-family:"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif; } .msgdiv{ width:759px; padding-top:8px; padding-bottom:8px; background-color: #fff; font-weight:bold; font-size:18px;-moz-border-radius: 6px;-webkit-border-radius: 6px; } #container{width:763px;margin:0 auto;padding:3px 0;text-align:left;position:relative; -moz-border-radius: 6px;-webkit-border-radius: 6px; background-color:#FFFFFF } </style> </head><body> <div align="center" id="err"> <?php echo $change; ?> </div> <div id="space"></div> <div id="container" > <div id="con"> <table width="502" cellpadding="0" cellspacing="0" id="main"> <tbody> <tr> <td width="500" height="238" valign="top" id="main_right"> <div id="posts"> <img src="<?php echo $filename; ?>" /> <img src="<?php echo $filename1; ?>" /> <form method="post" action="" enctype="multipart/form-data" name="form1"> <table width="500" border="0" align="center" cellpadding="0" cellspacing="0"> <tr><Td style="height:25px"> </Td></tr> <tr> <td width="150"><div align="right" class="titles">Picture : </div></td> <td width="350" align="left"> <div align="left"> <input size="25" name="file" type="file" style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10pt" class="box"/> </div></td> </tr> <tr><Td></Td> <Td valign="top" height="35px" class="help">Image maximum size <b>400 </b>kb</span></Td> </tr> <tr><Td></Td><Td valign="top" height="35px"><input type="submit" id="mybut" value=" Upload " name="Submit"/></Td></tr> <tr> <td width="200"> </td> <td width="200"><table width="200" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="200" align="center"><div align="left"></div></td> <td width="100"> </td> </tr> </table></td> </tr> </table> </form> </div> </td> </tr> </tbody> </table> </div> </div> </body></html> Hello all, I'm trying to write a joomla page that will import LinkShare banners into the banner component. The problem I'm having is that LinkShare doesn't seem to always have the correct image size listed. If I use their dimensions, the images come out skewed and bad looking. So I'm trying to use getimagesize, to get the real dimensions, and it's still not working. Please take a look, and let me know if you have any suggestions. Code: [Select] <?php define('_JEXEC', 1); define('JPATH_BASE', dirname(__FILE__)); define('DS', DIRECTORY_SEPARATOR); require_once(JPATH_BASE . DS . 'includes' . DS . 'defines.php'); require_once(JPATH_BASE . DS . 'includes' . DS . 'framework.php'); $mainframe =& JFactory::getApplication('site'); $user =& JFactory::getUser(); If (($user->gid) === '25') { $token = "mylinksharetoken"; // required $status = "approved"; //application status name $mid = $_POST['mid']; $cat = $_POST['cat']; $size = $_POST['size']; //optional, use -1 as the default value. $campaignID = "-1"; //optional, use -1 as the default value $page = "1"; //optional, use 1 as a default value $startdate = ""; //formatted MMDDYYYY - optional, use an empty set as the default value (//). $enddate = ""; //formatted MMDDYYYY - optional, use an empty set as the default value (//). if (isset($_POST['submit'])) { $feed = simplexml_load_file("http://lld2.linksynergy.com/services/restLinks/getBannerLinks/{$token}/{$mid}/{$cat}/{$startdate}/{$enddate}/{$size}/{campaignID}/{$page}"); $children = $feed->children('http://endpoint.linkservice.linkshare.com/'); $entries = $children->return; foreach ($entries as $entry) { $sourcecode=GetImageFromUrl($details->imgURL); $name=md5(mt_rand()); $path = '/home/mysite/tmp/imgtmp/'; $savefile = fopen($path.$name, 'w'); fwrite($savefile, $sourcecode); list($realwidth, $realheight) = getimagesize($path.$name); $details = $entry->children('http://endpoint.linkservice.linkshare.com/'); $image = "<a href=\"{$details->clickURL}\" target=\"_NEW\">"; $image .= "<img src=\"{$details->imgURL}\" border=\"'0\" height=\"{$realheight}\" width=\"{$realwidth}\" title=\"{$details->name}\" alt=\"{$details->name}\" />"; $image .= "</a><img border=\"0\" height=\"1\" width=\"1\" src=\"{$details->showURL}\" />"; echo $image . "<br>\n"; fclose($savefile); @unlink($path.$name); } } ?> <form name="form1" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post"> Categories<select name="cat"> <option value="-1">All Categories</option> <option value="17">Business & Career</option> <option value="150">B-to-B</option> <option value="151">Employment</option> <option value="152">Real Estate</option> <option value="18">Department Store</option> <option value="153">Clothing</option> <option value="154">Gifts</option> <option value="155">Home</option> <option value="247">Jewelry</option> <option value="19">Family</option> <option value="156">Baby</option> <option value="157">Education</option> <option value="158">Entertainment</option> <option value="159">Pets</option> <option value="21">Telecommunications</option> <option value="211">Equipment</option> <option value="212">Long Distance</option> <option value="213">Wireless</option> <option value="1">Hobbies & Collectibles</option> <option value="101">Art</option> <option value="102">Auctions</option> <option value="103">Collectibles</option> <option value="2">Auto</option> <option value="104">Accessories</option> <option value="105">Cars</option> <option value="106">Rentals</option> <option value="3">Clothing & Accessories</option> <option value="207">Children</option> <option value="107">Accessories</option> <option value="108">Men</option> <option value="109">Women</option> <option value="246">Jewelry</option> <option value="4">Computer & Electronics</option> <option value="110">Hardware</option> <option value="111">Consumer</option> <option value="112">Software</option> <option value="5">Entertainment</option> <option value="113">Books/Magazines</option> <option value="114">Music</option> <option value="115">Videos</option> <option value="6">Financial Services</option> <option value="116">Banking/Trading</option> <option value="117">Credit Cards</option> <option value="118">Loans</option> <option value="7">Food & Drink</option> <option value="218">Candy</option> <option value="119">Cigars</option> <option value="120">Gourmet</option> <option value="121">Wine</option> <option value="8">Games & Toys</option> <option value="122">Children</option> <option value="123">Educational</option> <option value="124">Electronic</option> <option value="9">Gift & Flowers</option> <option value="125">Gifts</option> <option value="126">Flowers</option> <option value="127">Greeting Cards</option> <option value="10">Health & Beauty</option> <option value="229">Prescription</option> <option value="128">Bath/Body</option> <option value="129">Cosmetics</option> <option value="130">Vitamins</option> <option value="11248">Medical Supplies & Services</option> <option value="11">Home & Living</option> <option value="232">Improvement</option> <option value="131">Bed/Bath</option> <option value="132">Garden</option> <option value="133">Kitchen</option> <option value="12">Mature/Adult</option> <option value="134">Apparel</option> <option value="135">Books</option> <option value="136">Entertainment</option> <option value="13">Office</option> <option value="137">Equipment</option> <option value="138">Home Office</option> <option value="139">Supplies</option> <option value="14">Sports & Fitness</option> <option value="140">Clothing</option> <option value="141">Collectibles</option> <option value="142">Equipment</option> <option value="15">Travel</option> <option value="245">Vacations</option> <option value="143">Airline</option> <option value="144">Car</option> <option value="145">Hotel</option> <option value="16">Internet & Online</option> <option value="149">Programs</option> <option value="146">Services</option> <option value="147">Development</option> <option value="148">Hosting</option> <option value="16249">Online Dating</option> <option value="20">Miscellaneous</option> <option value="210">Other, Other Products/Services</option> </select> <?php $merchantlist = simplexml_load_file("http://lld2.linksynergy.com/services/restLinks/getMerchByAppStatus/{$token}/{$status}"); $children2 = $merchantlist->children('http://endpoint.linkservice.linkshare.com/'); $entries2 = $children2->return; echo "Manufacturers: <select name=\"mid\">\n"; echo "<option selected value=\"-1\">All Manufacturers</option>\n"; foreach ($entries2 as $entry2) { $details2 = $entry2->children('http://endpoint.linkservice.linkshare.com/'); echo "<option value=\"{$details2->mid}\">{$details2->name}</option>\n"; } echo "</select>"; ?>Size: <select name="size"> <option selected value="-1">Any Size</option> <option value="1">468x60 - Full Banner <option value="2">392x72 - Mid Banner</option> <option value="9">160x600 - Wd Skyscrp</option> <option value="10">120x600 - Skyscraper</option> <option value="11">180x150 - Rectangle</option> <option value="12">336x280 - Large Rect</option> <option value="3">234x60 - Half Banner</option> <option value="13">300x250 - Med Rect</option> <option value="14">250x250 - Sq Pop-up</option> <option value="15">240x400 - Vert Rect</option> <option value="4">125x125 - Sq Button</option> <option value="5">120x90 - Button 1</option> <option value="6">120x60 - Button 2</option> <option value="7">88x31 - Micro Bar</option> <option value="8">120x240 - Vert Banner</option> <option value="0">0x0 - Other</option> <option value="16">728x90 - Leader-board</option> <option value="17">720x300 - Pop-Under</option> <option value="18">550x480 - Pop-Up Large</option> <option value="19">300x600 - Half Page Ad</option> <option value="20">305x64 - X-Large</option> <option value="21">215x64 - Large</option> <option value="22">167x30 - Medium</option> <option value="23">112x20 - Small</option> </select> <input name="submit" type="submit" value="submit" /> </form> <?php } else { echo "not logged in"; die(); } function GetImageFromUrl($link) { $ch = curl_init(); curl_setopt($ch, CURLOPT_POST, 0); curl_setopt($ch,CURLOPT_URL,$link); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_BINARYTRANSFER,1); curl_setopt($ch, CURLOPT_HEADER, 0); $result=curl_exec($ch); curl_close($ch); return $result; } ?> Hello happy codes, I have an image as such; http://storage.canoe.ca/v1/dynamic_resize/?src=http://www.torontosun.com/specialsections/2011/03/10/248x186_mb.jpg&size=40x30 getimagesize doesn't work with this image. Any ideas or links? I have looked through this site and can't find anyone having this problem. Am I missing something? Thank you, V. Can I get some help or a point in the right direction.
I am trying to create a form that allows me to add, edit and delete records from a database.
I can add, edit and delete if I dont include the image upload code.
If I include the upload code I cant edit records without having to upload the the same image to make the record save to the database.
So I can tell I have got the code processing in the wrong way, thing is I cant seem to see or grasp the flow of this, to make the corrections I need it work.
Any help would be great!
Here is the form add.php code
<?php require_once ("dbconnection.php"); $id=""; $venue_name=""; $address=""; $city=""; $post_code=""; $country_code=""; $url=""; $email=""; $description=""; $img_url=""; $tags=""; if(isset($_GET['id'])){ $id = $_GET['id']; $sqlLoader="Select from venue where id=?"; $resLoader=$db->prepare($sqlLoader); $resLoader->execute(array($id)); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Add Venue Page</title> <link href='http://fonts.googleapis.com/css?family=Droid+Sans' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <?php $sqladd="Select * from venue where id=?"; $resadd=$db->prepare($sqladd); $resadd->execute(array($id)); while($rowadd = $resadd->fetch(PDO::FETCH_ASSOC)){ $v_id=$rowadd['id']; $venue_name=$rowadd['venue_name']; $address=$rowadd['address']; $city=$rowadd['city']; $post_code=$rowadd['post_code']; $country_code=$rowadd['country_code']; $url=$rowadd['url']; $email=$rowadd['email']; $description=$rowadd['description']; $img_url=$rowadd['img_url']; $tags=$rowadd['tags']; } ?> <h1 class="edit-venue-title">Add Venue:</h1> <form role="form" enctype="multipart/form-data" method="post" name="formVenue" action="save.php"> <input type="hidden" name="id" value="<?php echo $id; ?>"/> <div class="form-group"> <input class="form-control" type="hidden" name="id" value="<?php echo $id; ?>"/> <p><strong>ID:</strong> <?php echo $id; ?></p> <strong>Venue Name: *</strong> <input class="form-control" type="text" name="venue_name" value="<?php echo $venue_name; ?>"/><br/> <br/> <strong>Address: *</strong> <input class="form-control" type="text" name="address" value="<?php echo $address; ?>"/><br/> <br/> <strong>City: *</strong> <input class="form-control" type="text" name="city" value="<?php echo $city; ?>"/><br/> <br/> <strong>Post Code: *</strong> <input class="form-control" type="text" name="post_code" value="<?php echo $post_code; ?>"/><br/> <br/> <strong>Country Code: *</strong> <input class="form-control" type="text" name="country_code" value="<?php echo $country_code; ?>"/><br/> <br/> <strong>URL: *</strong> <input class="form-control" type="text" name="url" value="<?php echo $url; ?>"/><br/> <br/> <strong>Email: *</strong> <input class="form-control" type="email" name="email" value="<?php echo $email; ?>"/><br/> <br/> <strong>Description: *</strong> <textarea class="form-control" type="text" name="description" rows ="7" value=""><?php echo $description; ?></textarea><br/> <br/> <strong>Image Upload: *</strong> <input class="form-control" type="file" name="image" value="<?php echo $img_url; ?>"/> <small>File sizes 300kb's and below 500px height and width.<br/><strong>Image is required or data will not save.</strong></small> <br/><br/> <strong>Tags: *</strong> <input class="form-control" type="text" name="tags" value="<?php echo $tags; ?>"/><small>comma seperated vales only, e.g. soul,hip-hop,reggae</small><br/> <br/> <p>* Required</p> <br/> <input class="btn btn-primary" type="submit" name="submit" value="Save"> </div> </form> </div> </body> </html>Here is the save.php code <?php error_reporting(E_ALL); ini_set("display_errors", 1); include ("dbconnection.php"); $venue_name=$_POST['venue_name']; $address=$_POST['address']; $city=$_POST['city']; $post_code=$_POST['post_code']; $country_code=$_POST['country_code']; $url=$_POST['url']; $email=$_POST['email']; $description=$_POST['description']; $tags=$_POST['tags']; $id=$_POST['id']; if(is_uploaded_file($_FILES['image']['tmp_name'])){ $folder = "images/hs-venues/"; $file = basename( $_FILES['image']['name']); $full_path = $folder.$file; if(move_uploaded_file($_FILES['image']['tmp_name'], $full_path)) { //echo "succesful upload, we have an image!"; var_dump($_POST); if($id==null){ $sql="INSERT INTO venue(venue_name,address,city,post_code,country_code,url,email,description,img_url,tags)values(:venue_name,:address,:city,:post_code,:country_code,:url,:email,:description,:img_url,:tags)"; $qry=$db->prepare($sql); $qry->execute(array(':venue_name'=>$venue_name,':address'=>$address,':city'=>$city,':post_code'=>$post_code,':country_code'=>$country_code,':url'=>$url,':email'=>$email,':description'=>$description,':img_url'=>$full_path,':tags'=>$tags)); }else{ $sql="UPDATE venue SET venue_name=?, address=?, city=?, post_code=?, country_code=?, url=?, email=?, description=?, img_url=?, tags=? where id=?"; $qry=$db->prepare($sql); $qry->execute(array($venue_name, $address, $city, $post_code, $country_code, $url, $email, $description, $full_path, $tags, $id)); } if($success){ var_dump($_POST); echo "<script language='javascript' type='text/javascript'>alert('Successfully Saved!')</script>"; echo "<script language='javascript' type='text/javascript'>window.open('index.php','_self')</script>"; } else{ var_dump($_POST); echo "<script language='javascript' type='text/javascript'>alert('Successfully Saved!')</script>"; echo "<script language='javascript' type='text/javascript'>window.open('index.php','_self')</script>"; } } //if uploaded else{ var_dump($_POST); echo "<script language='javascript' type='text/javascript'>alert('Upload Recieved but Processed Failed!')</script>"; echo "<script language='javascript' type='text/javascript'>window.open('index.php','_self')</script>"; } } //move uploaded else{ var_dump($_POST); echo "<script language='javascript' type='text/javascript'>alert('Successfully Updated.')</script>"; echo "<script language='javascript' type='text/javascript'>window.open('index.php','_self')</script>"; } ?>Thanks in advance! Edited by hankmoody, 12 August 2014 - 05:15 PM. Hello, I'm trying to echo an additional variable using this: $numincorrect = '<div id="incorrectnum">Sorry, that number was not correct.</div>'; I want to incorperate: $code from require('send.php'); I've tried $numincorrect = '<div id="incorrectnum">Sorry, that number was not "$code".</div>'; However, it literally displays $code on output. Many thanks I have mysql table with Type, Month, Date, and Quantity. I am doing query, and writing to xml which will pass to chart. My error is coming because for each <row> I need to have same number of child tags. For instance, if there are six months represented in first row (<header>), I need to have six <number> tags in all the following rows, even when there may not be any Quantity for that particular month in mysql table. Right now, if a particular Type in my table doesn't show quantity for some months, than I end up with fewer <number> tags. My php is here, and xml structure below: Code: [Select] //start the XML output print "<chart>"; print "<chart_data>"; //output the first row that contains the years print "<row>"; print "<null></null>"; $category = mysql_query ("SELECT prMonth FROM table1 GROUP BY prMonth ORDER BY prDate"); for ( $column=0; $column < mysql_num_rows($category); $column++ ) { print "<header>".mysql_result ( $category, $column, "prMonth")."</header>"; } print "</row>"; //output row 2 to 4. Each row contains a type name and its data (Qty, Prem, Comm ...) $series = mysql_query ("SELECT prType FROM table1 GROUP BY prType ORDER BY prType"); for ( $row=0; $row < mysql_num_rows($series); $row++ ) { print "<row>"; $type = mysql_result ( $series, $row, "prType"); print "<string>$type</string>"; $data = mysql_query ("SELECT SUM(prQty) FROM table1 WHERE prType='$type' GROUP BY prMonth ORDER BY prDate"); for ( $column=0; $column < mysql_num_rows($data); $column++ ) { // Need to do something here to // get number tags to show zero // when there's no data for that // month print "<number>".mysql_result($data,$column)."</number>"; } print "</row>"; } //finish the XML output print "</chart_data>"; print "</chart>"; XML structu Code: [Select] <chart> <chart_data> <row> ----this row will be the head row---- </null> <header>Month name</header> <header>Month name</header> ... </row> <row> ----this row will start body rows---- <string>Type name</string> <number>total quantity for month, for this type</number> <number>total quantity for month, for this type</number> ... </row> ... </chart_data> </chart> Hi there i have a basic query that is simply not outputting, i just dont get it. Im pretty sure the query is sound. If you can spot anything wrong here please let me know. Code: [Select] $colname_RecordSet1 = "-1"; if (isset($_SERVER['MM_Username'])) { $colname_RecordSet1 = (get_magic_quotes_gpc()) ? $_SERVER['MM_Username'] : addslashes($_SERVER['MM_Username']); } mysql_select_db($database_swb, $swb); $query_resultp = sprintf("SELECT PlayerName, PlanetName, Class1, Class2, Class3, Class4 FROM planet WHERE PlayerName = %s", GetSQLValueString($colname_RecordSet1, "text")); $resultp = mysql_query($query_resultp, $swb) or die(mysql_error()); $row_resultp = mysql_fetch_assoc($resultp); $totalRows_resultp = mysql_num_rows($resultp); <?php do { echo 'Class: '; echo $row_resultp['PlanetName']; echo $row_resultp['Class1']; echo $row_resultp['Class2']; echo $row_resultp['Class3']; echo $row_resultp['Class4']; ?> <?php } while ($row_resultp = mysql_fetch_assoc($resultp)); mysql_free_result($resultp); ?> Thanks I'm doing the following query where "ctext" comes from the clues table and "answerid" and "atext" come from the answers table... Code: [Select] $sql = "SELECT * from clues, answers WHERE clues.quizid = '{$_GET['quizid']}' AND answers.quizid = '{$_GET['quizid']}'"; $result = mysql_query($sql, $connection); if (!$result) { die("Database query failed: " . mysql_error()); } else { while ($info=mysql_fetch_array($result)) { echo "<tr><td>" . $info['answerid'] . "</td>"; echo "<td>".$info['ctext']."</td>"; echo "<td>".$info['atext']."</td>"; } echo "</tr>"; } } But when this displays in the browser, it's outputting each result set twice and kinda mixed up. For example, it looks like this... 1 monkey funny 1 cat funny 2 monkey boring 2 cat boring But I want (i.e. was expecting) it to display as... 1 monkey funny 2 cat boring Can anyone tell me why it's showing TWO rows for each and seemingly mixing up the returned results? Ultimate question is this. Do I have to break apart the mysql queries in order to get PHP to display the results how I want? I gotta think there is a way to do just one query and do what I want, but I obviously can't figure it out On my website, I have Sticky Forms that use the following style code... <input id="firstName" name="firstName" type="text" maxlength="30" value="<?php if(isset($firstName)){echo htmlspecialchars($firstName, ENT_QUOTES);} ?>" /><!-- Sticky Field --> Do I need to use htmlspecialchars($firstName, ENT_QUOTES); anytime I output data to the screen?? For example, in this code do I need to wrap $username?? echo ' <div class="userInfo"> <a href="#" class="username"> <strong>' . $username . '</strong> </a>'; Debbie The code below is in a PHP file, but is really HTML with nested PHP. <img src="<?php echo WEB_ROOT; ?>images/BeachSunset.jpg" width="200" alt="Pictu Beach Sunset." title="Pictu Beach Sunset." /> I want to put it in a MySQL record and output it using PHP. So how do I re-write this code so that it can be displayed with the same end effect using a PHP Echo statement?? (I seem to be having trouble figuring things out with MySQL in the way?! Thanks, Debbie What is the proper way to output the contents of a class? (We will assume that Getters and Setters are evil...) Let's say I have the following class... class FormHandler2 { // Define Variables. private $myFormArray; // Constructor. public function __construct($param){ $this->myFormArray = $param; } } ...and I want to be able to output its contents either via a variable dump OR by printing something to the screen. How would I do that? TomTees Hi
I have a self calling script which does the following:
Stage 1: First run, it detects that $_POST is empty, and so displays a chunk of html which prompts for a password.
Stage 2: When resubmitted, it detects $_POST and displays another chunk of html which prompts the user for some values
Stage 3; When resubmitted the second time, $_POST is detected, along with the user values and some php is executed and a menu displayed.
So, question is this, what is the best method to output the html at stage 1 and stage 2?
I have tried using echo statements and wrapping each chunk in a function = messy.
I have tried using HEREDOCS (<<<VARNAME), better but ties my HTML to my script which is a pain
I am thinking to use file_get_contents("../html/chunk1.htm") this seems quite elegant and allows me to get someone else on our team to design the HTML keeping it out of my script
Thoughts and suggestions?
Thanks as ever
p.s. who pays for this site, are donation accepted?
This topic has been moved to Third Party PHP Scripts. http://www.phpfreaks.com/forums/index.php?topic=320494.0 Hello guys. I am facing a little problem on my website when I am trying to output the data from the database in the form of a table. If you go to http://sigmalogistix.com/track-trace/ and enter any on of the following B/L No's: 123456789 987651234 543216789 You can see that the table is being created but the data is not being shown to the user. If I switch back to the old code in which there was no table, then the data is being shown to the user upon entering the B/L No. Please help me guys. Attached below are the codes which I have inside the function.inc.php file and the index.php file. function.inc.php Code: [Select] <?php include 'db.inc.php'; function search_results($keywords) { $returned_results = array(); $where = ""; $keywords = preg_split('/[\s]+/', $keywords); $total_keywords = count($keywords); foreach($keywords as $key=>$keyword){ $where .= "`keywords` LIKE '%$keyword%'"; if ($key != ($total_keywords - 1)) { $where .= " AND "; } } $results = "SELECT `Bill_No`, `Origin_City`, `Origin_Country`, `Destination_City`, `Destination_Country`, `Status`, `Current_Location` FROM `billoflading` WHERE $where"; $results_num = ($results = mysql_query($results)) ? mysql_num_rows($results) : 0; if ($results_num === 0) { return false; } else { while ($results_row = mysql_fetch_assoc($results)) { $returned_results[] = array ( 'Bill_No' => $results_row['Bill_No'], 'Origin_City' => $results_row['Origin_City'], 'Origin_Country' => $results_row['Origin_Country'], 'Destination_City' => $results_row['Destination_City'], 'Destination_Country' => $results_row['Destination_Country'], 'Status' => $results_row['Status'], 'Current_Location' => $results_row['Current_Location'] ); } return $returned_results; } } ?> index.php Code: [Select] <?php include 'func.inc.php'; ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>search</title> </head> <body> <form action="" method="POST"> <p> <input type="text" name="keywords" size="17" maxlength="9" value="Enter B/L No." onfocus="if(this.value == 'Enter B/L No.'){this.value = '';}" /> <input type="submit" class="formbutton" value="Track" /> </p> </form> <?php if (isset($_POST['keywords'])) { $suffix = ""; $keywords = mysql_real_escape_string(htmlentities(trim($_POST['keywords']))); $errors = array(); if (empty($keywords)) { $errors[] = ''; } else if (strlen($keywords)<9) { $errors[] = '<br><strong>Your Bill of Lading Number must contain 9-digits.</strong>'; } else if (search_results($keywords) === false) { $errors[] = '<br><strong>Please enter a valid Bill of Lading Number.</strong>'; } if (empty($errors)) { $results = search_results($keywords); $results_num = count($results); $suffix = ($results_num !=1) ? 's' : ''; foreach($results as $result) { echo '<br><table> <thead> <tr> <th><strong>B/L No.</strong></th> <th><strong>Origin City</strong></th> <th><strong>Origin Country</strong></th> <th><strong>Destination City</strong></th> <th><strong>Destination Country</strong></th> <th><strong>Status</strong></th> <th><strong>Current Location</strong></th> </tr> </thead> <tbody> <?php while ($row = mysql_fetch_assoc($results) { ?> <tr> <td><?php echo $row["Bill_No"]; ?></td> <td><?php echo $row["Origin_City"]; ?></td> <td><?php echo $row["Origin_Country"]; ?></td> <td><?php echo $row["Destination_City"]; ?></td> <td><?php echo $row["Destination_Country"]; ?></td> <td><?php echo $row["Status"]; ?></td> <td><?php echo $row["Current_Location"]; ?></td> </tr> <?php } ?> </tbody> </table>'; } } else { foreach($errors as $error) { echo $error, '</br>'; } } } ?> </body> </html> I have converted xml into an array with no problems, however I'm having difficulty outputting the various attributes. Here is a sample: Code: [Select] [0] => Array ( [@attributes] => Array ( [YourId] => 1082-1 [Name] => Woodwards Metals [Description] => ) ) The bit that is confusing me is the @attributes part. How would I output the 'Name' element for example? Hi guys, I am very simply inserting text into a table with php and mysql, and outputting it, it all works fine but when I use paragraphs when inserting it, and then try to ouput it, all the paragraphs are gone and it looks like one big block of text, I suppose the way to go around this is to use <br> instead of just enters as it probably doesnt read this, but is it possible to make this text area do read and insert <br>'s where people use enter to make paragraphs? Much help appreciated, I realize this must be a very beginner question but I am not really sure how to word this so I wasn't sure on specific search on this. Hi All, I'm working on an X-Cart site. Looking through the pages, any page with an apostrophe in the content is being loaded as an � instead. The sites' char set is UTF-8. Changing it to ISO then creates an issue in itself with bulleted lists. Just wondering if anyone has had the problem in the past and if they have solved it? Any help appreciated. Cheers Hello guys i am doing a search function whereby users can check whether a setting is Pass or Fail. After user press the search button, it will return the file which contain the settings the user wants. However i have encountered a problem, currently i am using if statement and && operator to search for file so if the file is missing a string whereby the preg_match function couldn't find it, it will not output the file if i check another setting. Hence i am interested on what other options can i use. Also, Is it possible to use while loop? I tried for awhile and my browser just keeps loading and loading. Thanks for the help! Example: I want to check File 1 for Maximum Password Age settings but it does not contain Service Pack Requirement string... if ((preg_match("/\bService Pack Requirement:(.*)./", $allFiles)) && (preg_match("/\bMaximum Password Age Requirement:(.*)./", $allFiles)) && (preg_match("/\bMinimum Password Length:(.*)./", $allFiles)) && (preg_match("/\bAudit Account Logon Events:(.*)./", $allFiles)) { echo "<a href=\"$file\" target=\"_blank\"> $file </a><br />"; } |