0

I have a database which contains mobile numbers. How do I write perl script which get all of numbers into array & check new number already exist or not in that array?

Create Table:

CREATE TABLE consumeruser (
  ConsumerId    int(10) NOT NULL AUTO_INCREMENT,
  ConsumerName  varchar(45) DEFAULT NULL,
  ConsumerMobNo varchar(10) DEFAULT NULL,
  PRIMARY KEY (ConsumerId)
) ENGINE=InnoDB AUTO_INCREMENT=4494 DEFAULT CHARSET=latin1

Script :

#!/usr/bin/perl -w
use strict;
use warnings qw(all);

use DBI;
use Getopt::Long;
use Pod::Usage;
use Text::CSV_XS;

my $username = 'root';         # set your MySQL username
my $password = 'xxxx';         # set your MySQL password
my $database = 'app';          # set your MySQL database name
my $server   = 'localhost';    # set your server hostname (probably localhost)

my $dbh = DBI->connect( "DBI:mysql:$database;host=$server", $username, $password )
    || die "Could not connect to database: $DBI::errstr";

my $CustomerMobileNumber = 9999999;
my @MobileNumbers;
my $mobileNumberQuery = "select ConsumerMobNo from consumeruser";
my $sth               = $dbh->prepare($mobileNumberQuery);
$sth->execute();
while ( my @row = $sth->fetchrow_array() ) {
    push @MobileNumbers, $row;

    if (/test for is present/) {
        #9999999 found in array;
    } else {
        #9999999 not found in array;
    }
}
1
  • Instead of getting all the numbers out of the DB and into an array, use a SELECT query to see if the number exists in the DB. Commented Sep 20, 2014 at 10:20

1 Answer 1

2

You can ask the database to search for the number:

my $mobileNumberQuery = "SELECT 1 FROM consumeruser WHERE ConsumerMobNo = ?";
my $sth = $dbh->prepare($mobileNumberQuery);
$sth->execute(9999999);
if ($sth->fetchrow_array) {
    print "Found.\n"
} else {
    print "Not found.\n";
}
Sign up to request clarification or add additional context in comments.

1 Comment

Actually I have CSV file which contain mobile numbers that mobile numbers I wanna check with database,for that I wanna avoid select query for each mobile numbers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.