0

I have been reading many different pieces of code an I am confused as to why the $echo row[0] at the bottom of my code here does not return anything.

$dbhost = 'localhost';

$uname = $_POST["uname"];

//***create connection object
$connection = mysql_connect($dbhost, "bc572fsdf", "abcdfsds") or die(mysql_error());

$dbname = "bc57db";
mysql_select_db($dbname) or die(mysql_error());

//***select a random security question

//*** need this to import session variables
session_start();

echo ($_SESSION["ValidUser"] . "\n");

$rq       = array('q1', 'q2', 'q3');
$rand_key = array_rand($rq, 1);
echo $rq[$rand_key];

$question = $rq[$rand_key];

$qtoanswer = mysql_query("select '$question' from users where uname = '$uname'");
if (!$qtoanswer) {
    echo "Could not run query:" . mysql_error();
    exit;
}

echo $qtoanswer;
$row = mysql_fetch_row($qtoanswer);

echo $row[0];

?>
Dave Chen
  • 10,887
  • 8
  • 39
  • 67
Brian
  • 65
  • 1
  • 1
  • 8
  • do a print_r( $row ); and see what it contains – Ole Haugset Oct 08 '14 at 11:52
  • 1
    You should stop using mysql_* functions. They are depreciated. Instead, use mysqli_* functions. :). Try var_dump($row) and see what outputs ? – Yash Sodha Oct 08 '14 at 11:52
  • a simple debugging session will pinpoint the problematic part. – Karoly Horvath Oct 08 '14 at 11:52
  • 1
    **Danger**: You are using [an **obsolete** database API](http://stackoverflow.com/q/12859942/19068) and should use a [modern replacement](http://php.net/manual/en/mysqlinfo.api.choosing.php). You are also **vulnerable to [SQL injection attacks](http://bobby-tables.com/)** that a modern API would make it easier to [defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) yourself from. – Quentin Oct 08 '14 at 11:56

2 Answers2

1

The fault is in this line:

$qtoanswer = mysql_query("select '$question' from users where uname = '$uname'");

You should be using grave marks for the column name, such as:

$qtoanswer = mysql_query("select `$question` from users where uname = '$uname'");
                                 ^         ^

Also, you should be using MySQLi/PDO, so you can prepare this, or at the very least, escape $uname.

Dave Chen
  • 10,887
  • 8
  • 39
  • 67
  • 1
    if that were the only problem, he would see something.. "does not return anything" - not that I *trust* OPs in general... – Karoly Horvath Oct 08 '14 at 11:59
  • @KarolyHorvath Most likely the OP has error messages off, so `$row[0]` returned a warning, (index doesn't exist or something). – Dave Chen Oct 08 '14 at 12:04
0

Because you cannot echo a array....try var_dump or print_r, or use a loop:

foreach($row[] as $result) {
    echo $row[], '<br>';
}