The Lodge is members-only design/dev videos and Office Hours.

Next Office Hours Session: "SVG" Oct 14 - 6:30 PM Eastern
Get a free trial // Grow your CSS skills // Land your dream job

Return Only One Variable from MySQL Query

Last updated on:


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).

Reference URL


  1. Kenrick
    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

    • David
      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. 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. 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. Mark
    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. Dale
    Permalink to comment#

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

Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in in triple backtick fences like this:

  function example() {
    element.innerHTML = "<div>code</div>";

There's a whole bunch of content on CSS-Tricks.

Search for Stuff   •   Browse the Archives

Get the Newsletter ... or get the RSS feed