http://www.perlmonks.org?node_id=996454


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.