Solved

php insert mysql loop - ajax error handerling

Posted on 2014-01-10
2
862 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 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

Salesforce Made Easy to Use

On-screen guidance at the moment of need enables you & your employees to focus on the core, you can now boost your adoption rates swiftly and simply with one easy tool.

Question has a verified solution.

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

Suggested Solutions

I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
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 look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

726 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