Variables from a single row.

Hi
I am attempting to request a single row from a table that has 20 fields.
I want to turn each field into it’s own variable (you’ll see oc1, oc2 etc in the code) and then echo the variable just to check it has worked.

When I run the qry below - it picks up the first one correctly but then places the same value in all the other fields. (The $question var should be a long text string but is echoing the first variable instead.
There’s clearly something wrong with the way I have constructed this - but I don’t know at which point it has gone wrong.

Can anyone help?

[php]$result = mysql_query(“SELECT oid,qid,question,posneg,oc1,oc2,oc3,oc4,oc5,oc6,oc7,psc1,psc2,psc3,psc4,psc5,psc6,psc7,psc8,psc9 FROM tblquestions WHERE oid = ‘1’”);
if (!$result) {
echo 'Could not run query: ’ . mysql_error();
exit;
}

$oid=mysql_result($result,“oid”);
$qid=mysql_result($result,“qid”);
$question=mysql_result($result,“question”);
$posneg=mysql_result($result,“posneg”);
$oc1=mysql_result($result,“oc1”);
$oc2=mysql_result($result,“oc2”);
$oc3=mysql_result($result,“oc3”);
$oc4=mysql_result($result,“oc4”);
$oc5=mysql_result($result,“oc5”);
$oc6=mysql_result($result,“oc6”);
$oc7=mysql_result($result,“oc7”);
$psc1=mysql_result($result,“psc1”);
$psc2=mysql_result($result,“psc2”);
$psc3=mysql_result($result,“psc3”);
$psc4=mysql_result($result,“psc4”);
$psc5=mysql_result($result,“psc5”);
$psc6=mysql_result($result,“psc6”);
$psc7=mysql_result($result,“psc7”);
$psc8=mysql_result($result,“psc8”);
$psc9=mysql_result($result,“psc9”);
?>

<?php echo $oid; // Question Number?> <?php echo $qid; // Question Number?> <?php echo $question; // Question Number?> <?php echo $posneg; // Question Number?> <?php echo $oc1; // Question Number?> <?php echo $oc2; // Question Number?> <?php echo $oc3; // Question Number?> <?php echo $oc4; // Question Number?> <?php echo $oc5; // Question Number?> <?php echo $oc6; // Question Number?> <?php echo $oc7; // Question Number?> <?php echo $psc1; // Question Number?> <?php echo $psc2; // Question Number?> <?php echo $psc3; // Question Number?> <?php echo $psc4; // Question Number?> <?php echo $psc5; // Question Number?> <?php echo $psc6; // Question Number?> <?php echo $psc7; // Question Number?> <?php echo $psc8; // Question Number?> <?php echo $psc9; // Question Number?>[/php]

It is better to use one of these functions:
mysql_fetch_row()
mysql_fetch_array()

In your example it will look like this:
[php]<?php
$fields=mysql_fetch_array($result);
$oid=$fields[“oid”];
$qid=$fields[“qid”];
$question=$fields[“question”];
// … etc.
?>[/php]

For more information and examples you can go here: http://www.php.net/manual/en/function.mysql-fetch-array.php

Sponsor our Newsletter | Privacy Policy | Terms of Service