Page 1 of 1
Undefined Offset issue...
Posted: Mon May 10, 2010 10:54 am
by MiniMonty
Hi all,
having a small issue with undefined offset.
Scenario: A user uploads up to 5 images and makes comments on each image.
The comments (and image file location) are stored in a .txt file. This all works fine.
The problem occurs when displaying the images and text using this:
Code: Select all
$lines = file("members/" . $id . "/images/course_pics/" . $course_num . ".txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach($lines as $line) {
$fields = explode("&", $line);
list($path, $comment) = $fields;
}
And in the html i just use
Code: Select all
<td height="60" bordercolor="#333333"><span class="orangeText">Comments on Image 1 </span><br>
<?php print $fields[1]; ?></td>
</tr>
Trouble is, if the user has only made three comments then 4 and 5 become undefined offsets and all my efforts to "set" them as "No comment made"
have come to no good. Any ideas ?
Best wishes
Monty
Re: Undefined Offset issue...
Posted: Mon May 10, 2010 11:05 am
by hypedupdawg
Don't wait until after the comment storage to address this issue - do it when you are writing the files. What code are you using to add new data to your .txt files?
Re: Undefined Offset issue...
Posted: Mon May 10, 2010 11:07 am
by AbraCadaver
You'll have to show more code and/or a sample line from your text file, but loop through the comments something like this:
Code: Select all
foreach($lines as $line) {
$fields = explode("&", $line);
$path = array_shift($fields);
foreach($fields as $comment) {
echo $comment;
}
}
Re: Undefined Offset issue...
Posted: Mon May 10, 2010 11:33 am
by MiniMonty
hypedupdawg wrote:Don't wait until after the comment storage to address this issue - do it when you are writing the files. What code are you using to add new data to your .txt files?
Hi all,
here's the whole script with the display html and everything.
I write the text file at line 170
Code: Select all
<?php
session_start();
include_once "scripts/connect_to_mysql.php";
$firstname = "";
$email = "";
$tutor_fk = "";
$courseName = $_REQUEST["courseName"];
$thumbsToPrint ="";
$error_msg ="";
$course_num="";
$tutor_num ="";
$tutorFirstname ="";
$tutorSecondname="";
$tutor_email="";
if(isset($_GET['id']) || isset($_POST['id']));
else if (isset($_SESSION['id'])) {
$id = $_SESSION['id'];
} else {
// the page to send them to if they are NOT logged in
include_once "index.php";
exit();
}
///// GET MEMBER id, FIRSTNAME AND EMAIL
$id = mysql_real_escape_string($id);
$id = eregi_replace("`", "", $id);
$sql = mysql_query("SELECT * FROM myMembers WHERE id='$id'");
while($row = mysql_fetch_array($sql)){
$firstname = $row["firstname"];
$email = $row["email"];
}
// IDENTIFY THE COURSE NAME AND NUMBER !!!
if ($courseName == "Day One Digital"){
$course_num =1;
} else if ($courseName == "Tune In To Programs") {
$course_num =2;
} else if ($courseName == "Shutter Speeds For Shutter Bugs") {
$course_num =3;
} else if ($courseName == "Compose Yourself") {
$course_num =4;
} else if ($courseName == "The Modern Portrait") {
$course_num =5;
} else if ($courseName == "Outward Bound") {
$course_num =6;
}
//// IDENTIFY THE TUTOR
$sql = mysql_query("SELECT * FROM courses WHERE course_id= '$course_num'");
while($row = mysql_fetch_array($sql)){
$tutor_num = $row["tutor_fk"];
}
$sql = mysql_query("SELECT * FROM myMembers WHERE id= '$tutor_num'");
while($row = mysql_fetch_array($sql)){
$tutorFirstname = $row["firstname"];
$tutorSecondname = $row["lastname"];
$tutor_email = $row["email"];
}
$tutor_name = "$tutorFirstname" . " " . "$tutorSecondname";
// AND NOW THE UPLOAD PART !!!!
//Define an array of acceptable image extensions
$acceptableextensions = array('jpg','jpeg','png','gif');
//Define an array of acceptable MIME types
$acceptablemimetypes = array('image/jpg','image/jpeg','image/png','image/gif');
//Define maximum file size
$maxfilesize = 256000; // 256000 bytes equals 250kb
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$success = 0;
$fail = 0;
$uploaddir = "members/$id/images/course_pics/";
for ($i=0;$i<5;$i++)
{
if ((isset($_FILES['userfile']['name'][$i])) && ($_FILES['userfile']['error'][$i] == 0)){
$image = $_FILES['userfile']['name'][$i];
$filename = stripslashes($_FILES['userfile']['name'][$i]);
$extension = getExtension($filename);
$extension = strtolower($extension);
// NOW DO THE TEXT AREA AS WELL !!!
$comments = stripslashes($_POST['textarea'][$i]);
// This line will return "&comment1="blah blah blah".
//echo "&comment" . $i . "=" .$comments;
$student_comments=$comments;
//Filetype check
if (!in_array($extension,$acceptableextensions)){
exit("Upload failed.<BR>Unacceptable file type.<br. Use only jpg, jpeg, png or fig formats");
echo '<h1>Only try to upload .jpg, .jpeg, .png and .gif files!</h1>';
$errors=1;
//Filesize check
} else if ($_FILES['userfile']['size'][$i] > $maxfilesize ) {
$error_msg = 'Ooops - your image was too large,<br> 250kb Maximum. Please try again.';
unlink($_FILES['userfile']['tmp_name'][$i]);
} else {
// rename the picture incrementally
$extension = getExtension($filename);
$extension = strtolower($extension);
$groovy = sizeof(glob("members/$id/images/course_pics/*"));
$groovy = ++$groovy;
$image_name=$groovy.'.'.$extension;
$newname="".$image_name;
// NOW put the files in the dir
$place_file = move_uploaded_file( $_FILES['userfile']['tmp_name'][$i], "members/$id/images/course_pics/".$newname);
chmod ("members/$id/images/course_pics/$newname", 0644);
////////// MY RESIZE EFFORT !!
//// RESIZE !!!!!
$originalImage = "members/$id/images/course_pics/".$newname;
$maxHeight = 500;
$maxwidth = 780;
list($width, $height) = getimagesize($originalImage);
$xscale=$width/$maxwidth;
$yscale=$height/$maxHeight;
//// CALCULATE THE NEW SIZE FOR THE IMAGE
if ($yscale>$xscale){
$new_width = round($width * (1/$yscale));
$new_height = round($height * (1/$yscale));
}
else {
$new_width = round($width * (1/$xscale));
$new_height = round($height * (1/$xscale));
}
/// RESIZE THE IMAGE
$imageResized = imagecreatetruecolor($new_width, $new_height);
$imageTmp = imagecreatefromjpeg ($originalImage);
imagecopyresampled($imageResized, $imageTmp, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
//// OVERWRITE THE ORIGINAL IMAGE WITH THE RESIZED VERSION
imagejpeg($imageResized, $originalImage, 100) ;
//NOW WRITE THE .txt FILE
$myFile = "members/$id/images/course_pics/" . $course_num . ".txt";
$fh = fopen($myFile, 'a+') or die("can't open file");
$stringData = "members/$id/images/course_pics/".$newname ."&";
fwrite($fh, $stringData);
fclose($fh);
}
$student_comments = eregi_replace("'", "'", $student_comments);
$student_comments = eregi_replace("`", "'", $student_comments);
$sortamp = str_replace("&","and","$student_comments");
$student_comments = mysql_real_escape_string($sortamp);
$myFile = "members/$id/images/course_pics/" . $course_num . ".txt";
$fh = fopen($myFile, 'a+') or die("can't open file");
$stringData = "$sortamp" . "&";
fwrite($fh, $stringData);
fclose($fh);
}
$success_msg = '<span class="Big_Orange_Times">Your image has been uploaded. it may take a few moments to appear in your gallery, please be patient.<br>';
}
//////// SET THE DB TO "work submitted = 1"
$sql = mysql_query("UPDATE `students_to_courses` SET `work_submitted` = '1' WHERE `student_fk` = '$id' && course_fk = '$course_num' ");
$linkToSend = "http://www.shutterbugclub.com/critique.php?student_id=".$id."&course_num=".$course_num. "&courseName=" .$courseName;
/////////// NOW EMAIL THE TUTOR
$to = "$tutor_email";
$from = "admin@shutterbugclub.com";
$subject = "Critique Required";
//Begin HTML Email Message
$message = "Hi $tutorFirstname,
A student on your course $courseName has uploaded their coursework and now requires a critique.
Please view their work by following this link:
$linkToSend
admin@shutterbugclub.com";
//end of message
$headers = "From: $from\r\n";
$headers .= "Content-type: text\r\n";
mail($to, $subject, $message, $headers);
$lines = file("members/" . $id . "/images/course_pics/" . $course_num . ".txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach($lines as $line) {
$fields = explode("&", $line);
list($path, $comment) = $fields;
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Upload COURSE images</title>
<link href="styles/main.css" rel="stylesheet" type="text/css" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style type="text/css">
<!--
.style1 {color: #FF6600}
-->
</style>
</head>
<body>
<?php include_once "header_template.php"; ?>
<br>
<br>
<table width="59%" height="656" border="0" align="center">
<tr>
<td><table width="98%" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td><div align="justify">OK<span class="orangeText"> <?php print "$firstname"; ?></span><br>
All your images and text have been uploaded and entered into the database for <span class="Big_Orange_Times"><br>
<?php print $_REQUEST["courseName"]; ?></span><br>
Your course tutor, <span class="orangeText"><?php print "$tutor_name"; ?></span>, has been sent an email and will respond wih an honest and considered critisism. <br>
We really hope you enjoyed the course and don't hesitate to take another one ! </div>
</td>
</tr>
</table>
<div align="right"></div>
<div align="right"></div>
<p align="justify"> </p>
<div align="center"> </div>
<div align="center"> </div></td>
</tr>
<tr>
<td><div align="center"><img src="<?php print $fields[0]; ?>" /></div></td>
</tr>
<tr bgcolor="#CCCCCC">
<td height="60" bordercolor="#333333"><span class="orangeText">Comments on Image 1 </span><br>
<?php print $fields[1]; ?></td>
</tr>
<tr>
<td><div align="center"><img src="<?php print $fields[2]; ?>" /></div></td>
</tr>
<tr bgcolor="#CCCCCC">
<td height="60"><span class="orangeText">Comments on Image 2 </span><br>
<?php print $fields[3]; ?></td>
</tr>
<tr>
<td><div align="center"><img src="<?php print $fields[4]; ?>" /></div></td>
</tr>
<tr bgcolor="#CCCCCC">
<td height="60"><span class="orangeText">Comments on Image 3 </span><br>
<?php print $fields[5]; ?></td>
</tr>
<tr>
<td><div align="center"><img src="<?php print $fields[6]; ?>" /></div></td>
</tr>
<tr bgcolor="#CCCCCC">
<td height="60"><span class="orangeText">Comments on Image 4 </span><br>
<?php print $fields[7]; ?></td>
</tr>
<tr>
<td><div align="center"><img src="<?php print $fields[8]; ?>" /></div></td>
</tr>
<tr bgcolor="#CCCCCC">
<td height="60"><span class="orangeText">Comments on Image 5 </span><br>
<?php print $fields[9]; ?></td>
</tr>
</table>
<div align="center">
<div align="left"><br>
<br>
<?php include_once "footer_template.php"; ?>
</div>
</div>
</p>
</body>
</html>
Best wishes
Monty
Re: Undefined Offset issue...
Posted: Mon May 10, 2010 11:44 am
by wurdup
can you not simply add an if stantement to check the array has something in it before the <td>?
Re: Undefined Offset issue...
Posted: Mon May 10, 2010 8:07 pm
by MiniMonty
Hi all,
just gently bumping this because this is the last single thing to solve to complete a project
I've been working away at for about a year and I would REALLY like it finished
All and any help on this MUCH appreciated....
Best wishes
Monty
Re: Undefined Offset issue...
Posted: Tue May 11, 2010 2:35 am
by hypedupdawg
I would change the code like this (lines 230 - 240); i have not been able to test this code as i do not have your database etc, but give it a try:
Code: Select all
foreach($lines as $line) {
$fields = explode("&", $line);
// list($path, $comment) = $fields;
}
for ($i=0; $i<10; $i++)
{
if(!$fields[$i] || $fields[$i]=="")
{
$fields[$i] = "No comment left.";
}
}
Explanation:
I commented your list() function as it did not appear you were actually using it anywhere in the page - I did a search and couldn't find any relevant output.
The for() loop simply loops through the $fields array 10 times (you can always change this), and checks to see if the current value is not assigned or empty. It then replaces it with a pre-defined message, e.g. "No comment left." (You can change this as well.)
Hope this helps you
EDIT: Just to make it clear, I only put in the foreach() fuction to show you where to put the new code - the only new code to insert is from the for() statement downwards.