?
Solved

php insert mysql loop - ajax error handerling

Posted on 2014-01-10
2
Medium Priority
?
868 Views
Last Modified: 2014-01-10
I have a ajax call which scans a directory and inserts image links into a database.
The problem I have is... how to I manage the loop and different errors.... For instance, if the first images adds ok to the db and the second doesn't.. Currently I will get a fail sent back to my ajax js.

I have set up a unique on the file name field in the mysql db. So some images may add ok, others will get a duplicate 1062 error.

I need to report back to the user that 6 images added ok. but images 1.jpg, 7.jpg 27.jpg didnt add.

I hope that makes sence....

Heres my PHP so far:

function scanSlideDirectory()
{
	$slidesGroupID		= $_POST['slidesGroupID'];

	$result3 = mysql_query("
	SELECT slidesGroupDirectory
	FROM   slidesGroups
	WHERE slidesGroupID = $slidesGroupID")
	or die("SELECT Error: ".mysql_error()); 
	
	$row3 = mysql_fetch_array($result3);

	$slidesGroupDirectory = str_replace('/','\\',$row3['slidesGroupDirectory']);
	
	$exclude_list = array(".", "..", ".DS_Store", "Thumbs.db");
		
	$slidesImageDir = $_SERVER["DOCUMENT_ROOT"]."\\webapp\\" . $slidesGroupDirectory;
	$imagesDirArray = array_diff(scandir($slidesImageDir), $exclude_list);
		
	//echo "slidesImageDir: " . $slidesImageDir . "<br><br><br>";
	//print_r ($imagesDirArray);
	
	$i=0;
	foreach ($imagesDirArray as $key => $value) {
		$key = $i;
		$result=mysql_query("INSERT INTO slides (slidesGroupID, slideNumber, slideLocation)".
		"VALUES ('$slidesGroupID', '$key', '$value')");

		if ($result) {
			$i++;
		}
	}	


//handle your query.
	if ($result == '') {
		 $ajaxResponse['status'] = "success";
		 $ajaxResponse['inserted'] = $i;
	} else {
		 $ajaxResponse['status'] = "failure";
		 $ajaxResponse['message'] = "There was a problem: " . mysql_errno() . ": " . mysql_error();
	}

	echo json_encode($ajaxResponse);	
}

Open in new window


and my js

function scanDirectory(slidesGroupID) {
    $.blockUI({ message: 'Scanning slide group: ' + slidesGroupID + '<br>Please Wait...' }); 

	$.ajax({
		type:"POST",
		dataType : 'json',
		url: "library/process_slides.php",
		data:'slidesGroupID=' + slidesGroupID + '&action=scanSlideDirectory',
		cache: false,
	
		success:function(data) {
			if (data.status == "success") {
				$.unblockUI();
				alert("Horray! " + data.inserted + " slides have been added.");
			} else {
				$.unblockUI();
				alert("Oops. " + data.message);
			}
		}
	})
};

Open in new window

0
Comment
Question by:Steve Tinsley
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 35

Accepted Solution

by:
gr8gonzo earned 2000 total points
ID: 39771277
I would...

1. Capture the failed filenames and their errors in a separate array:

$failedImages = array(); // <=============== Add this line
$i=0;
	foreach ($imagesDirArray as $key => $value) {
		$key = $i;
		$result=mysql_query("INSERT INTO slides (slidesGroupID, slideNumber, slideLocation)".
		"VALUES ('$slidesGroupID', '$key', '$value')");

		if ($result) {
			$i++;
		}
                // ======= And add the below lines ========
                else
                {
                   $failedImages[$value] = mysql_errno() . ": " . mysql_error();
                }
	}

Open in new window


2. Check the number of failed images to determine success or not and use the array to show the errors:
if (count($failedImages) == 0) {  // <=============== Update this line
		 $ajaxResponse['status'] = "success";
		 $ajaxResponse['inserted'] = $i;
	} else {
		 $ajaxResponse['status'] = "failure";
                 // ======== And add/update the below lines ========
		 $ajaxResponse['message'] = "There was at least one problem: ";
                 foreach($failedImages as $failedImage => $error)
                 {
                                  $ajaxResponse['message'] .= "{$failedImage} failed ({$error})<br />\n";
                 }
                 // $ajaxResponse['failedImages'] = $failedImages;
	}

Open in new window


3. Profit!
0
 

Author Closing Comment

by:Steve Tinsley
ID: 39771532
AMAZING! I can take that further now!
Thanks
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
This post looks at MongoDB and MySQL, and covers high-level MongoDB strengths, weaknesses, features, and uses from the perspective of an SQL user.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to dynamically set the form action using jQuery.
Suggested Courses

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question