Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error Reporting? Import .sql file from PHP and show errors

Tags:

php

mysql

I am building a way of importing .SQL files into a MySQL database from PHP. This is used for executing batches of queries. The issue I am having is error reporting.

$command = "mysql -u $dbuser --password='$dbpassword' --host='$sqlhost' $dbname < $file";
exec($command, $output);

This is essentially how I am importing my .sql file into my database. The issue is that I have no way of knowing if any errors occurred within the PHP script executing this command. Successful imports are entirely indistinguishable from a failure.

I have tried:

  • Using PHP's sql error reporting functions.
  • Adding the verbose argument to the command and examining the output. It simply returns the contents of the .sql file and that is all.
  • Setting errors to a user variable within the .sql file and querying it from the PHP script.

I hope I am not forced to write the errors into a temporary table. Is there a better way?

UPDATE: If possible, it would be very preferable if I could determine WHAT errors occurred, not simply IF one occurred.

like image 487
Tanoro Avatar asked Jun 12 '26 13:06

Tanoro


1 Answers

$command = "mysql -u $dbuser --password='$dbpassword' --host='$sqlhost' $dbname"
  . " < $file 2>&1";
exec($command, $output);

The error message you're looking for is probably printed to stderr rather than stdout. 2>&1 causes stderr to be included in stdout, and as a result, also included in $output.

Even better, use proc_open instead of exec, which gives you far more control over the process, including separate stdout and stderr pipes.

like image 61
Frank Farmer Avatar answered Jun 14 '26 04:06

Frank Farmer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!