Jump to content


Photo

Data variables shortcut


  • Please log in to reply
1 reply to this topic

#1 master82

master82
  • Members
  • PipPipPip
  • Advanced Member
  • 182 posts

Posted 05 September 2006 - 10:54 AM

Here is a sample of code I use to get data from my users table, as you can see its very long and in some other tables there are alot more fields - so it very time consuming


include("connectionfile.php");
$values = "SELECT field, field1, field2, field3, field4, field5, field6, field7, field8, field9 FROM users WHERE field1 = '$anothervalue';
$output = mysql_query($values,$connection) or die("Unable to retrieve user data");
while ($newArray = mysql_fetch_array($output)){
$field1= $newArray[''field1];
$field2= $newArray['field2'];
$field3= $newArray['field3'];
$field4= $newArray['field4'];
$field5= $newArray['lfield5'];
$field6= $newArray['field6'];
$field7= $newArray['field7'];
$field8= $newArray['field8'];
$field9= $newArray['field9'];
}


when I require one of these fields I simply


echo"$field1";


It works fine but I've seen it done a shorter way, but couldnt get it to work:


$values=mysql_query("SELECT * FROM users WHERE field1 = $anothervalue");
while($us=mysql_fetch_array($values)) {
}


I thought I could then use the following to call the data:


echo"$us[field1]";


...but the values came out blank :-[

Any idea where im going wrong or a different way to do this?

#2 shocker-z

shocker-z
  • Members
  • PipPipPip
  • Advanced Member
  • 864 posts
  • LocationNottingham

Posted 05 September 2006 - 12:08 PM

NOT tested but this should work or a less i have made a stupid litle mistake somewhere...
<?php $values=mysql_query("SELECT * FROM users WHERE field1 = $anothervalue");
$us=mysql_fetch_array($values);
$i=1;
$ii='field1';
while ($us[$ii] !== '') {
 $i++;
 $$ii=$us[$ii];
 $ii='field'.$i;
}
?>


notice how i didnt use a while for the data being pulled out.. this is because you only have 1 line of data in your database else if you have more then you will have to put everything into an array like below..

<?php $values=mysql_query("SELECT * FROM users WHERE field1 = $anothervalue");
while ($us=mysql_fetch_array($values)) {
 $i=1;
 $ii='field1';
 while ($us[$ii] !== '') {
  $i++;
  $$ii[]=$us[$ii];
  $ii='field'.$i;
 }
}
?>


then you can call each filed1,2,3,4.... by using $file1[0] which will pull out the data of field 1 row 1...


Regards
Liam
www: www.ukchat.ws | irc: irc.ukchat.ws chan: #blufudge




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users