I am starting to write some Perl scripts for some cron jobs that will query the database and send out reminders about upcoming events. I'm quite new to database access in Perl as most of my work thus far has been on the web end using PHP. Anyway, the first query is working fine to generate a temporary output file and then I'm reading back in that output file to loop thru the results querying to find the specific events for the users discovered in the first query.
The problem that I am running into now is getting the following error:
./remind.pl
DBD::mysql::st execute failed: FUNCTION dbName.GLOB does not exist at ./remind.pl line 41.
SQL Error: FUNCTION dbName.GLOB does not exist
This is my Perl code
$host = 'localhost';
$database = 'dbName';
$user = 'user';
$password = 'password';
use POSIX qw(strftime);
use List::MoreUtils qw(uniq);
use Mail::Sendmail;
use DBI;
$dt = strftime("%Y%m%d%H%M%S", localtime(time));
$List30 = "../tmp/queries/30DayUserList.$dt";
open my $UserList30Day, ">> $List30" or die "Can't create tmp file: $!";
$dbh = DBI->connect('dbi:mysql:dbName',$user,$password) or die "Connection error: $DBI::errstr\n";
$sql = "SELECT DISTINCT user FROM shows WHERE initial_date BETWEEN CURDATE() AND CURDATE() + INTERVAL 30 DAY";
$sth = $dbh->prepare($sql);
$sth->execute or die "SQL Error: $DBI::errstr\n";
while (#jeweler = $sth->fetchrow_array()) {
print $UserList30Day "$user[0]\n";
}
close $UserList30Day;
open my $UserIDList, "< $List30" or die "Can't open temp file: $List30";
while ($id = $UserIDList) { # Read in User ID from temp file as $id
# Query for show information for next 30 days
my $sql = "SELECT shows.initial_date, shows.initial_time, shows.hostess_key, hostess.hostess_fname, hostess.hostess_lname, hostess.primary_phone, hostess.address1, hostess.address2, hostess.city, hostess.zipcode, hostess.state
FROM shows, hostess
WHERE shows.user = $id
AND initial_date BETWEEN CURDATE() AND CURDATE() + INTERVAL 30 DAY
AND shows.hostess_key = hostess.hostess_key";
my $sth = $dbh->prepare($sql);
$sth->execute or die "SQL Error: $DBI::errstr\n";
# Iterate thru query results to create output data
while (#row = $sth->fetchrow_array()) {
$content = "Reminder: You have a show for $row[3] $row[4] coming up on $row[0] at $row[1].\n";
$content .= "Location: $row[6] \n";
if ($row[7] != '') {
$content .= " " . $row[7] . "\n";
}
$content .= " $row[8], $row[10] $row[9] \n";
$content .= "Phone: $row[5] \n";
}
%mail = (To => 'email',
From => 'email',
Subject => 'Just another test',
Message => $content
);
# sendmail(%mail) or die $Mail::Sendmail::error;
print %mail;
}
close $UserList30Day;
Thanks in advance for any assistance.
while ($id = $UserIDList) {
should be
while ($id = <$UserIDList>) {
chomp;
Related
I am trying to make a little script to extract databases/tables/columns from my database, but in the first step I couldn't move on, I am getting databases in strange list, please look:
#!/usr/bin/perl
use DBI;
$host = "localhost";
$user = "wnyclick_siteusr";
$pw = "Hank0402\$";
$dsn = "dbi:mysql:$database:localhost:3306";
$connect = DBI->connect($dsn, $user, $pw);
$databases = $connect->selectcol_arrayref('show databases');
use Data::Dumper;
print Dumper $databases;
executing this code giving me the following:
$VAR1 = [
'information_schema',
'wnyclick_sitedatawp'
];
How can I put this execution result in a list?
print #VAR1[0];
print #databases[0];
I just modified your code. Try the below code:
#!/usr/bin/perl -w
use DBI;
use DBD::mysql;
my $user = "wnyclick_siteusr";
my $pw = "Hank0402\$";
#Connecting Database
$dbh = DBI->connect( 'dbi:mysql:database=mysql;host=localhost;port=3306', '$user', '$pw' )
or die "Connection Error: $DBI::errstr\n";
$sql = "show databases";
$sth = $dbh->prepare($sql);
$sth->execute or die "SQL Error: $DBI::errstr\n";
while ( #row = $sth->fetchrow_array ) {
#print $row[1];
print "#row\n";
}
I am making a code that connects to a database 'peoples', gets data from there and what i need to do is with a button to get the id for the person where this button is clicked and delete or update. The problem is i dont know how to make this i perl because in other languages i did it.
my $q= new CGI;
print $q->header;
print $q-> start_html(
-title => "Main",
-style => {-src =>'/media/css/ui-lightness/jquery-ui-1.10.3.custom.css" rel="stylesheet' },
-script => [
{ -src=>'/media/js/jquery-1.9.1.js'},
{ -src=>'/media/js/jquery-ui-1.10.3.custom.js' }
]
);
print $q->start_form;
print $q->table({},
$q->Tr(
$q->th('Name', 'Surname', 'Age')
));
# Connect to the database
## mysql user database name
my $db = "student";
## mysql database user name
my $user = "root";
## mysql database password
my $pass = "";
## user hostname : This should be "localhost" but it can be diffrent too
my $host="127.0.0.1";
## SQL query
my $query = "select Name,Surname,Age from student";
my $dbh = DBI->connect("DBI:mysql:$db:$host", $user, $pass);
my $sqlQuery = $dbh->prepare($query)
or die "Can't prepare $query: $dbh->errstr\n";
my $rv = $sqlQuery->execute
or die "can't execute the query: $sqlQuery->errstr";
while ( my ($Name, $Surname, $Age) = $sqlQuery->fetchrow_array() ) {
print STDOUT "$Name $Surname $Age";
$q->button( print $q->button(
-id => 'leletebtn',
-name => 'submit_form',
-value => 'Delete',
)
)
}
print $q->end_form;
print $q->end_html;
There are a lot of tutorials out there. You have to use DBI:
http://oreilly.com/catalog/perldbi/chapter/ch04.html
http://www.perl.com/pub/1999/10/DBI.html
my $lastname = 'test';
my $dbh = DBI->connect('DBI:Oracle:people')
or die "Couldn't connect to database: " . DBI->errstr;#connect
my $sth = $dbh->prepare('SELECT id,uid FROM people WHERE lastname = ?')
or die "Couldn't prepare statement: " . $dbh->errstr;#prepare
$sth->execute($lastname); # Execute the query
while ( my $ref = $sth->fetchrow_hashref() ) {
print "$$ref{'id'} \t $$ref{'uid'}\n";
}
I have created a code that connects to database and i want to delete data from database using a button the same for update. but i just can display data in a table and cant delete.
my $q= new CGI;
print $q->header;
print $q-> start_html(
-title => "",
);
# print $q->start_form;
## mysql user database name
my $db = "people";
## mysql database user name
my $user = "root";
## mysql database password
my $pass = "";
## user hostname : This should be "localhost" but it can be diffrent too
my $host="127.0.0.1";
## SQL query
my $query = "select ID,Name,Surname,Gender from person";
my $dbh = DBI->connect("DBI:mysql:$db:$host", $user, $pass);
my $sqlQuery = $dbh->prepare($query)
or die "Can't prepare $sqlQuery: $dbh->errstr\n";
my $rv = $sqlQuery->execute
or die "can't execute the query: $sqlQuery->errstr";
print start_form (-method => 'post', -action => "modify.pl" );
my #aRows;
while (my #data = $sqlQuery->fetchrow_array()) {
my $cRowId = hidden('ID', $data[0]);
my $bt1 = submit('action','delete');
my $bt2 = submit('action','update');
push #aRows, ($cRowId, $q->Tr($q->td([$data[1], $data[2], $data[3],$bt1,$bt2])));
}
print $q->table({-border =>'1', -align =>'center', -width => '100%'},
$q->Tr([$q->th([ 'Name', 'Surname', 'Gender', 'Delete', 'Update', ])]),
#aRows,
);
print $q->input({-type => 'button', -class => 'button', -onclick => "window.location.href='insert.pl';", -value => 'Shto'});
print $q->end_form;
print $q->end_html;
delete.pl
use CGI;
use CGI qw(standard);
use DBI;
use CGI::Carp qw(set_die_handler);
use CGI qw/:all/;
BEGIN {
sub handle_errors {
my $msg = shift;
print "content-type: text/html\n\n";
#proceed to send an email to a system administrator,
#write a detailed message to the browser and/or a log,
#etc....
}
set_die_handler(\&handle_errors);
}
my $q = CGI->new();
my $db = "people";
my $user = "root";
my $pass = "";
my $host="127.0.0.1";
my $dbh = DBI->connect("DBI:mysql:$db:$host", $user, $pass);
my $action = $q->param('action'){
given ($action){
when('delete'){
my $row_id = $q->param('ID');
my $sth = $dbh->prepare("DELETE FROM person WHERE ID = $row_id ") or die "Can't prepare $query: $dbh->errstr\n";
my $rv = $sth->execute() or die $DBI::errstr;
print "deleted";
my $sth->finish();
my $dbh->commit or die $DBI::errstr;
}
} }
I dont know where may be the problem
The vast majority of Perl CGI problems can be solved by:
Adding use strict and use warnings to your code
Fixing all of the errors that now appear in your error log
You assign a value to $row_id after you try to use that variable to create your query.
Additionally, using raw user input in SQL queries makes you vulnerable to XSS attacks. Rewrite your code to use parameterized queries
Do not use my if you do not want a new variable. Remove all my's from the method calls:
my $sth->finish();
my $dbh->commit or die $DBI::errstr;
I am trying to create a cgi based on perl to display my album and now I am working on the sorting function on photos. I stored the information of each photo in mysql. To display all photos, I have to fetch the information first.
Here is the problem: I am expecting the fetched data from mysql is sorted by the file size of each photos, however the result from the fetchrow_array() is the data sorting according to the time being inserted into mysql.
In mysql shell, I tested
SELECT * FROM album ORDER BY filesize;
which gives the expected result sorted by the file size. Here is part of my source code:
#!/usr/bin/perl -w
use strict;
use CGI;
my $sort = 'filesize';
# Connect the database
my $dbh = do 'db.pl';
# Prepare to print out the pictures
my $query;
$query = $dbh->prepare("SELECT * FROM album ORDER BY ?") or die $DBI::errstr;
$query->execute($sort) or die $DBI::errstr;
# Print out all pictures
while( my #data = $query->fetchrow_array() ){
# Process fetched data
(my $id, my $user, my $filepath, my $filename, my $filesize, my $uploadtime, my $description, my $tfilepath, my $sessioninfo) = #data;
print '<fieldset>';
# Display thumbnail
print '<img src="', $tfilepath, '" title="', $description, '">';
# Display filename
print '</br>';
print $filename;
print '</fieldset>';
}
# Finish printing out all fetched pictures
$query->finish;
Am I using the wrong command? Or I am using a wrong approach to do the sorting function?
Thanks for helping!
ORDER BY takes a field name, not an expression.
my $query = "SELECT * FROM album ORDER BY ".$dbh->quote_identifier($sort);
my $sth = $dbh->prepare($query);
$sth->execute();
By the way, you have have bugs on the output side too. What if $description contains """, "&" or "<"? You need some escaping.
sub text_to_html {
my ($s) = #_;
$s =~ s/&/&/g;
$s =~ s/</</g;
$s =~ s/>/>/g;
$s =~ s/"/"/g;
$s =~ s/'/'/g;
return $s;
}
By the way,
(my $id, my $user, my $filepath, my $filename,
my $filesize, my $uploadtime, my $description,
my $tfilepath, my $sessioninfo) = #data;
can be written as
my ($id, $user, $filepath, $filename,
$filesize, $uploadtime, $description,
$tfilepath, $sessioninfo) = #data;
I host at hostgator and have about 30 mysql databases (all different websites that sit on the same server). For the last year.. no problems and suddenly, the last 2 days, I've seen 5 - 10 of these databases marked as 'crashed' and they return no results... so my websites display no info. I have to run a "repair table mytable" to fix these and then they work great again.
Instead of logging in to go through the databases 1 by 1 every morning, is there a way I could setup a php page to connect to all 30 databases and run a simple select statement.. and if it works, return
"database db1 is working"
"database db2 is working"
and then when not working, return
"no reply from db3"
....or something similar?
Thanks!
There's no reason you couldn't have a script that lists all of your databasenames and login credentials, and try to connect in turn to each:
$logins = array(
array('dbname' => 'blah', 'user' => 'username1', 'password' => 'password1'),
array('dbname' => 'yuck', ....)
...
);
$failures = array();
foreach ($logins as $login) {
$con = mysql_connect('servername', $login['user'], $login['password']);
if (!$con) {
$failures[] = $login['dbname'] . " failed with " . mysql_error();
continue;
}
$result = mysql_select_db($login['dbname']);
if (!$result) {
$failures[] = "Failed to select " . $login['dbname'] . ": " . mysql_error();
continue;
}
$result = mysql_query("SELECT something FROM sometable");
if (!$result) {
$failures[] = "Faile to select from " . $login['dbname'] . ": " . mysql_error();
continue;
}
if (mysql_num_rows($result) != $some_expected_value) {
$failures[] = "Got incorrect rowcount " . mysql_num_rows($result) . " on " . $login['dbname'];
}
etc....
mysql_close();
}
if (count($failures) > 0) {
echo "Failures found: "
print_r($failures);
}
You should be able to do something like the following:
<?php
//connect to database
mysql_connect('database','user','password');
//get all database names
$result = mysql_query("show databases;");
//iterate over all databases returned from 'show databases' query
while($row = mysql_fetch_array($result)) {
//DB name is returned in the result set's first element. select that DB
mysql_selectdb($row[0]);
//get all tables in the database
$query = "show tables;";
$result2 = mysql_query($query);
echo "Query: (".$row[0].")$query\n";
echo mysql_error();
//iterate over all tables in the current database
while($row2 = mysql_fetch_array($result2)) {
//the first element of the returned array will always be the table name, so:
$query = "select * from ".$row2[0]." where 1=1;";
$result3 = mysql_query($query);
echo "Query:\t(".$row[0].'/'.$row2[0].")$query\n";
//If mysql_query returns false (i.e., $result3 is false), that means that
// the table is damaged
if(!$result3) {
echo "***Error on table '".$row2[0]."' *** ... Fixing...";
//So, we repair the table
mysql_query("repair table ".$row2[0].";");
}
}
}
?>