Log in

View Full Version : Retrieving a value from MySQL as a string (efforts at simplification).



james438
01-23-2008, 03:29 PM
Hi, I was just wondering if there was a simpler way to write the following code. This is assuming that I know what row it is located in and what field and that I want just the one value from the table.


$query = "SELECT field FROM tablename where ID=1";
$result = mysql_query($query)
or die ("Couldn't execute query.");
$value = mysql_fetch_array($result,MYSQL_ASSOC);
$value= $value['field'];echo "pop $value pop";

Thanks for reading :)

boogyman
01-23-2008, 06:33 PM
not so much as simpler, but you could re-write it to be something like


$q = "SELECT field FROM table WHERE id='#'";
if( $rs=mysql_fetch_array(mysql_query($q), MYSQL_ASSOC) )
{
echo "pop {$rs['field']} pop";
}
else {
echo "Couldn't execute query";
}

codeexploiter
01-24-2008, 03:10 AM
I feel that it is better to have die statement while executing the query.

james438
01-24-2008, 09:42 AM
hmm, thanks for the advice, but it looks like I am using the right code for what I want to do and am not being needlessly complicated. There is some minor rearranging of code that can be done to make this a little more efficient, but I find it easier to read this way.

I have to agree with codeexploiter here. The die statement has been a valuable tool for me when debugging a script. Mostly I was concerned that I was using around 10 commands when with other built in php functions available I could say the same thing in just 2 or three commands or maybe I was being too server heavy in the layout of it.