0

Wel all know that we have to use something like mysql_fetch_assoc to a mysql query to get an associative array and then use $row['foo'] and $row['bar'] to get every value.

Is there a way to optimize the query to get a simple string if we want to return a single column from a single row so that the result will be a simple var and not an associative array?

Thanks.

4
  • 1
    For the retrieval of a single value you've described, there seems to be no gain from any optimization, whatever it means. That seems to be the reason why a more straightforward approach is hard to find. Behind the scenes, the same DB mechanisms, drivers, cursors, etc. will be used anyway. Commented Oct 29, 2012 at 22:25
  • 1
    @full.stack.ex its not hard to find. Dont you know about mysql_result function? Commented Oct 29, 2012 at 22:27
  • 1
    But it "retrieves the contents of one cell from a MySQL result set." Same result set, just the access method is different. Without profiling, I'm not sure it would save any cycles or bytes. Not any substantial amount, perhaps. Commented Oct 29, 2012 at 22:31
  • @full.stack.ex if the result contains only single row and single column calling this function will certainly save cpu cycles for array access Commented Oct 29, 2012 at 22:36

3 Answers 3

2

Use mysql_result funciton

$res = mysql_query(..);
$str = mysql_result($res, 0, 0);

Here $str contains the first column of first row.

Also keep in mind that mysql_result will move the internal result pointer to point the next row.

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

Comments

1

Note mysql_ extension is deprecated, you should use mysqli extension or PDO

$res = mysql_query($sql) or die(mysql_error());

list($val) = mysql_fetch_row($res);

Comments

1

The short answer: No.

The long answer: No, but you can optimise the query a little by only returning the row you're looking for (SELECT my_column... then $row['my_column']). Other than that, you've got to lump it if you use MySQL.

Comments

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.