Jump to content

[SOLVED] how do i take only one result from DB


snk

Recommended Posts

thx for replying,

 

I use a query that returns just one result. lets say

 

$nameQ = "select name from people where key= '$value'";

 

key is unique.. so I know that only one result will come back

 

The question is how do I assign the name to a variable? I used to use mysql_fetch_array($nameQ);

and then do/while.

 

Is there any way to place it a variable, but not array?

 

i see your point . well i don't know!

 

just letting you know mysql_fetch_array do return an array that each value is repeated 2 times !

for example the mysql_fetch_array for you sql line will be :

 

array([0] => "the_value_in_name_field"  ,  [name] => "the_value_in_name_field");

 

however it is not important, you don't have to use do while ...

 

do this :

 

<?php
$nameQ = "select name from people where key= '$value'";
$result = mysql_query($nameQ);
$name_array = mysql_fetch_array($result); // now you name is into $name_array[name] and  $name_array[0]

$name = $name_array[name];

?>

 

as you see no do while .

 

you can use mysql_fetch_assoc too :

http://ir2.php.net/manual/en/function.mysql-fetch-assoc.php

 

i guess it won't return a repeated values . (not sure)

 

 

 

 

 

Add a "LIMIT 1" to the end of your query.

 

Anyhow,

 

$query = "SELECT * FROM people WHERE key='$value' LIMIT 1"; # Define query
$result = mysql_query($query); # Use query to return a result
$row = mysql_fetch_array($result); # Return a $row array, with keys matching the table's column names 
$name = $row['name']; # Set the value of $name to the value of name column in the database (you could use $row['name'] itself though)
$other = $row['other']; # Set the value of $other to the value of other column in the database ^
$more = $row['more']; # Set the value of $more to the value of more column in the database ^

 

Simple, no? :P

$sql="SELECT `column` FROM `table` WHERE `column`='value'" or die(mysql_error());

$query=mysql_query($sql);

$results=mysql_fetch_assoc($query);

 

Just use this.

Your "or die" is in the wrong bit.

 

You're questioning a string declaration. You want to move it to the mysql_query($sql) line.

Archived

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

×
×
  • 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.