[Last Call] Learn about multicloud storage options and how to improve your company's cloud strategy. Register Now

x
?
Solved

php insert mysql loop - ajax error handerling

Posted on 2014-01-10
2
Medium Priority
?
874 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

Learn how to optimize MySQL for your business need

With the increasing importance of apps & networks in both business & personal interconnections, perfor. has become one of the key metrics of successful communication. This ebook is a hands-on business-case-driven guide to understanding MySQL query parameter tuning & database perf

Question has a verified solution.

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

In this series, we will discuss common questions received as a database Solutions Engineer at Percona. In this role, we speak with a wide array of MySQL and MongoDB users responsible for both extremely large and complex environments to smaller singl…
Originally, this post was published on Monitis Blog, you can check it here . In business circles, we sometimes hear that today is the “age of the customer.” And so it is. Thanks to the enormous advances over the past few years in consumer techno…
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…
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.
Suggested Courses

656 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