Solved

Printing result Perl?

Posted on 2003-12-09
4
724 Views
Last Modified: 2013-12-25
how do i get perl to display rthe result of the sql:
 $uidpwd = $FORM{'username'}."/".$FORM{'password'};
   $stuid = " select spid,surname,forename,userid,faccode,course,slotday,tpid" .
          " from diz.students" .
          " where spid='" .
          $FORM{'id'} ."';";

I want to display the results of '$stuid' but when i use the 'PRINT' function it just displays the sql formula and not the result of the sql help!!
0
Comment
Question by:boffer
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
4 Comments
 
LVL 3

Accepted Solution

by:
mrh30 earned 25 total points
ID: 9904791
You will need to actually run the SQL query.  This will probably mean:

use DBI;  #Or whatever you're using

## You need to set up the variables you need here

my $dbh = DBI->Connect("DBI:mysql:database=".$db_name.";host=".$db_host, $db_user, $db_pass)
                      or die "Cannot connect to database";

print $dbh->selectrow_array(" ... your sql here ... ");
0
 
LVL 5

Assisted Solution

by:djplaistow
djplaistow earned 25 total points
ID: 9905743
Try this subroutine; the sub prolog has example usage. It relies on some global variables, so be sure they are set.

################################################################################
# Author:  Don Plaistow
# Purpose: This function will execute an arbitrary number of SQL queries on
#          the database specified in the first argument. If any of the queries
#          are a select, then a reference to an array of hashes will be returned.
#          Here is an example of executing a select statement:
#
#              my $sql = qq[SELECT * from myTable;];
#              my $raRows = Sql($dbName, $sql);
#              # Get the value from the first row of the column named "Id"
#              my $firstRowId = $raRows->[0]->{Id};
#              
#              # Loop through all the rows in the data set printing the value of
#              # the column named "Id" for every row
#              foreach my $rhRow (@$raRows)
#              {
#                print "$rhRow->{Id} \n";
#              }
#
# Arguments: $dbName: the database name
#            $sqlStatement: A valid SQL statement
# Global variables:
#             $host: The database host computer
#         $dbUser: The database user name to use for the connection to the DB
# $dbPassword: The password required for the user specified in $dbUser
#    $debugging: Set true if debugging data is desired
#       $debugDir: The directory where the debug text file,
#                          db_executeSQLStatement.txt, will be stored.
################################################################################
sub Sql
{
  my $dbName = shift(@_);
  my $sql = "";
  my $status = "1";
  my @rowArray = ();

  if (my $db = DBI->connect("dbi:mysql:$dbName:$host", $dbUser, $dbPassword, {PrintError => 0, RaiseError => 0}))
  {
    # The remaining function arguments should be valid SQL statements, so execute them
    # until there are no more.
    while (@_)
    {
      $sql = shift(@_);
      # If the query has any whitespace after the closing ';' it might fail
      # TODO: This might not be a problem.
      $sql =~ s/;\s*$/;/;

      if (my $sth = $db->prepare($sql))
      {
        if ($sth->execute())
        {
          # If the SQL statement was a select, then push a reference to the
          # results hash into an array so it can be returned to the caller
          if ($sql =~ m/^\s*select/io)
          {
            while(my $hashRef = $sth->fetchrow_hashref())
            { push (@rowArray, $hashRef); }
          }
        }
        else { $status = "ERROR: Can't execute sql statement: $sql\n\n $DBI::errstr\n";}
      }
      else { $status = "ERROR: Can't prepare sql statement: $sql\n\n $DBI::errstr\n";}
    }
    if (!$db->disconnect)
    { $status = "ERROR: disconnecting: $DBI::errstr\n";}
  }
  else
  { $status = "ERROR: Can't connect to database $DBI::errstr\n";}
   
  if(($debugging == 1) && ($status ne "1"))
  {
    open (DB_FILE, ">$debugDir/db_executeSQLStatement.txt");
    print DB_FILE "$sql\n";
    foreach my $rowHash (@rowArray)
    {
      print DB_FILE "*******************  ROW DATA  ************************\n";
      foreach $field (keys %$rowHash)
      { print DB_FILE "$field = $rowHash->{$field}\n"; }
    }
    print DB_FILE "status: $status";
    close(DB_FILE);
  }

  # If there was a problem and it wasn't just a blank database name
  if (($status ne "1") && ($dbName !~ m/^\s*$/))
  {
    my $envs = "";
    foreach $var (sort(keys(%ENV)))
    {
      $val = $ENV{$var};
      $val =~ s|\n|\\n|g;
      $val =~ s|"|\\"|g;
      $envs .= "${var}=\"${val}\"\n";
    }
    if ($sql eq "") { foreach $arg (@_) { $sql .= "$arg\n"; } }
    print "Content-type: text/html\n\n";
    print "<pre>Testing: Error during SQL call.\nDB: $dbName\nSQL: $sql\nStatus: $status\n ENVS:\n $envs";
  }

  # If at least one of the queries was a select, then there should be values in
  # the array that need to be returned. Otherwise, just return the
  if (@rowArray) { return(\@rowArray); }
  else           { return($status); }
} # end of Sql
0

Featured Post

Webinar: Aligning, Automating, Winning

Join Dan Russo, Senior Manager of Operations Intelligence, for an in-depth discussion on how Dealertrack, leading provider of integrated digital solutions for the automotive industry, transformed their DevOps processes to increase collaboration and move with greater velocity.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this tutorial I will show you how to make a simple HTML bar chart with the usage of WhizBase, If you want more information about WhizBase please read my previous articles at http://www.experts-exchange.com/ARTH_5123186.html (http://www.experts-ex…
In threads here at EE, each comment has a unique Identifier (ID). It is easy to get the full path for an ID via the right-click context menu. However, we often want to post a short link within a thread rather than the full link. This article shows a…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…

737 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question