0

Very new to PHP and ran into some trouble and was wondering if anyone could help. I'm having problems with an array of names that are looked up in a database. When I use just the array of names it gets processed correctly. When I try and read a file of those same names only the last name gets displayed. My question is how can I get all names displayed for the file array?

Please see examples and code below. Thanks for your time.

//This works -- Sample 1
$x = array("joe", "paul", "tom");

//This does not -- Sample 2
$x = file("name.txt"); //Same names from the array above are in this file

Here is the full code below.

<html>
    <head>
        <title>Name Check</title>
    </head>
    <body>
        <?php
            $con = mysql_connect("localhost", "xxxxxxxx", "xxxxxxxx");
            if (!$con) {
                die('Could not connect: ' . mysql_error());
            }

            mysql_select_db("xxxxxxxxxx", $con);

            // $x=array("joe", "paul", "tom"); //displays all names correctly in Sample 1 below
            $x = file("name.txt"); // only displays the last name in the file. Sample 2 below

            foreach ($x as $test) {
                $result = mysql_query("SELECT * FROM categories WHERE Name='$test' Limit 0, 1");

                while ($row = mysql_fetch_array($result)) {
                    echo $row['Name'];
                    echo " " . $row['Sport'];
                    echo "<br />";
                }
            }
        ?> 
    </body>
</html>

Sample 1 output

joe basketball
paul basketball
tom baseball

Sample 2 output

tom baseball

Here is the contents of name.txt, that was requested. Thanks!

joe 
paul 
tom
2
  • 1
    Could you provide sample file contents? Commented Mar 3, 2011 at 23:38
  • post the format of the file please. Commented Mar 3, 2011 at 23:38

1 Answer 1

3

file() leaves in the newline character at the end of each line, which only the last one lacks. You could use rtrim($test) to fix this.

You should also be escaping the name in case it contains characters like ', so a complete solution would be (just before the query):

$test = mysql_real_escape_string(rtrim($test));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.