Code Snippet

Home » Code Snippets » PHP » Return Only One Variable from MySQL Query

Return Only One Variable from MySQL Query

Function

function mysql_get_var($query,$y=0){
       $res = mysql_query($query);
       $row = mysql_fetch_array($res);
       mysql_free_result($res);
       $rec = $row[$y];
       return $rec;
}

Usage

$name = mysql_get_var("SELECT name from people where email = 'roger@freekrai.net'");

Will return the name field, so what gets returned will be "Roger" (if that was my name in the database).

Reference URL

Subscribe to The Thread

  1. does this work with mulitple rows like if i wanted to hole name table could i use mysql_fectch_array with it?

    check out my site

    • No this function only works for returning one row.

      About the function, if the $y will only allow an integer to be given to specify which field to select then it would be better to use mysql_fetch_row instead of mysql_fetch_array.
      Also you can just do a:
      return $row[$y];
      instead of creating a new variable.

  2. I want to thank you from the bottom of my heart. I spent the last 4 hours trying to figure out what I was doing wrong, come to CSS-Tricks, found this, my problems are fixed. Thank you.

  3. Kevin Meek

    Even easier is to use the LIMIT keyword for MySQL so using the above example your query string would be…

    SELECT name FROM people WHERE email = ‘roger@freekrai.net’ LIMIT 1

    Which would give you the first record MySQL comes across. This can be changed using different orders such as
    ORDER BY id or
    ORDER BY date etc.
    MySQL is optimized to get the data faster this way than PHP. Your way MySQL would spend a lot of time maybe getting 10,00 records packaged and delivered whereas when using LIMIT it knows to only package 1 record fast.

  4. Mark

    Thank you. I’ve been digging for the longest time to find exactly this. The best thing of all is that it actually works!

Speak, my friend

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
~ The Management ~