0

So I want to be able to get information from MySQL. In my PHP code, I call the query and echo the info in this sort of fashion:

$sql = "SELECT * FROM `person`";
$rs = $COMMON->executeQuery($sql, $_SERVER["SCRIPT_NAME"]);

while($row = mysql_fetch_row($rs)){
    echo ("Name: ".$row['name']."<br />";
    echo ("Gender: ".$row['gender']."<br />";
    echo ("Age: ".$row['age']."<br />";
};

Though, the actual value of $row['name'] and the rest is completely blank. Not even a single space. Though, when I call it by the actual column index like so $row[1], it gives me the right value.

So, for example, lets say this had three person in the table. The end result page would look like this:

Name: 
Gender: 
Age: 
Name: 
Gender: 
Age:
Name: 
Gender: 
Age:

Is something I'm doing wrong? Why is it giving me this empty string instead of the query value?

MySQL database is saved on MyPHPAdmin. I don't know if it makes a difference or not. If there is anymore information missing that you deem necessary, please let me know. Thanks!

SomeShinyObject
  • 7,581
  • 6
  • 39
  • 59
Rob Avery IV
  • 3,562
  • 10
  • 48
  • 72

2 Answers2

7

You need to be using mysql_fetch_assoc() instead of mysql_fetch_row(). mysql_fetch_assoc() returns an associative array of your results. mysql_fetch_row() returns a numerical array.

Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

Community
  • 1
  • 1
John Conde
  • 217,595
  • 99
  • 455
  • 496
1

Change your code to:-

$sql = "SELECT * FROM `person`";
$rs = $COMMON->executeQuery($sql, $_SERVER["SCRIPT_NAME"]);

while($row = mysql_fetch_assoc($rs)){
echo ("Name: ".$row['name']."<br />";
echo ("Gender: ".$row['gender']."<br />";
echo ("Age: ".$row['age']."<br />";
};

mysql_fetch_assoc(), as the name implies it will return an associative array (with the column names as keys and the values as the row values).

Vivek Sadh
  • 4,230
  • 3
  • 32
  • 49