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 = '[email protected]'");
Will return the name field, so what gets returned will be “Roger” (if that was my name in the database).
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.
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.
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 = ‘[email protected]’ 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.
Thank you. I’ve been digging for the longest time to find exactly this. The best thing of all is that it actually works!
THANK YOU SO VERY MUCH!!! This was very, extremely useful! thank you thank you.