0

I am querying a mysql database with php but cannot get it to work on my iMac. In particular, php is unable to connect to the mysql DB. It connects to mysql and selects the DB but then fails. See code below:

if (!mysql_connect($db_host, $db_user, $db_pwd)){
    die("I cannot connect to database");
}
if (!mysql_select_db($database)){
    die("I cannot select database");
}

$sql = "SELECT FROM ${table} ORDER BY $sql_orderBy";
$result = mysql_query($sql);
if (!$result) {
    die("I cannot execute query to show fields from Table: {$table}. Query failed.");
}

For reference, I installed apache/mysql/php with macports. The same php code works on my laptop (same installations), and the query works when I invoke it from within mysql on both computers. All variables are declared. Something with the system config is my best guess, but I even went through a uninstall/install.

Any help would be appreciated!

3
  • 2
    what is ${table} ? This should be {$table} or better still, ".$table." Commented Mar 12, 2015 at 23:06
  • 1
    also DO NOT USE MySQL as it is deprecated . Instead spend an afternoon reading up on MySQLi or PDO, they are more secure and currently supported by PHP Commented Mar 12, 2015 at 23:07
  • Remove { and } from ${table}, which is a variable variable of a Constant. Commented Mar 12, 2015 at 23:10

1 Answer 1

2

Your issue is ${table} . This should be {$table} or better still, ".$table."

You also need to say what you are SELECTING: So:

$sql = "SELECT * FROM ".$table." ORDER BY ".$sql_orderBy;

You can discover issues by using Mysql_error() at the end of the query, for example:

mysql_query($sqlString) or die("line: ".__LINE__.":".mysql_error()); 

this will output a clear error message regarding your SQL statement. This is not for production and public situations but for development.

Also:

MySQL is deprecated and is no longer supported by PHP or the wider community, it is VERY strongly recommended you take up MySQLi or PDO and use these methods as they are much stronger, less flawed and more efficient delivery of results. They will also be supported in future updates and developments whereas MySQL will not.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.