0

I'm experiencing something strange, and I can't figure out why it's happening. I'm running a query to pull data from a column in a mysql table, and when I do a straight printf(), the data comes out as expected. However, when I do $variable = printf(), I'm getting an additional value in the string.

The following prints something like: 22611,21435,23327,22876,22986,23692,21581,21832,22337,24313,22174,24368,

$query  = "SELECT column FROM table WHERE year in (2012)";
if ($result = mysqli_query($connect, $query)) {
    while ($row = mysqli_fetch_assoc($result)) {
        printf ("%s,", $row["column"]);
    }
}

But if I try to put the result into a variable like so:

$data = printf ("%s,", $row["column"]);

I get an output of 22611,21435,23327,22876,22986,23692,21581,21832,22337,24313,22174,24368,6

Why is it adding this extra value? Am I adding the result to the variable incorrectly? FYI, this is just a snippet from the code, I have error handling in place.

2
  • You should have a look at the printf() manual. By the way, why are you using "in" in your request ? Commented Feb 6, 2013 at 18:30
  • Because the year is actually a variable, and sometimes its value is "2008,2009,2010" or something to that effect. Commented Feb 6, 2013 at 18:37

3 Answers 3

4

Use sprintf() instead (it works exactly like printf()). This 'silences' it and gives a return value.

Sign up to request clarification or add additional context in comments.

2 Comments

Hmm, I tried that but when I do sprintf(), I'm only getting one value returned. In this instance, it just returns 24368,
It's not sprintf(), rather, you're not assigning your first sprintf() to a variable and appending the rest to it.
2

printf() outputs the data and returns its length. So that's where the extra value is coming from. You want sprintf() which just returns the value.

Comments

2

Just out of curiosity, why are you using sprintf() at all?

You can assign values to variables directly or with string concatenation.

$data = $row["column"];
$data = $row["column"] . ',';

Read more about Strings in PHP.

In this specific case, I would recommend implode().

$data = array();
while ($row = mysqli_fetch_assoc($result)) {
    $data[] = $row["column"];
}
echo implode(',', $data);

3 Comments

Totally agree with this OP, sprint() is just using more (albeit little) resources.
This is much better, thanks. I am using this solution. Accepting the first response, though, as I think it answers the question more directly.
I'm having the same issue mentioned here. It's adding the array twice even though I'm using mysql_fetch_assoc(). Any idea why? That thread that I linked to suggests that mysql_fetch_assoc shouldn't do that.

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.