Undefined offset: 0 error

14 posts by 2 authors in: Forums > CMS Builder
Last Post: November 9, 2018   (RSS)

By gkornbluth - October 30, 2018 - edited: October 30, 2018

Hi All,

I’m stuck again.

Here’s a form that I created based on a recipe from my CMSB cookbook that I thought worked fine but when I load the update form I’m getting the following error:

Notice: Undefined offset: 0 in /home3/ellescho/public_html/dbtproviders/provider_profile_multi.php on line 451

which I’ve narrowed down to the following code in step 2 of the recipe below:

<?php list(list($current_user_with_uploads),) = getRecords(array('tableName' => 'accounts', 'where' => mysql_escapef('num = ?', $CURRENT_USER['num']), 'allowSearch' => false)); ?>

BTW: The uploading portion of the scheme works perfectly and it uploads and replaces the profile image as planned.

The error is thrown whether there's an uploaded image or not.

Any help would be appreciated.

Thanks,

Jerry Kornbluth

ADDING A PROFILE IMAGE USING THE PROFILE UPDATE FORM - Sep 3rd, 2018

I needed to add a profile image to existing account records using the profile update form that’s part of the Website Membership Plugin. I also wanted to enable replacing that profile image when desired.

I was stumped until I came across this hidden gem provided by Chris way back in 2010.

He said:

1) Add an upload field to the accounts table called Profile Image and limit the maximum uploads to 2 (this allows an existing profile image to be replaced with a new one)

2) Add the following to your existing form table (style as appropriate):

<tr>
<td valign="top">Profile Image</td>
<td>
<?php list(list($current_user_with_uploads),) = getRecords(array('tableName' => 'accounts', 'where' => mysql_escapef('num = ?', $CURRENT_USER['num']), 'allowSearch' => false)); ?>
<?php if (sizeof(@$current_user_with_uploads['profile_image'])):
$upload = $current_user_with_uploads['profile_image'][0] ?>
<a href="<?php echo $upload['urlPath'] ?>">
<img src="<?php echo $upload['thumbUrlPath'] ?>" width="<?php echo $upload['thumbWidth'] ?>" height="<?php echo
$upload['thumbHeight'] ?>" alt="" />
</a>
<?php else: ?>
No image uploaded
<?php endif ?>
Upload: <input type="file" name="profile_image">
</td>
</tr>

3) Add

ENCTYPE="multipart/form-data"

to any other code in your opening <FORM> tag.

4) Add the following just before // update user

// upload 'profile_image' if supplied
$uploadFieldName = 'profile_image';
$uploadInfo = @$_FILES[$uploadFieldName];
if ($uploadInfo && !$errorsAndAlerts) {

/// attempt to save the upload
$errors = saveUpload('accounts', $uploadFieldName, $CURRENT_USER['num'], null, $uploadInfo, $newUploadNums);

/// check for errors
if ($errors) {
$errorsAndAlerts .= "There was a problem with your upload: $errors\n";
}
else {

/// if the upload was successful, delete any other uploads associated with that record and field (so users only ever
have 1 profile image)
global $TABLE_PREFIX;

// create query
$where = mysql_escapef(" WHERE tableName = 'accounts' AND recordNum = ? AND num != ?", $CURRENT_USER['num'],
$newUploadNums[0]);

// remove upload files
$query = "SELECT * FROM `{$TABLE_PREFIX}uploads` $where";
$result = mysql_query($query) or die("MySQL Error: ". htmlspecialchars(mysql_error()) . "\n");
while ($row = mysql_fetch_assoc($result)) {
$files = array($row['filePath'], $row['thumbFilePath'], @$row['thumbFilePath2'], @$row['thumbFilePath3'],
@$row['thumbFilePath4']);
foreach ($files as $filepath) {
if (!$filepath || !file_exists($filepath) || @unlink($filepath)) { continue; }

//$error = "Unable to remove file '" .htmlspecialchars($filepath). "'\n\n";
//$error .= "Please ask your server administrator to check permissions on that file and directory.\n\n";
//$error .= "The PHP error message was: $php_errormsg\n";
//die($error);
}
}
if (is_resource($result)) { mysql_free_result($result); }

// remove upload records
mysql_query("DELETE FROM `{$TABLE_PREFIX}uploads` $where") or die("MySQL Error: ". htmlspecialchars(mysql_error()) .
"\n");
}

}

Chris added that more than half of that code is dedicated to removing any other uploads after an upload is successful so
that users never have more than one profile image. This is important since I haven't provided any way for users to
remove a profile image. They can, of course, replace their current image with another. (This is where the maximum upload
limit of 2 comes in. If it was set to allow only 1, then the upload of the replacement image, seen as a second image
before the original was removed, would fail.)

The first CMS Builder reference book is now available on-line!







Take advantage of a free 3 month trial subscription, only for CMSB users, at: http://www.thecmsbcookbook.com/trial.php

By daniel - October 30, 2018

Hey Jerry,

Are you viewing this page while logged in? The line that you indicate (<?php list(list($current_user_with_uploads),) = ...) would throw that error if getRecords() returns zero results, e.g. no "current user." It doesn't appear that there's a user-check in the code above, so it's theoretically possible that you're updating the profile image for "no user". I would recommend adding such a check - a standard one (requires Website Membership plugin) being:

if (!$CURRENT_USER) { websiteLogin_redirectToLogin(); }

Let me know if that helps!

Thanks,

Daniel
Technical Lead
interactivetools.com

Hi Daniel,

As always, appreciate the help you offer us.

Yes I am checking for a current user with that exact code.

This is also a user account update form using the website membership plugin.

Everything else, including uploading and saving a new image works fine.

I get the error whether there is an image uploaded or not.

Thanks,

Jerry

The first CMS Builder reference book is now available on-line!







Take advantage of a free 3 month trial subscription, only for CMSB users, at: http://www.thecmsbcookbook.com/trial.php

By daniel - November 2, 2018

Hi Jerry,

It sounds like there's something a bit non-obvious occurring. Have you by chance changed the accounts table used by the Website Membership plugin to something other than "accounts"? If not, one other thing I can suggest is changing the line in question so that it requires a found record:

<?php 
  list($accountRecords,) = getRecords(array('tableName' => 'accounts', 'where' => mysql_escapef('num = ?', $CURRENT_USER['num']), 'allowSearch' => false));
  $current_user_with_uploads = @$accountRecords[0];
  if (!$current_user_with_uploads ) { dieWith404("Record not found!"); }
?>

If this prevents the page from loading, then that points to a problem with retrieving the user's account record, which is a more concrete issue to troubleshoot.

Otherwise, if you don't mind filling out a support request (https://www.interactivetools.com/support/email_support_form.php) with the CMS/FTP details I'd be happy to take a look at it.

Thanks,

Daniel
Technical Lead
interactivetools.com

By daniel - November 5, 2018

A quick summary for anyone else who may encounter a similar error, this was caused by the "hidden" flag being set on the current user's account record. The getRecords() field doesn't display hidden records by default, so the "ignoreHidden" option needed to be added. The result being something like this:

list($accountRecords,) = getRecords(array('tableName' => 'accounts', 'where' => mysql_escapef('num = ?', $CURRENT_USER['num']), 'allowSearch' => false, 'ignoreHidden' => true));
$current_user_with_uploads = @$accountRecords[0];

Note that dieWith404() (used in a previous example) cannot be called if there's already output on the page, so it did not suit this particular case and was removed.

Cheers,

Daniel
Technical Lead
interactivetools.com

By gkornbluth - November 8, 2018 - edited: November 8, 2018

Hi Daniel,

Hate to bother you again, but I’ve hit a snag.

I’ve been able (with your help) to upload and/ or replace a single “profile” image for a single provider in an account record.

When I try to upload a “profile” image for more than one provider in the same account record, I can’t get them both to work.

*** There will ultimately be 12 or more individual profile images for 12 or more providers.

If I comment the upload code block for either provider all works as planned.

If I try to upload an image with both code blocks active, both images are deleted. (leaving the code for both images in the form seems to have no ill effects)

I’ve tried naming all variables for each image uniquely to avoid any conflicts but it seems I've missed something and am out of ideas.

Hope you can find the culprit easily.

Should you need them, there are 3 demonstration files (you’ll need to log in for them). The results will show up in your account record.

1) http://www.dbtproviders.com/provider_profile_multiF php with one block commented
2) http://www.dbtproviders.com/provider_profile_multiG with the other block commented
3) http://www.dbtproviders.com/provider_profile_multiH.php with both blocks active

Thanks as always,

Jerry Kornbluth

Here are the 2 code blocks.
// /*
// ******************Begin upload practice profile image if supplied ***********************

$uploadFieldName = 'profile_image';
$uploadInfo = @$_FILES[$uploadFieldName];
if ($uploadInfo && !$errorsAndAlerts) {

/// attempt to save the upload
$errors = saveUpload('accounts', $uploadFieldName, $CURRENT_USER['num'], null, $uploadInfo, $newUploadNums);

/// check for errors
if ($errors) {
$errorsAndAlerts .= "There was a problem with your upload: $errors<br/>\n";
}
else {

// if the upload was successful, delete any other uploads associated with that record and field (so users only ever have 1 profile image)
global $TABLE_PREFIX;

// create query
$where = mysql_escapef(" WHERE tableName = 'accounts' AND recordNum = ? AND num != ?", $CURRENT_USER['num'], $newUploadNums[0]);

// remove upload files
$query = "SELECT * FROM `{$TABLE_PREFIX}uploads` $where";
$result = mysql_query($query) or die("MySQL Error: ". htmlspecialchars(mysql_error()) . "\n");
while ($row = mysql_fetch_assoc($result)) {
$files = array($row['filePath'], $row['thumbFilePath'], @$row['thumbFilePath2'], @$row['thumbFilePath3'], @$row['thumbFilePath4']);
foreach ($files as $filepath) {
if (!$filepath || !file_exists($filepath) || @unlink($filepath)) { continue; }

//$error = "Unable to remove file '" .htmlspecialchars($filepath). "'\n\n";
//$error .= "Please ask your server administrator to check permissions on that file and directory.\n\n";
//$error .= "The PHP error message was: $php_errormsg\n";
//die($error);
}
}
if (is_resource($result)) { mysql_free_result($result); }

// remove upload records
mysql_query("DELETE FROM `{$TABLE_PREFIX}uploads` $where") or die("MySQL Error: ". htmlspecialchars(mysql_error()) . "\n");
}

}
// ******************End upload profile image if supplied ***************************
// */

// /*
// ******************Begin upload therapist 1 profile image if supplied *******************

$uploadFieldName1 = 'profile_image_practitioner_1';
$uploadInfo1 = @$_FILES[$uploadFieldName1];
if ($uploadInfo1 && !$errorsAndAlerts) {

// attempt to save the upload
$errors1 = saveUpload('accounts', $uploadFieldName1, $CURRENT_USER['num'], null, $uploadInfo1, $newUploadNums1);

// check for errors
if ($errors1) {
$errorsAndAlerts .= "There was a problem with your upload: $errors<br/>\n";
}
else {

// if the upload was successful, delete any other uploads associated with that record and field (so users only ever have 1 profile image)
global $TABLE_PREFIX;

// create query
$where = mysql_escapef(" WHERE tableName = 'accounts' AND recordNum = ? AND num != ?", $CURRENT_USER['num'], $newUploadNums1[0]);

// remove upload files
$query1 = "SELECT * FROM `{$TABLE_PREFIX}uploads` $where";
$result1 = mysql_query($query1) or die("MySQL Error: ". htmlspecialchars(mysql_error()) . "\n");
while ($row1 = mysql_fetch_assoc($result1)) {
$files1 = array($row1['filePath'], $row['thumbFilePath'], @$row1['thumbFilePath2'], @$row1['thumbFilePath1'], @$row['thumbFilePath4']);
foreach ($files1 as $filepath1) {
if (!$filepath1 || !file_exists($filepath1) || @unlink($filepath1)) { continue; }

//$error = "Unable to remove file '" .htmlspecialchars($filepath). "'\n\n";
//$error .= "Please ask your server administrator to check permissions on that file and directory.\n\n";
//$error .= "The PHP error message was: $php_errormsg\n";
//die($error);
}
}
if (is_resource($result1)) { mysql_free_result($result1); }

// remove upload records
mysql_query("DELETE FROM `{$TABLE_PREFIX}uploads` $where") or die("MySQL Error: ". htmlspecialchars(mysql_error()) . "\n");
}

}

// ************************* End upload Therapist 1 image *************************
// */

And here’s the code for the upload form.

<form ENCTYPE="multipart/form-data" method="post" action="?">
<table>
<tr>
<td class="heading_font" colspan="2"><b>PROFILE IMAGE</b></td>
</tr>
<tr>
<td class="text_font" valign="top">1 JPG Only - 2 MB max. -
Uploading a new image will replace any existing image.
<br /><br />
Images will be uploaded when the &quot;revalidate or update&quot; button at the bottom of this page is clicked/tapped.</td>
<td>
<?php list($accountRecords,) = getRecords(array('tableName' => 'accounts', 'where' => mysql_escapef('num = ?', $CURRENT_USER['num']), 'allowSearch' => false, 'ignoreHidden' => true));
$current_user_with_uploads = @$accountRecords[0];
?>
<?php if (sizeof(@$current_user_with_uploads['profile_image'])):
$upload2 = $current_user_with_uploads['profile_image'][0] ?>
<a href="<?php echo $upload2['urlPath'] ?>">
<img src="<?php echo $upload2['thumbUrlPath'] ?>" width="<?php echo $upload2['thumbWidth'] ?>" height="<?php echo $upload2['thumbHeight'] ?>" alt="" /><br/>
</a>
<?php else: ?>
<span class="text_font">No (new) image uploaded</span><br />
<?php endif ?>
<span class="text_font">Image To Upload:</span> <input type="file" name="profile_image">

</td>
</tr>
<tr>
<td class="text_font" colspan="2"><b>PRACTITONER 1 PROFILE IMAGE</b></td>
</tr>
<tr>
<td colspan="2" class="text_font" valign="top">1 JPG Only - 2 MB max. - Uploading a new image will replace any existing image. Images will be uploaded when the &quot;revalidate or update&quot; button at the bottom is clicked/tapped.</td>
<td><?php list($accountRecords,) = getRecords(array('tableName' => 'accounts', 'where' => mysql_escapef('num = ?', $CURRENT_USER['num']), 'allowSearch' => false, 'ignoreHidden' => true));
$current_user_with_uploads1 = @$accountRecords[0];
?>
<?php if (sizeof(@$current_user_with_uploads1['profile_image_practitioner_1'])):
$upload1 = $current_user_with_uploads1['profile_image_practitioner_1'][0] ?>
<a href="<?php echo $upload1['urlPath'] ?>"> <img src="<?php echo $upload1['thumbUrlPath'] ?>" width="<?php echo $upload1['thumbWidth'] ?>" height="<?php echo $upload1['thumbHeight'] ?>" alt="" /><br/>
</a>
<?php else: ?>
<span class="text_font">No (new) image uploaded</span><br />
<?php endif ?>
<span class="text_font">Image To Upload:</span>
<input type="file" name="profile_image_practitioner_1"></td>
</tr>
</table>
</form>

The first CMS Builder reference book is now available on-line!







Take advantage of a free 3 month trial subscription, only for CMSB users, at: http://www.thecmsbcookbook.com/trial.php

By daniel - November 8, 2018

Hi Jerry,

It appears that at least part of the problem is that the code that prevents more than one image from being uploaded is applying to all uploads on that record, not per upload field. You should be able to account for this by updating the $where variable to this (adjusting for any changed variable names):

$where = mysql_escapef(" WHERE tableName = 'accounts' AND recordNum = ? AND num != ? AND fieldName = ?", $CURRENT_USER['num'], $newUploadNums[0], $uploadFieldName);

It also looks like, when changing the variable names, you missed a couple of $row variables on line 192. 

Try fixing the above, and see if that gives you any progress.

Thanks,

Daniel
Technical Lead
interactivetools.com

Hi Daniel,

Thanks for catching the $row and $row1 error

I updated the $wheres, but I'm still having a problem with existing image's being deleted.

 **** The new code is in http://www.dbtproviders.com/provider_profile_multiI.php ****

I changed the variables to $uploadFieldName and $uploadFieldName1 in the $where's for the 2 code blocks as follows:

$where = mysql_escapef(" WHERE tableName = 'accounts' AND recordNum = ? AND num != ? AND fieldName = ?", $CURRENT_USER['num'], $newUploadNums[0], $uploadFieldName); // Per Daniel 11/7/18

$where = mysql_escapef(" WHERE tableName = 'accounts' AND recordNum = ? AND num != ? AND fieldName = ?", $CURRENT_USER['num'], $newUploadNums[0], $uploadFieldName1); // Per Daniel 11/7/18

Was I supposed to change anything else there?

Thanks,

Jerry Kornbluth

The first CMS Builder reference book is now available on-line!







Take advantage of a free 3 month trial subscription, only for CMSB users, at: http://www.thecmsbcookbook.com/trial.php

By daniel - November 8, 2018

Hi Jerry,

In the 2nd $where, it looks like $newUploadNums should be $newUploadNums1.

Try that out and let me know how it goes!

Thanks,

Daniel
Technical Lead
interactivetools.com