Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to make a MySQL connection through Perl when called in a PHP script

Tags:

php

mysql

perl

I'm creating a connection to a MySQL database within a Perl script, called by a PHP script. Here are the 2 scripts:

Perl:

#!/usr/bin/perl
# script name = MyCode.pl
use DBI;
my $data_source = q/dbi:mysql:name:localhost/;
my $user = q/myname/;
my $pwd = q/pword/;

print "before...\n";
# Connect!
$dbhandle= DBI->connect($data_source,$user,$pwd) or die "can't connect
       $data_source: $DBI::errstr \n";
print "...after \n";

PHP:

<?php
 // script name = Test.php
 $myResult=shell_exec("perl /path/MyCode.pl");
 echo $myResult;
?>

When executed on the command line, Test.php prints "before..." and "...after" and the DB connection is indeed established within the Perl code. However, when Test.php is executed from my (Chrome) browser, all that prints is "before..." and no connection is made. And no error message is displayed.

Why is there success on the command line but not from a web server?

like image 249
MikeP Avatar asked Apr 14 '15 17:04

MikeP


People also ask

What is Perl DBI in MySQL?

Perl/DBI modules. DBI is a database-independent interface for the Perl programming language. DBD::mysql is the driver for connecting to MySQL database servers with DBI. DBI is the basic abstraction layer for working with databases in Perl.

How do you check is MySQL connected or not?

Try this: <? php $servername = "localhost"; $database = "database"; $username = "user"; $password = "password"; // Create connection $conn = new mysqli($servername, $username, $password, $database); // Check connection if ($conn->connect_error) { die("Connection failed: " .


2 Answers

Yes, PHP shell_exec() function doesn't capture STDERR.

To debug your code, you can add a 2>&1 at the end of system command to redirect STDERR to STDOUT:

$myResult = shell_exec("perl /path/script.pl 2>&1");

Also, you can setup the DBI module to die if some error occurs at runtime:

$dbh = DBI->connect($data_source,$user, $pwd, { RaiseError => 1, PrintError => 0}) or die $DBI::errstr;
like image 68
fvox Avatar answered Oct 16 '22 10:10

fvox


Problem fixed...I needed correct path specification: this is done (on godaddy) by using:

use cPanelUserConfig;

in the Perl script to access the DBD::mysql module that I installed.

like image 1
MikeP Avatar answered Oct 16 '22 08:10

MikeP