php连接mysql指定表名,从MySQL数据库显示PHP中的所有表名

Alright, so I'm fairly new to PHP and SQL/MySQL so any help is appreciated.

I feel like I took the right approach. I searched php.net for "MySQL show all table names", it returned a deprecated method and suggested using a MySQL query on SHOW TABLES [FROM db_name] [LIKE 'pattern'] I'm not sure what "pattern" means but, I searched for "SQL Wildcard" and got the "%" symbol. According to everything I found, this should work and output the table names at the end, but it does not. Any suggestions? Thanks in advance.

if ($_REQUEST["username"]=="coke"&&$_REQUEST["password"]=="pepsi"){

echo 'You have successfully logged in.';

echo '
';

echo 'These are your tables:';

echo '
';

$link = mysql_connect("sql2.njit.edu", "username", "password");

mysql_select_db("db_name") or die(mysql_error());

$result = mysql_query('SHOW TABLES [FROM db_name] [LIKE '%']');

echo $result;

}

else

echo 'You did not provide the proper authentication';

?>

I get no errors. The output is exactly what's echoed, but no table names.

解决方案

The square brackets in your code are used in the mysql documentation to indicate groups of optional parameters. They should not be in the actual query.

The only command you actually need is:

show tables;

If you want tables from a specific database, let's say the database "books", then it would be

show tables from books;

You only need the LIKE part if you want to find tables whose names match a certain pattern. e.g.,

show tables from books like '%book%';

would show you the names of tables that have "book" somewhere in the name.

Furthermore, just running the "show tables" query will not produce any output that you can see. SQL answers the query and then passes it to PHP, but you need to tell PHP to echo it to the page.

Since it sounds like you're very new to SQL, I'd recommend running the mysql client from the command line (or using phpmyadmin, if it's installed on your system). That way you can see the results of various queries without having to go through PHP's functions for sending queries and receiving results.

If you have to use PHP, here's a very simple demonstration. Try this code after connecting to your database:

$result = mysql_query("show tables"); // run the query and assign the result to $result

while($table = mysql_fetch_array($result)) { // go through each row that was returned in $result

echo($table[0] . "
"); // print the table that was returned on that row.

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值