Jump to content

Archived

This topic is now archived and is closed to further replies.

Fyorl

Fetching information from a database

Recommended Posts

Why is getting the value of one of the fields in a table in a MySQL databse so complicated?

Say I have a table called \'blah\' with two columns in called \'id\' and \'name\' and I use

"INSERT INTO blah (name) VALUES (\'fyorl\')"

 

then I just want to put the value of \'name\' into a variab;e and print it. Why do I have to use while and foreach loops with things in that I don\'t understand to simply get a value?

 

Why can\'t I just do something like:

 

[php:1:d1680a5442]<?

$sql = mysql_query(\"SELECT name FROM blah WHERE id=\'1\'\");

print \"$sql\";

?>[/php:1:d1680a5442]

 

or at the most:

 

[php:1:d1680a5442]<?

$sql = mysql_query(\"SELECT name FROM blah WHERE id=\'1\'\");

$sql_2 = mysql_fetch_array($sql)

print \"$sql_2[0]\";

?>[/php:1:d1680a5442]

 

Is there actually a less complicated way and I\'m too nooby to realise?

Share this post


Link to post
Share on other sites

Your first example will fail because the result is a pointer to the retuned data, no the data.

 

Your second example should work. (You could have tried it instead of posting. Experimentation is a great way to learn.)

 

If a query return multipe rows you normally want to process them all - with a while loop.

 

If it only returns one then you don\'t need the while loop processing.

 

There is also a mysql_result() function

 

[php:1:8d1e372d75]<?php

$sql = mysql_query(\"SELECT name FROM blah WHERE id=\'1\'\");

$name = mysql_result ( $sql, 0, \'name\' ); // 0 = row number

?>[/php:1:8d1e372d75]

Share this post


Link to post
Share on other sites
Your second example should work. (You could have tried it instead of posting. Experimentation is a great way to learn.)

 

I did actually try it (I usually come here as a last resort). But I must have done something wrong. Thanks for the mysql_result() function though!

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.