Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

Re: Need help writing a script that interacts with a MySQL DB!

by chromatic (Archbishop)
on Sep 30, 2012 at 03:33 UTC ( #996454=note: print w/replies, xml ) Need Help??

in reply to Need help writing a script that interacts with a MySQL DB!

Which part is giving you trouble? We can only guess, but here are some suggestions:

my $query = "SELECT * FROM People where Name = '$console'";

Change the query to SELECT name, email FROM People... for two reasons. One, to get in the habit of selecting only the columns you need. Two, so that you know what you're getting back and in what order.

(You should also look up prepared queries in the DBI documentation, because it's really easy to allow bad data into a query to get the wrong results or to make a security hole. For now, this isn't a problem if you're the only one who runs this program, but look up this information as soon as you get the program working and then change the program to use them.)

if ($index = "1") {

This is always going to be true because you're not comparing $index to "1". You're assigning "1" to $index. You should instead write if $index == 1 for two reasons. First, it's a numeric comparison, so you need to use the numeric equality operator. Second, it's a numeric comparison, so you can leave 1 as a numeric literal and not a string literal. With that all said, you don't need $index at all because...

while (@results = $query1->fetchrow_array()) { foreach(@results) {

... you don't need the for loop. If you've only selected the name and email columns from the database, you can more easily and simply write:

while (my ($name, $email) = $query1->fetchrow_array()) { print "\nName: $name\nEmail: $email\n"; }

(You don't even have to select the name column because you're searching on it, but you get the point.)

Improve your skills with Modern Perl: the free book.

Replies are listed 'Best First'.
Re^2: Need help writing a script that interacts with a MySQL DB!
by Anonymous Monk on Sep 30, 2012 at 09:49 UTC

    I'll one-up you with bound columns. (Perhaps not for the beginner, though.)

    $query1 = $conn->prepare(q{SELECT name, email FROM ...}); $query1->execute(...); $query1->bind_columns( \my ($name, $email) ); while ($query1->fetch) { print "\nName: $name\nEmail: $email\n"; }

    They're just magic. And among the cleanest and most efficient interfaces DBI provides.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://996454]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (7)
As of 2018-06-24 22:45 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (126 votes). Check out past polls.