0

I am trying to delete from table1 if ID does not exist in table2 in Mysql.

When using sql query in Phpmyadmin

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 !

However when using same sql in PHP as

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 ! What am I doing wrong ?

jahajee.com
  • 3,683
  • 4
  • 21
  • 26

3 Answers3

1

Finally I got it working ! I still fail to understand why the PHP Query fails. Anyways, the query itself was simple which I copied from SO question Delete all rows which has no id existing in another table.

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");

Community
  • 1
  • 1
jahajee.com
  • 3,683
  • 4
  • 21
  • 26
0

Make sure you passed the db name you wanted to use:

$conn = mysqli_connect($servername, $username, $password, $dbname);
Ahsan
  • 3,845
  • 2
  • 36
  • 36
0

Please specify your database with the connection.

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

Here you are no passing the database name in your connection .

Or

in your query itself specify the db name eg :- db.table

Use this way also.

Please try any of this. This will work in your case.

Pranav MS
  • 2,235
  • 2
  • 23
  • 50