Jump to content

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?

Link to comment
https://forums.phpfreaks.com/topic/1055-fetching-information-from-a-database/
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]

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!

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.