Skip to content
View in the app

A better way to browse. Learn more.

Web Designer Forum

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

Need Help With Complex SQL Update Statement

Featured Replies

I'm trying to build a SQL Update statement using data submitted from an HTML form, but I think I'm doing a better job at destroying brain cells (and pulling out hair) than I am at finding a solution.

 

As an example, the basic structure of the query I'm trying to build is as follows:

UPDATE [AES_StoreAppVersions]
SET [fk_ApplicationVersionID] = CASE [storeAppVersionID]
WHEN 1839 THEN 1
WHEN 2688 THEN 23
WHEN 10386 THEN 12
END
WHERE [storeAppVersionID] IN (1839,2688,10386)

 

The [AES_StoreAppVersions] table itself is very simple and only contains 3 columns:

[storeAppVersionID] = auto incrementing unique ID

[fk_StoredID] = not unique, links to another table with store details

[fk_ApplicationVersionID] = not unique, links to another table with application details

 

Since the form is built dynamically this may not be the easiest to follow, but bear with me for a moment.. The form from which the data is being submitted has one <select> for each application, with one <option> for each available version of that application.

 

Each <select> has the [storeAppVersionID] as it's name, and each <option> has the [ApplicationVersionID] as it's value (linked to [fk_ApplicationVersionID]).

 

If it helps at all, here is the PHP I've got so far for this query:

$queryString = "UPDATE [AES_StoreAppVersions]
SET [fk_ApplicationVersionID] = CASE [storeAppVersionID] ";
foreach ($array as $item) {
$queryString .= "WHEN ".$item[0]." THEN ".$item[1];
}
$queryString .= "END
WHERE [storeAppVersionID] IN (".$array.")";

 

Taken in relation to the DB, the $array variable needs to be an array of [storeAppVersionID] => [fk_ApplicationVersionID], with the array keys pulled from the multiple <select> options. Whether the data is posted in the correct format, or if it's restructured in the PHP function after post doesn't really matter too much, but I can't get either way to work.

 

If I use <select name="appID"> for each select, I can get to them just fine with $_POST[appID], but I can't tell which applicationID needs to go where in the update statement. On the other hand, if I use the unique [storeAppVersionID] for the form, I won't have any problem working out which ID needs to be updated, but I can't figure out how to structure the $_POST[] command to get the posted values when the names are different for every single <select>...

 

I need somebody to kick me back onto the straight and narrow before I spend eternity going around in circles... I'm feeling very confused right now, any ideas how I can do this? If you need to see the actual code from the different <select>s, let me know and I'll type out a manual example. The forms are generated using a PHP file loaded via an AJAX call that's run from a button that's generated by other PHP earlier on, most of the page is displayed dynamically and doesn't show in Chrome's 'view source' option.. :/

Wait, are you using the HTML's form <select> with <option> ? (Like dropdown)

  • Author

Hi Dino,

 

For the application versions yes, it is a drop down list. Here's a snip of the page when the form loads:

post-23450-0-92429500-1339236344_thumb.png

 

Not sure if this makes any difference to the actual problem at hand, but just for your information I'm submitting the forms using JS in order to prevent the page from reloading.

<script type="text/javascript">
$("form").submit(function(){
	var str = $(this).serialize();
	$.post('includes/update.php', str, function(result){
		$.jGrowl(result);
	})
	return(false);
});
</script>

 

Each form is submitted along with a 'formID' field to identify the source form, at which point a switch statement sets up the SQL query that should be used, and all the code to run the query and return a response is at the end.

 

The problem I'm having is with trying to link the newly selected ApplicationVersionID (but not a unique field in the DB table I'm trying to update) with the current StoreAppVersionID (which is a unique field). But when I try use the StoreAppVersionID as the name for the <select>, I can't find it with checking $_POST[] values from inside update.php... I don't know how to do that if the name of the item is generated dynamically.

How about adding a "id" field to the option tag and pulling it (well fill it with PHPs some kind of id first) with javascript to php?

  • Author

I think I've made some good progress, I've been reading up on different ways to use $_POST and I found something very interesting.. I've altered the form to use the following line for creating the <select>s:

 

<select name="appVerID[<?php echo($apps["StoreAppVersionID"]); ?>]">

 

In the generated form, I now have a form with the following basic structure (typed out, not copied):

 

<select name="appVerID[8]">
<option value="0">--select a new version--</option>
<option value="1">New Version 1</option>
<option value="2">New Version 2</option>
<option value="3">New Version 3</option>
</select>
<select name="appVerID[12]">
<option value="0">--select a new version--</option>
<option value="4">New Version 1</option>
<option value="5">New Version 2</option>
<option value="6">New Version 3</option>
</select>

 

The value="0" options are used to filter out entries that don't need to be updated. Now when the form is submitted, I can put these entries into an array using the following:

 

$newValues = $_POST["appVerID"];

$queryString = 
"UPDATE [AES_StoreAppVersions]
SET [fk_ApplicationVersionID] = CASE [storeAppVersionID]\n";
foreach ($newValues as $key => $value) {
if ($value != 0) {
	$queryString .= "WHEN ".$key." THEN ".$value."\n";
}
}
$queryString .= "END";

 

While this in itself will generate a SQL query that will update the values I want, the table currently has nearly 16000 rows, so without limiting the UPDATE statement to only the rows that need to be updated would put unneeded strain on the server... I still need to get the array keys into the 'WHERE [storeAppVersionID] IN (".$arrayKeys.")' line of the query. The closest I've got so far is the following query:

 

UPDATE [AES_StoreAppVersions]

SET [fk_ApplicationVersionID] = CASE [storeAppVersionID]
WHEN 17 THEN 2
WHEN 2866 THEN 24
END

WHERE [storeAppVersionID] IN (1)

 

But it needs to be:

 

UPDATE [AES_StoreAppVersions]

SET [fk_ApplicationVersionID] = CASE [storeAppVersionID]
WHEN 17 THEN 2
WHEN 2866 THEN 24
END

WHERE [storeAppVersionID] IN (17, 2866)

 

I tried using array_keys($newValues), but whether I try it straight, or with print, or with print_r, I can't get it to output as a string to include in $queryString.

 

Any suggestions here?

 

Edit: Sorry Dino, didn't see your reply before I posted. I was trying to do this without having to send yet another data field with the submitted form, I already have all the required data being sent, I just need to catch it correctly in 'update.php'.

Edited by ZaLiTH

Yeah you should do it this way:

 

 

 

 


<?php

$someVar = array('mike', 'john', 'andy');

foreach($someVar as $var) {
echo "$var, ";
}

?>

 

 

 

  • Author

Sorry, but I don't really see how that helps me.. If you look through my last reply again, you'll see the values I need for the 'where' clause in my SQL statement are already being passed to 'update.php' in an array when I submit the form, but they are the keys in an associative array. I just need to figure out how to get just the keys listed in string format in order to concatenate that string to the end of my $queryString variable for the SQL query.

 

Here's an example of the associative arrays that I'll be using:

array {
1839 => 2
4688 => 24
7537 => 30
10386 => 12
13235 => 17
}

 

The keys (1839, 4688, etc) are [storeAppVersionID], the values (2, 24, etc) are [ApplicationVersionID]. Any idea how I can pull just the keys into a string from this array?

Sorry, but I don't really see how that helps me.. If you look through my last reply again, you'll see the values I need for the 'where' clause in my SQL statement are already being passed to 'update.php' in an array when I submit the form, but they are the keys in an associative array. I just need to figure out how to get just the keys listed in string format in order to concatenate that string to the end of my $queryString variable for the SQL query.

 

Here's an example of the associative arrays that I'll be using:

array {
1839 => 2
4688 => 24
7537 => 30
10386 => 12
13235 => 17
}

 

The keys (1839, 4688, etc) are [storeAppVersionID], the values (2, 24, etc) are [ApplicationVersionID]. Any idea how I can pull just the keys into a string from this array?

 

Use the same concept he gave you with alittle bit of change

 

foreach($array as $key => $value){
echo $key;
}

 

that allows you to eather get the key or the value

  • Author

Use the same concept he gave you with alittle bit of change

 

foreach($array as $key => $value){
echo $key;
}

 

that allows you to eather get the key or the value

To be honest, I did consider using foreach, but trying to get a comma in between each of them for the "WHERE [x] IN (1,2,3,4)" section wasn't working for me. I think I've just managed to get it working with a combination of implode() and array_keys() though.

 

To build the query, I've now got:

$queryString = 
"UPDATE [AES_StoreAppVersions]
SET [fk_ApplicationVersionID] = CASE [storeAppVersionID]\n";
foreach ($newValues as $key => $value) {
if ($value != 0) {
	$queryString .= "WHEN ".$key." THEN ".$value."\n";
}
}
$queryString .= "END
WHERE [storeAppVersionID] IN (".implode(",",array_keys($newValues)).")";

 

Which correctly generated the following script ():

UPDATE [AES_StoreAppVersions] 
SET [fk_ApplicationVersionID] = CASE [storeAppVersionID] 
WHEN 1839 THEN 2
WHEN 4688 THEN 24
WHEN 7537 THEN 30
WHEN 10386 THEN 12
WHEN 13235 THEN 17
END
WHERE [storeAppVersionID] IN (1839,4688,7537,10386,13235)

 

I know I didn't take any of the suggestions as they were intended, but in the end I did manage to get it working. :)

  • Author

For the benefit of anybody else who decides to read through this, I did have a small problem with the last part of the query... While the 'WHEN THEN' section was correctly excluding items in the array with a value of '0' (see the value setting for the options in the form), the variable I imploded to build the 'WHERE' part of the statement was being difficult.

 

Instead of trying to filter out an array in two separate areas, I decided to use unset() to remove items from the array where their value was '0'. I first prepare the array as follows:

 

$newValues = $_POST["appVerID"]; // array([storeAppVersionID] => [fk_ApplicationVersionID])
foreach ($newValues as $key => $value) {
if ($value == '0') {
	unset($newValues[$key]);
}
}
$storeAppVersionIDs = implode(",",array_keys($newValues));

 

This removes all entries from the array where the value is '0'. After which, I do the following:

 

if (count($newValues) != 0) {
// SQL statement
$queryString = 
"UPDATE [AES_StoreAppVersions]
SET [fk_ApplicationVersionID] = CASE [storeAppVersionID]\n";
foreach ($newValues as $key => $value) {
$queryString .= "	WHEN ".$key." THEN ".$value."\n";
}
$queryString .= "END
WHERE [storeAppVersionID] IN (".$storeAppVersionIDs.")";

// Prepare query
$stmt = $dbh->prepare($queryString);
}

 

This way, any of the submitted <select> elements that have a value of '0' are not included in the array when $queryString is built. :) So only items that need to be updated are actually included in the update statement.

Create an account or sign in to comment

Account

Navigation

Search

Search

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.