1

This is a problem I solved a lot of times in different ways, but never could quite get an elegant solution for.

I have an SQL string which I want to build:

$sql = "UPDATE table";
$sql .= "SET"; 
$sql .= "sqlTableName = 'Y', column2 = value2";

now, based on

isset($_GET['value1'])

I want to add:

$sql .= "sqlTableName = 'Y',"

and based on

isset($_GET['value2'])    

I want:

$sql .= "sqlTableName2 = 'Y',"

to be added.

If I put the comma before or after the string I run into trouble.

Now I know how to solve it but how to do this elegantly?

Dharman
  • 30,962
  • 25
  • 85
  • 135
SanThee
  • 2,301
  • 3
  • 23
  • 35

2 Answers2

6

Put the values in an array, then use an array join method. The specific syntax would depend on which programming language you are using.

The tags you selected are not helpful at all in determining what that is but it looks like you are using PHP.

<?php
    $values = [ $_GET['value1'], $_GET['value2'] ];
    print join(", ", $values);

(Obviously, since the number of values in the array is variable for your case, you would generate it dynamically, probably using a push method, and sticking user input directly into SQL is dangerous).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

You can build an array of all the fields to be updated and then implode them together.

$sql = "UPDATE table SET "; 

$setArray = [];
if(isset($_GET['value1'])){
    $setArray[] = "sqlTableName = 'Y'";
}
if(isset($_GET['value2'])){
    $setArray[] = "sqlTableName2 = 'Y'";
}

echo $sql.implode(', ', $setArray);

This is very simple when you have hardcoded values. It gets more difficult with user input, which must be parameterized. You need to collect the values in a separate table.

Here is an example, how this would be achieved with PDO.

$setFields = [];
$setValues = [];
if (isset($_GET['value1'])) {
    $setFields[] = "sqlTableName = ?";
    $setValues[] = $_GET['value1'];
}
if (isset($_GET['value2'])) {
    $setFields[] = "sqlTableName2 = 'Y'";
    $setValues[] = $_GET['value2'];
}

$pdo = new PDO($dsn, $user, $pass, [
    \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
    \PDO::ATTR_EMULATE_PREPARES => false
]);

$pdo->prepare("UPDATE table SET ".implode(', ', $setFields))->execute($setValues);
Dharman
  • 30,962
  • 25
  • 85
  • 135