I'm baffled, when I use the terminal (mysql) and insert into username,account_password columns, user_id AUTO_INCREMENTS just as it should.
my table:
CREATE TABLE users (
user_id int NOT NULL AUTO_INCREMENT,
user_type VARCHAR(20) NULL,
creation_date TIMESTAMP NOT NULL,
username VARCHAR(100) NOT NULL,
account_password VARCHAR(255) NOT NULL,
PRIMARY KEY (user_id)
);
yet when I use this script:
use strict;
use warnings FATAL => 'all';# good for debugging, FATAL kills program so warnings are more identifiable
use CGI qw/:standard/;
use CGI::Carp qw(fatalsToBrowser); # good for debugging, sends info to browser
use DBI;
use DBD::mysql;
use Digest::SHA qw(sha256);
print header, start_html;
my $fName = param('firstName');
my $lName = param('lastName');
my $compName = param('compName');
my $email = param('email');
my $pswrd = param('password');
my $cnfPswrd = param('confPassword');
my $encpswrd = "";
#check passwords match, if not display error, and exit script
if ($pswrd eq $cnfPswrd) {
$encpswrd = sha256($pswrd);
} else {
print "Passwords did not match! refresh form!";
exit;
}
#database credentials, to be changed accordingly
my $database = "intsystest";
my $host = "localhost";
my $user = "root";
my $pw = "password";
my $dsn = "dbi:mysql:$database:localhost:3306";
#connect to database
my $dbh = DBI->connect($dsn, $user, $pw,
{ RaiseError => 1 }) or die "unable to connect:$DBI::errstr\n"; # <- this line good for debugging
#create, prepare, execute query, disconnect from DB
my $personsQuery = "INSERT INTO persons (first_name, last_name) VALUES (?,?)";
my $compQuery = "INSERT INTO company (company_name) VALUES (?)";
my $usersQuery = "INSERT INTO users (username, account_password) VALUES (?,?)";
my $sth = $dbh->prepare($personsQuery);
$sth->execute($fName, $lName);
$sth = $dbh->prepare($compQuery);
$sth->execute($compName);
$sth = $dbh->prepare($usersQuery);
$sth->execute($email, $encpswrd);
$dbh -> disconnect;
# additional processing as needed ...
print end_html;
I get this error:
DBD::mysql::st execute failed: Field 'user_id' doesn't have a default value at /usr/lib/cgi-bin/compSignUpDBCGI.pl line 44.
I'm assuming it's likely something wrong with the handler. What am I missing??
If your persons table has a foreign key to the users table then you need insert the users record first, then get the id of the new users record and add that to the SQL to insert the persons record.
Something like this:
my $usersQuery = "INSERT INTO users (username, account_password) VALUES (?,?)";
$sth = $dbh->prepare($usersQuery);
$sth->execute($email, $encpswrd);
$sth = $dbh->prepare('SELECT user_id FROM users WHERE username = ?');
$sth->execute($email);
my $user_id = $sth->fetch->[0];
my $personsQuery = "INSERT INTO persons (user_id ,first_name, last_name) VALUES (?,?,?)";
$sth = $dbh->prepare($personsQuery);
$sth->execute($user_id, $fName, $lName);
This is an area where DBIx::Class will definitely make your life easier.
Related
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;
}
}
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";
}
I am new in perl programming language. Can you please guide how to write csv upload into mysql database.
I have following table & csv file format
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
Csv file example:
4495,Sanchita Mehra,999999999
4496,Rupesh Shewalkar,88888888
4497,Aditya Mishra,111111111
Csv upload should be on basis of mobile number, suppose if table already contain mobile 111111111 Then that row should be skip. Means all mobile numbers should be check with existing data, if it is already in database that row should not be insert in database & rest of inserted into database.
You can check for the count of the row to see if the data is already present and then continue to next statement if its present. The implementation is for SQLite and you can change it to MySQL.
#!/usr/bin/perl
use Modern::Perl '2012';
use DBD::SQLite;
use warnings;
my $dbh = DBI->connect("dbi:SQLite:dbname=Consumer");
while(<DATA>){
chomp;
my ($id, $name, $MobNo) = split /,/;
my $query = "select count(*) from consumeruser where ConsumerMobNo = ?";
my $sth = $dbh->prepare($query);
$sth->execute($MobNo);
my $row = $sth->fetch();
next if(#$row > 0);
my $insertStatement = "insert into consumeruser values(?,'?',?)";
$sth = $dbh->prepare($insertStatement);
$sth->execute($id,$name,$MobNo);
}
__DATA__
4495,Sanchita Mehra,999999999
4496,Rupesh Shewalkar,88888888
4497,Aditya Mishra,111111111
4498,Aditya,111111111
Edit:
For fetching all the mobile numbers in the array. You can do like this.
my #MobileNumbers;
my $mobileNumberQuery = "select ConsumerMobNo from consumeruser";
my $sth = $dbh->prepare($mobileNumberQuery);
$sth->execute();
while(my $row = $sth->fetch()){
push #MobileNumbers, #$row;
}
Please refer to perldoc DBI for various ways of accessing the results.
Afternoon everyone,
I'm currently trying to insert or update form field values via params into a mysql after some simple validation. The form submits, but does not actually execute any of the operations and does not raise a syntax or database connection error. I know my connection string works because I fetched values from it to compare to in the code prior to the nested evaluation blocks shown below. The foreach loops were inserted as an alternate means of validating that the values have indeed been altered in the table. Your help is greatly appreciated, as always:
my $dbusr = param("dbuser");
my $dbpw = param("dbpass");
my $dbmail = param("dbemail");
my $dbtel = param("dbphone");
my $postflag = param("Submit");
if ($dbusr ne "") {
$sth = $dbh->prepare("SELECT * FROM USER WHERE username LIKE ?");
$sth->execute('$dbusr');
warn( $DBI::errstr ) if ( $DBI::err );
my #results = $sth->fetchall_arrayref();
foreach(#results){
if ($dbusr eq $_){
$loopval = 1;
}
}
unless($loopval){
$sth = $dbh->prepare("INSERT INTO USER
(username, password, phone, email)
values
(?,?,?,?)");
$sth->execute($dbusr, $dbpw, $dbtel, $dbmail);
warn( $DBI::errstr ) if ( $DBI::err );
$sth = $dbh->prepare("SELECT * FROM USER WHERE username LIKE ?");
$sth->execute('$dbusr');
#results = $sth->fetchall_arrayref();
foreach(#results){
if ($dbusr eq $_){
$successflag = 1;
}
}
}
else{
$sth = $dbh->prepare("UPDATE USER
SET (password = ?, phone = ?, email = ?)
WHERE username = ?");
$sth->execute($dbpw, $dbtel, $dbmail, $dbusr);
warn( $DBI::errstr ) if ( $DBI::err );
$sth = $dbh->prepare("SELECT * FROM USER WHERE username LIKE ?");
$sth->execute('$dbusr');
#results = $sth->fetchall_arrayref();
foreach(#results){
if ($dbusr eq $_){
$successflag = 1;
}
}
}
}
Basic Perl: '-quoted strings do NOT interpolate variables:
$sth->execute('$dbusr');
^-- ^---
You're literally passing $, d, b, etc... to your query as the placeholder value.
Try
$sth->execute($dbusr); // note the lack of ' quotes
instead.
You are searching for entire rows with the SELECT * FROM USER WHERE username LIKE ? statement, and are then fetching all the rows in one go with
my #results = $sth->fetchall_arrayref();
That method "returns a reference to an array that contains one reference per row.", but you are treating the returned value as an list of usernames:
foreach(#results){
if ($dbusr eq $_){
$loopval = 1;
}
}
To make this work you should just fetch the username column, and treat the returned rows as references of references. And as you look for exact matches in the database replace LIKE with =:
$sth = $dbh->prepare("SELECT username FROM USER WHERE username = ?");
$sth->execute($dbusr); # no quoting
die( $DBI::errstr ) if ( $DBI::err ); # what else to do if the execute fails?
my $results = $sth->fetchall_arrayref(); # an arrayref is returned
foreach(#$results){ # de-reference the array
if ($dbusr eq $_->[0]){ # each row is an arrayref, look in first element
$loopval = 1;
}
}
(Of course the same applies to the second search.)
My update query is
"UPDATE registration SET `dob` = '".$theDate."' , pwd='".$_REQUEST['n_password']."', name='".$_REQUEST['n_name']."' where id='".$_SESSION['id']."' "
Problem is that it is not necessary that user update all fields so if it happens there are null values coming from form and it will replace earlier value in database.
I can update it one by one after checking if field value is not null but if there is any other way r tutorial please help me
I can update it one by one after checking if field value is not null
but if there is any other way r tutorial please help me
Don't issue an UPDATE query after you check each value, instead add that column to the query you're building, then execute just one UPDATE with only the columns that had values.
$dbh = new PDO('mysql:host=localhost;dbname=whatever', 'user', 'password');
$params = array();
$sql = "UPDATE REGISTRATION SET `dob` = ?";
$params[] = $theDate;
if (!empty($_REQUEST['n_password'])) {
$sql .= ", `pwd` = ?";
$params[] = $_REQUEST['n_password'];
}
if (!empty($_REQUEST['n_name'])) {
$sql .= ", `name` = ?";
$params[] = $_REQUEST['n_name'];
}
$sql .= " WHERE `id` = ?";
$params[] = $_SESSION['id'];
$stmt = $dbh->prepare($sql);
$stmt->execute($params);
Please I am having problem tracking down the problem with this code I have been trying for hours . it gives me the error DBD::mysql::st fetchrow_hashref failed: fetch() without execute() at line 15
sub Split_Into_Words
{
#### Connection parameters ############################
my $dsn = "dbi:mysql:malware:localhost:3306";
my $user = 'root';
my $passwd = 'sxxxs';
########################################################
my $domain ;
my $countDir = 0 ;
my $file = shift ;
my $labelID = (split(/[.]/ , $file))[1] ; ### Split and get the middle value since format is temporay.
#### Query String ############################################################################
my $InsertIntoHostTable_QS = "INSERT INTO TB_host(HostName , UrlID , ExtID) Values (? , ? , ? ) ; ";
my $InsertIntoDomainTable_QS = "INSERT IGNORE INTO TB_Domain(Domain) values (?) ;" ;
my $InsertIntoArgVal_QS = "INSERT INTO TB_Arg_Value(Arg, URL_ID) VALUES (? , ? ) ; " ;
my $InsertIntoDirectory_QS = "INSERT INTO TB_Directory(DIRNAME , DEPTH , URLID) VALUES (? , ? , ? )" ;
my $InsertIntoExtension_QS = "INSERT IGNORE INTO TB_Extension (Extension) values ( ? ) ; ";
my $InsertIntoExtensionNULL_QS = "INSERT IGNORE INTO TB_Extension (ID , Extension) values (? , ? ) ; ";
my $SelectString = " Select URL , ID from TB_URL where LabelID = '" . $labelID."';";
my $InsertIntoFileName_QS = "INSERT IGNORE INTO TB_FileName( filename) VALUES (?) ; " ;
###################################################################################################
my $DBIConnect = DBI->connect($dsn , $user , $passwd) or die("Cannot connect to datadbase $DBI::errstr\n");
print ("Splitting Into Words \n");
######Initialization of a default DB value #################
my $sth = $DBIConnect->prepare( $InsertIntoExtensionNULL_QS);
$sth->execute(1 , 'null') or die("Error Executing the Insertion" . $sth->errstr );
$sth->finish();
#############################################################
$sth = $DBIConnect ->prepare($SelectString);
sleep(10);
open (FH , '<' , $file); # Open file to be read from disk
my $i = 0;
$sth->execute() or die("Error Executing the Insertion" . $sth->errstr );
->line 15 while(my $hash_ref = $sth->fetchrow_hashref )
{
my $extensionID = "1";
my $intialURL = $hash_ref->{URL} ;
my $initialID = $hash_ref->{ID};
}
}
I'm not sure if this is the issue, but you may not need the finish after the insert. From the DBI doc:
Indicate that no more data will be fetched from this statement handle
before it is either executed again or destroyed. You almost certainly
do not need to call this method.
Adding calls to finish after loop that fetches all rows is a common
mistake, don't do it, it can mask genuine problems like uncaught fetch
errors.
If that is the problem, you may want to create a second statement handler for the select call.
Apart from the annoyingly long SQL variable names, $SelectString should contain a "?", in case $labelID contains something that could break the query or cause an injection.
prepare() doesn't absolutely require a "?", but if execute has parameters, then there must be a matching number of "?" in the query string.
First $sth->finish() is not needed because the query is an insert and doesn't return any rows.
Second 'die' should be "Error executing query", because it executing $SelectString
Note SQL convention is to write all in uppercase, and for extra safety enclose field names in backticks. Queries do not end with semicolon. Also note that "my" variables are local to that between braces, { } so that my variables in the while loop will be unavailable afterwards.
Suggest formatting thus:
sub Split_Into_Words {
#### Connection parameters ############################
my $dsn = "dbi:mysql:malware:localhost:3306";
my $user = 'root';
my $passwd = 'sxxxs';
########################################################
my $domain ;
my $countDir = 0 ;
my $file = shift ;
my $labelID = (split(/[.]/ , $file))[1] ; ### Split and get the middle value since format is temporary.
#### Query String ############################################################################
my $InsertIntoHostTable_QS = "INSERT INTO `TB_host` (`HostName`,`UrlID`,`ExtID`) VALUES (?,?,?)";
my $InsertIntoDomainTable_QS = "INSERT IGNORE INTO `TB_Domain` (`Domain`) VALUES (?)";
my $InsertIntoArgVal_QS = "INSERT INTO `TB_Arg_Value` (`Arg`,`URL_ID`) VALUES (?,?)";.
my $InsertIntoDirectory_QS = "INSERT INTO `TB_Directory` (`DIRNAME`,`DEPTH`,`URLID`) VALUES (?,?,?)";
my $InsertIntoExtension_QS = "INSERT IGNORE INTO `TB_Extension` (`Extension`) VALUES (?)";
my $InsertIntoExtensionNULL_QS= "INSERT IGNORE INTO `TB_Extension` (`ID`,`Extension`) VALUES (?,?)";
my $SelectString = "SELECT `URL`,`ID` FROM `TB_URL` WHERE `LabelID`=?";
my $InsertIntoFileName_QS = "INSERT IGNORE INTO `TB_FileName` (`filename`) VALUES (?)";
###################################################################################################
my $DBIConnect = DBI->connect($dsn , $user , $passwd) or die("Cannot connect to datadbase $DBI::errstr\n");
print ("Splitting Into Words \n");
######Initialization of a default DB value #################
my $sth = $DBIConnect->prepare( $InsertIntoExtensionNULL_QS);
$sth->execute(1 , 'null') or die("Error executing the Insertion: " . $sth->errstr );
# $sth->finish(); # not needed because it's an insert
#############################################################
$sth = $DBIConnect->prepare($SelectString);
sleep(10);
open (FH , "<$file"); # Open file to be read from disk
my $i = 0;
$sth->execute($labelID) or die("Error executing query: " . $sth->errstr );
while(my $hash_ref = $sth->fetchrow_hashref ) {
my $extensionID = "1";
my $intialURL = $hash_ref->{URL};
my $initialID = $hash_ref->{ID};
}