0

I have a custom html page which posts to php variables which then fills out custom sql queries.

function load_table($db, $old_table, $startRow, $nameColumn, $ipColumn, $addressColumn, $cityColumn, $stateColumn, $zipColumn, $countryColumn)
{
$select = "SELECT $nameColumn, $ipColumn, $addressColumn, $cityColumn, $stateColumn, $zipColumn, $countryColumn FROM " .$old_table.";";
$q = mysqli_query($db, $select);

return $q;
}

It works perfectly when all the variables are holding a value, but I need a way to dynamically assert this query, so that if the user is missing a column, i.e zip code is not in their table, it will still run without ruining the query.

5 Answers 5

2
$array = array();

if ($nameColumn)
    $array[] = $nameColumn;
if ($ipColumn)
    $array[] = $ipColumn;

// etc...

$cols = implode(',', $array);

if ($cols)
{
    $select = "SELECT $cols FROM $old_table;";
    $q = mysqli_query($db, $select);
    return $q;
}
Sign up to request clarification or add additional context in comments.

3 Comments

This is the proper way of doing it.
I have yet to try it but this makes the most sense! Thanks so much!
Actually, this could be improved using func_get_args as pointed out by Falci.
2

Or you can use

$select = "SELECT ".(($nameColumn != '')?$nameColumn.",":"")." .......";

Comments

1

See also: https://www.php.net/manual/en/function.func-get-args.php

Comments

1

Put all your variables in an array then do the following:

function load_table($db, $old_table, $startRow, array $columns) {
    $columns = array_filter($columns, 'strlen'); // removes empty values
    $select = "SELECT " . implode(",", $columns) . " FROM " .$old_table.";";
    $q = mysqli_query($db, $select);
    return $q;
}

3 Comments

I am unfamiliar with the implode function. Does it simply remove variables from the array which are null?
Then how would this help with my issue? The issue is that if one of the variables does not have a value, the sql query will throw an error because the value of the php variable is null
@user1475765 I've updated my answer that it removes empty values
0

You can give it a default:

function load_table($db, $old_table, $startRow, $nameColumn="Default name", $ipColumn, $addressColumn, $cityColumn, $stateColumn, $zipColumn, $countryColumn)

In this case $nameColumn will always have a value unless otherwise specified

1 Comment

Thanks for your response! This sounds good, but my concern is that with a default name, and no guarentee the default name is in the table, an error will occur because it will try to look up that column name and will not find it. Unless theres a default name I can give it which will simply act as a placeholder?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.