Jump to content


Photo

Fetching information from a database


  • Please log in to reply
2 replies to this topic

#1 Fyorl

Fyorl
  • Members
  • PipPipPip
  • Advanced Member
  • 273 posts
  • LocationUK

Posted 23 September 2003 - 05:22 PM

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?
[table]



Don't worry, the printer fairies will sort it out.

#2 Barand

Barand
  • Moderators
  • Sen . ( ile || sei )
  • 18,025 posts

Posted 23 September 2003 - 07:40 PM

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]
If you are still using mysql_ functions, STOP! Use mysqli_ or PDO. The longer you leave it the more you will have to rewrite.

Donations gratefully received






moon.png

|baaGrid| easy data tables - and more
|baaChart| easy line, column and pie charts

#3 Fyorl

Fyorl
  • Members
  • PipPipPip
  • Advanced Member
  • 273 posts
  • LocationUK

Posted 24 September 2003 - 05:54 AM

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!
[table]



Don't worry, the printer fairies will sort it out.




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users