开发者

problem with php and mysql

I am tr开发者_开发问答ying to connect to a db that is not on the same server as my script.

It doesn't work, why?

mysql_connect('twstg.com', 'myUser', 'myPass');

$data = mysql_query("SELECT * FROM Websites ORDER BY RAND()
                     LIMIT 1");
while($info = mysql_fetch_array( $data)) {
  $url = $info['url'];
  echo $url;
}


(This was too big for a comment, will update answer as appropriate when more data is provided)

What's the error you're getting, you can't expect us to magically know that. There could be many things that go wrong, whether it's in the connection, the query, or even the loop (if there are no results).

You can check what the error is by doing something like this:

mysql_connect(..) or die(mysql_error());
$data = mysql_query(); die(mysql_error());

If there are no errors with that, you're still missing is a call to mysql_select_db(). This wouldn't be required if, for example, you was doing a SELECT * FROM DATABASE.Websites, but you're not :)


You have to atleast select a valid database to query.

Put this function call under your connection function.

mysql_select_db('dbname');

http://php.net/manual/en/function.mysql-select-db.php


Does the mysqluser account have the correct access on the server?

What I mean is, do you have 'user'@'your ip here' OR 'user'@'%' as the user account and not just 'user'@'localhost'


you should check connectivity first

mysql_connect('twstg.com', 'myUser', 'myPass') or die(mysql_error);

by this you can check the connectivity other that this every thing is ok to me..


Probably mysql_connect() failed. But it's also possible that mysql_query() failed because there's no mysql_select_db() inthe script. Your local server might be configured to select a default database while the other server is not. We'll never know... unless you put some error handling into your script

Any of the mysql_...() functions can fail. If any of them returns false something went wrong and you have to handle this error condition.

<?php
define('DEBUG', 1);
function mySimpleErrorHandler($public, $private) {
    echo $public;
    if (defined('DEBUG') && DEBUG ) {
        echo " \n", $private;
    }   
    die;
}

$mysql = mysql_connect('twstg.com', 'myUser', 'myPass')
    or mySimpleErrorHandler('database connection failed', mysql_error());
mysql_select_db('databasename', $mysql)
    or mySimpleErrorHandler('database connection failed', mysql_error($mysql));

$data = mysql_query("SELECT * FROM Websites ORDER BY RAND() LIMIT 1")
    or mySimpleErrorHandler('query failed', mysql_error($mysql));

echo "results: \n";
while( false!==($info=mysql_fetch_array($data)) ) {
    echo $info['url'], "\n";
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜