简体   繁体   English

使用PHP时出现Mysql“未选择数据库”错误

[英]Mysql “No Database selected” error when using PHP

I am trying to delete from table1 if ID does not exist in table2 in Mysql. 如果ID在Mysql的table2中不存在,我试图从table1中删除。

When using sql query in Phpmyadmin 在Phpmyadmin中使用SQL查询时

DELETE t1 FROM db.table1 t1 LEFT JOIN db.table2 t2 ON t1.id = t2.id WHERE t2.id IS NULL

it works perfectly deleting from table1 rows not found in table2 ! 它可以完美地从table2中找不到的table1行中删除!

However when using same sql in PHP as 但是, 在PHP中使用相同的SQL作为

mysqli_query($connection,"DELETE t1 FROM db.table1 t1 LEFT JOIN db.table2 t2 ON t1.id = t2.id WHERE t2.id IS NULL") or die(mysqli_error($connection));

it throws error No database selected . 抛出错误未选择数据库 I have verified and my connections are defined properly with host,username and password. 我已经验证,并且使用主机,用户名和密码正确定义了我的连接。

$connection = @mysqli_connect($host,$username,$password);

I do not think that $connection is problem as there are other queries before/after it which all work perfectly ! 我不认为$ connection是问题,因为之前/之后还有其他查询都可以正常工作! What am I doing wrong ? 我究竟做错了什么 ?

Finally I got it working ! 终于我开始工作了! I still fail to understand why the PHP Query fails. 我仍然不明白为什么PHP查询失败。 Anyways, the query itself was simple which I copied from SO question Delete all rows which has no id existing in another table . 无论如何,查询本身很简单,我从SO问题中复制了它。 删除另一个表中不存在id的所有行

What i could make out is that using alias was problematic and finally I used full table name with DB and it worked perfectly. 我能弄清楚的是,使用别名是有问题的,最后我在数据库中使用了完整的表名,并且效果很好。 I am pretty sure that alias can be used, its just that I am not expert in them ! 我很确定可以使用别名,只是我不是他们的专家!

mysqli_query($connection,"DELETE db.table1 FROM db.table1 LEFT JOIN db.table2 ON table1.id = table2.id WHERE table2.id IS NULL");

确保您传递了要使用的数据库名称:

$conn = mysqli_connect($servername, $username, $password, $dbname);

Please specify your database with the connection. 请指定您的数据库与连接。

$conn = mysqli_connect($servername, $username, $password, $dbname); $ conn = mysqli_connect($服务器名,$用户名,$密码,$ dbname);

Here you are no passing the database name in your connection . 在这里,您无需在连接中传递数据库名称。

Or 要么

in your query itself specify the db name eg :- db.table 在查询本身中指定数据库名称,例如:-db.table

Use this way also. 也使用这种方式。

Please try any of this. 请尝试任何一种方法。 This will work in your case. 这将适合您的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM