Absinthe
Absinthe

Reputation: 3391

PHP add a variable to to mySQLi query results

I have a PHP function called GetQA which returns data from MySQL:

$result = mysqli_query($con, $sqlQuery) or die(mysqli_error()$con);

I'd like to add a dynamically generated variable result to the end. I don't want to store that variable in the database.

What I'd like to is something like this:

$result = Array(mysqli_query($con, $sqlQuery), myVariable);

Is this possible?

Upvotes: 2

Views: 67

Answers (1)

rickdenhaan
rickdenhaan

Reputation: 11298

Assuming $myVariable will be the same for all rows, I can think of two ways off the top of my head to do this:

$result = mysqli_query($con, $sqlQuery) or die(mysqli_error($con));

while ($row = mysqli_fetch_assoc($result)) {
    $row['myVariable'] = $myVariable;

    // do whatever you want to $row now, $myVariable will be at the end
}

Or:

$sqlQuery = "SELECT field1, field2, field3, '" . $myVariable . "' as myVariable FROM table";
$result = mysqli_query($con, $sqlQuery) or die(mysqli_error($con));

while ($row = mysqli_fetch_assoc($result)) {
    // $myVariable will be in $row['myVariable']
}

Keep in mind that in that last example, you will need to make sure $myVariable is properly escaped.

Upvotes: 1

Related Questions