Perl Database connect not working in .pm file - mysql

In Perl I have connected the database using DBI concept. The database connection and select table query is working fine in .pl file. But I have run the DBI database connection code in .pm file. It's not working.
Please review code.
Sample.pl (It's working fine)
use DBI;
my $driver = "mysql";
my $database = "marketplace_perl";
my $dsn = "DBI:$driver:database=$database";
my $userid = "root";
my $password = "root";
my $dbh = DBI->connect($dsn, $userid, $password );
my $dbh=connect_db();
my $sth = $dbh->prepare("SELECT UserEmail,UserPassword FROM pj_user where UserEmail=? and UserPassword=?");
$sth->execute($UserEmail,$UserPassword);
Marketplace.pm (It's not working)
package Marketplace;
use DBI;
sub connect_db {
my $driver = "mysql";
my $database = "marketplace_perl";
my $dsn = "DBI:$driver:database=$database";
my $userid = "root";
my $password = "root";
my $dbh = DBI->connect($dsn, $userid, $password );
return $dbh;
}
sub login_marketplace {
my $dbh=connect_db();
my $sth = $dbh->prepare("SELECT UserEmail,UserPassword FROM pj_user where UserEmail=? and UserPassword=?");
$sth->execute($UserEmail,$UserPassword);
my $User_count=$sth->rows;
return $User_count
}
It returns the error message of "Failed to access class (Marketplace): Can\'t locate DBI.pm in #INC (you may need to install the DBI module)"
Please let me know how to fix the DB issue.

Try this below code in marketplace.pm file.
use ENV;
my $PERL5LIB= $ENV{'PERL5LIB'};
package Marketplace;
BEGIN {
push(#INC, $PERL5LIB);
};
use DBI;
sub connect_db {
my $driver = "mysql";
my $database = "marketplace_perl";
my $dsn = "DBI:$driver:database=$database";
my $userid = "root";
my $password = "root";
my $dbh = DBI->connect($dsn, $userid, $password );
return $dbh;
}
sub login_marketplace {
my $dbh=connect_db();
my $sth = $dbh->prepare("SELECT UserEmail,UserPassword FROM pj_user where UserEmail=? and UserPassword=?");
$sth->execute($UserEmail,$UserPassword);
my $User_count=$sth->rows;
return $User_count
}

Related

getting error back from Prepared statement in case sql injection

I'm trying to test my prepared statement that is protecting one field to get the error message in case of SQL injection. I tried until now thousands of attacks, and all of the values I gave were accepted. Am I using a wrong syntax or attack? I can't see where the problem is. Here is my code:
try {
// $host = "localhost";
// $username = "root";
// $password = "root";
// $db_name = "pokemon";
$conn = new PDO('mysql:host='.$host.';dbname='.$db_name.';', $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$meldung="";
$name =$_REQUEST['name'];
$gewicht = $_REQUEST['Gewicht'];
$größe =$_REQUEST['Größe'];
$spezies = $_REQUEST['Spezies'];
$stufe =$_REQUEST['Stufe'];
$atacke =$_REQUEST['Attacke'];
$array = explode(',', $_REQUEST['Attacke']);
$stmt = $conn->prepare("INSERT INTO Pokemon (`Name`,`Gewicht`,`grosse`,`spezies`,`stufe`) VALUES (:Name, '".$gewicht."', '".$größe."', '".$spezies."', '".$stufe."')");
$stmt->bindParam(':Name', $name);
// $stmt->bindParam(':Gewicht', $gewicht);
// $stmt->bindParam(':grosse', $größe);
// $stmt->bindParam(':spezies', $spezies);
// $stmt->bindParam(':stufe', $stufe);
$stmt->execute();
}
catch(PDOException $e)
{
$meldung = "Error: " . $e->getMessage();
echo $meldung;
}
thanks

Can't import JSON string to MySQL

I'm trying to build a leaderboard web app, with data from 15 countries.
The data needs to be uploaded as an .xls file and imported to a MySQL database.
I have build the upload part, which gives me a valid JSON string.
The string is then posted via ajax, to this script as "output":
<?php
if(isset($_POST['output'])) {
$host = "localhost";
$username = "root";
$password = "password";
$dbname = "database";
$con = mysqli_connect($host, $username, $password, $dbname) or die('Error in Connecting: ' . mysqli_error($con));
$st = mysqli_prepare($con, 'INSERT INTO tbl_ttl(country, leads, followup, followuppercent) VALUES (?, ?, ?, ?)');
mysqli_stmt_bind_param($st, 'ssss', $country, $leads, $followup, $followuppercent);
$jsondata = $_POST['output'];
$data = json_decode($jsondata, true);
foreach ($data as $row) {
$country = $row['country'];
$leads = $row['leads'];
$followup = $row['followup'];
$followuppercent = $row['followuppercent'];
mysqli_stmt_execute($st);
}
echo "Success!";
mysqli_close($con);
And this is where im stuck. I do get the "Success!" alert and no errors.
I need to import the records in the string as seperate rows.
And one more thing...
The leaderboard needs to be updated once a month. So is it possible to update the existing rows with new values every time they are uploaded?
Thanks!

Cannot connect to MySQL

I am trying to connect to MySQL server (hosted by godaddy) from php using PDO.
But I get this error :
An error occured : SQLSTATE[HY000] [2002] Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
Note that this is not a database I host.
I was simply given the username and password to construct the database, create the users etc.
function ConnectToDb()
{
try{
$dns = 'mysql:host=1.1.1.1;dbname=dummyDbName';
$username = 'dummyUser';
$password = 'dummyPassword';
$LINK = new PDO($dns, $username, $password);
$LINK->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$LINK->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (!$LINK){
die('Could not connect : ' .mysql_error());
}
else{
return $LINK;
}
} catch (PDOException $ex){
echo "An error occured : " .$ex->getMessage();
}
}
I know that this works on localhost.
I'm using it no problem, but as soon as I try to connect to the live database it fails.
Anyone has an hint?
Thanks
Follow this format:
$user = "username";
$pass = "password";
$host = "localhost";
$db = "yourDbname";
$dns = "mysql:host=" . $host . ";dbname=" . $db;
$dbh = new PDO($dns, $user, $pass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
when you have to do a query (just an example):
$theid = 10;
$statement = $dbh->prepare('SELECT * FROM yourtable WHERE id = ? and name = ?');
$statement->execute(array($theid,'baronth'));
if you want to see if there's some errors while connecting or doing queryes (and you know how try-catch works), surround it with:
try {
all the code that you wan't to check
}
catch (PDOException $e) {
echo $e->getMessage();
}
it will echo the error.

php /mysql coding not working

i seem to be having an error on this coding any help would be appreciated
Parse error: parse error in C:\wamp\www\espn.com\login.php on line 19
<?php
//Database Information
$dbhost = "localhost";
$dbname = "users";
$dbuser = "root";
$dbpass = "*****";
//Connect to database
mysql_connect ( $dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error());
mysql_select_db($dbname) or die(mysql_error());
session_start();
$username = $_POST[‘username’];
$password = md5($_POST[‘password’]);
$query = “select * FROM users where 'username'=$username and 'password'= $password " ;
$result = mysql_query($query);
if (mysql_num_rows($result) != 1) {
$error = “Bad Login”;
include “login.html”;
} else {
$_SESSION[‘username’] = “$username”;
include “memberspage.php”;
}
?>
looks like you have a fancy quote on your query, so it's not a proper string
“ vs "
You are using odd quotes: “ instead of the proper ".
Probably happened while copying code from a web site.
The only valid string-delimiting quotes in PHP (and most other programming languages) are ' and ".
I want to tell you create a separate file/page for database connection. Suppose your connection file name is db_connection.php. Where you want to check only db_connection.php page will include. It saves your codding.
db_connection.php
<?php
//Database Information
$dbhost = "localhost";
$dbname = "users";
$dbuser = "root";
$dbpass = "*****";
//Connect to database
mysql_connect ( $dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error());
mysql_select_db($dbname) or die(mysql_error());
session_start();
?>
Now in your login page you include db_connection.php
loginpage:
<?php
include_once('db_connection.php');
if(isset($_POST['submit']) //submit is form button name
{
$username = $_POST[‘username’];
$password = md5($_POST[‘password’]);
$query = mysql_query(“select * FROM users where 'username'=$username and 'password'= $password ") ;
if (mysql_num_rows($result)>0) {
$_SESSION[‘username’] = “$username”;
header(location:memberspage.php);
} else {
$error = “Bad Login”;
header(location:memberspage.php);
}
?>

DBD::mysql - Problem with dropping a database

Why doesn't the line "$rc = $dbh->func( 'dropdb', $dbname, 'admin' );" remove the database db_test_2?
#!/usr/bin/perl
use warnings;
use strict;
use 5.010;
use DBI;
my $host = 'localhost';
my $user = 'user';
my $password = 'password';
my( $rc, $dbname, #databases );
my $drh = DBI->install_driver( 'mysql' );
$dbname = 'db_test_1';
# use a driver handle (drh)
$rc = $drh->func( 'createdb', $dbname, $host, $user, $password, 'admin' );
say for DBI->data_sources( $driver, { host => $host, user => $user, password => $password });
# DBI:mysql:information_schema
# DBI:mysql:db_test_1
# DBI:mysql:mysql
$rc = $drh->func( 'dropdb', $dbname, $host, $user, $password, 'admin' );
say for DBI->data_sources( $driver, { host => $host, user => $user, password => $password });
# DBI:mysql:information_schema
# DBI:mysql:mysql
my $dbh = DBI->connect( "DBI:mysql:", $user, $password, { RaiseError=>1, AutoCommit=>1 } );
$dbname = 'db_test_2';
# reuse the existing connection of a database handle (dbh)
$rc = $dbh->func( 'createdb', $dbname, 'admin' );
say for DBI->data_sources( $driver, { host => $host, user => $user, password => $password });
# DBI:mysql:information_schema
# DBI:mysql:db_test_2
# DBI:mysql:mysql
$rc = $dbh->func( 'dropdb', $dbname, 'admin' );
say for DBI->data_sources( $driver, { host => $host, user => $user, password => $password });
# DBI:mysql:information_schema
# DBI:mysql:db_test_2
# DBI:mysql:mysql
It is interesting, in the DBI func() it is defined differently, but DBD::MySQL has a convince method to it for what is really an _admin_internal method, which is defined in Mysql.xs and looks to have quite a few calls to do_error(), which leads me to believe that you should check the errors. Try connecting with RaiseError => 1 and see what it says.
To do this, connect with
$dbh = DBI->connect("DBI:mysql:database=$db;host=$host",
$user, $password, {RaiseError => 1});
then use $dbh->func('dropdb' ...), and see what happens.