Jump to content

**SOLVED** File() & mysql_query


Nexx

Recommended Posts

[code] <?php
include("login.inc.php");

mysql_connect($hostname,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");

$file = file("names.txt");

foreach ($file as $names) {
//echo just to see its working
echo $names."<br>";
mysql_query("INSERT INTO vote (id,name,vote) VALUES (NULL,$names,'')");
}
mysql_close();
?>[/code]

Hello,

I have a text file which is a list of names, each on its own line. I'm trying to use the above code to take each name and insert it into a mysql database. My problem is, that mysql_query will only take a value if it is a number. If I replace names in the text file with numbers it works perfectly. I have also tried replacing file() with file_get_contents() and exploding it, same problem. I am possitive my database is set up correctly, I tested the same code by replacing $names with actual text and it inserted just fine.

As you can probably tell I'm new at this, I appreciate any help that can point me in the right direction here.
Link to comment
Share on other sites

You need quotes round string values.
Also, use trim() to remove newline from end of each name
[code]
foreach ($file as $names) {
        //echo just to see its working
        echo $names."<br>";
        $names = trim($names);
mysql_query("INSERT INTO vote (id,name,vote) VALUES (NULL,'$names','')");
}[/code]
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.