Solved

php insert mysql loop - ajax error handerling

Posted on 2014-01-10
2
860 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
2 Comments
 
LVL 34

Accepted Solution

by:
gr8gonzo earned 500 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

Ransomware-A Revenue Bonanza for Service Providers

Ransomware – malware that gets on your customers’ computers, encrypts their data, and extorts a hefty ransom for the decryption keys – is a surging new threat.  The purpose of this eBook is to educate the reader about ransomware attacks.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Making API calls from hashed passwords 26 53
paypal ipn to mysql 3 36
php extract($_REQUEST) 5 49
Display images from mysql blob type (Not working) 9 28
The Confluence of Individual Knowledge and the Collective Intelligence At this writing (summer 2013) the term API (http://dictionary.reference.com/browse/API?s=t) has made its way into the popular lexicon of the English language.  A few years ago, …
Load balancing is the method of dividing the total amount of work performed by one computer between two or more computers. Its aim is to get more work done in the same amount of time, ensuring that all the users get served faster.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

770 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