Solved

php insert mysql loop - ajax error handerling

Posted on 2014-01-10
2
858 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:sjtinsley83
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:sjtinsley83
ID: 39771532
AMAZING! I can take that further now!
Thanks
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

This article discusses four methods for overlaying images in a container on a web page
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to count occurrences of each item in an array.

762 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

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now