0

Can someone help me figure out why mysql_query not working?

<?php
$dbhost = "localhost";
$dbusername = "USERNAME";
$dbpassword = "PASSWORD";
$dbname = "DB_NAME";
$connection = mysql_connect($dbhost, $dbusername,$dbpassword) or die('Could not connect');

$db_selected = mysql_select_db($dbname, $connection) or die(mysql_error());
echo " connect... \n";
$result = mysql_query("select * from test",$db_selected);
while($row = mysql_fetch_array($result))
  {
  echo $i++;
  echo "Id : " . $row['Id'] . " Name : " .$row['name'] . " Address : " . $row['address'];
  echo "<br>";
  }
?>

result: connect...

aidinMC
  • 1,415
  • 3
  • 18
  • 35

2 Answers2

1

You must use $connection instead of $db_connected in your mysql_query. See the man page.

And the fact you did not see the error implies that you have error reporting not configured correctly; check your php.ini and this answer.

It wouldn't have worked anyway since you were fetching a numeric array instead of an associative array (use mysql_fetch_assoc() for that) which is needed by $rec['Id'] syntax (as opposed to $rec[3]).

However, if you are just now beginning with PHP and MySQL, do not use mysql_* functions. They are deprecated and will be soon removed, and you'll have wasted time learning something no longer in use. Use PDO instead. A teensy bit more difficult to master, but lightyears better.

Community
  • 1
  • 1
LSerni
  • 55,617
  • 10
  • 65
  • 107
0

If you want to reference the columns by name you must use mysql_fetch_assoc($result) not mysql_fetch_array($result))

But don't use either. use mysqli_* functions instead or better still pdo.

echo $i++ doesn't produce anything as it is undefined

andrew
  • 9,313
  • 7
  • 30
  • 61