Return Only One Variable from MySQL Query


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


$name = mysql_get_var("SELECT name from people where email = ''");

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


  1. User Avatar
    Permalink to comment#

    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

    • User Avatar
      Permalink to comment#

      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. User Avatar
    David Moreen
    Permalink to comment#

    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. User Avatar
    Kevin Meek
    Permalink to comment#

    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 = ‘’ 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. User Avatar
    Permalink to comment#

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

  5. User Avatar
    Permalink to comment#

    THANK YOU SO VERY MUCH!!! This was very, extremely useful! thank you thank you.

Leave a Comment

Posting Code!

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.