Jump to content


Photo

**SOLVED** File() & mysql_query


  • Please log in to reply
2 replies to this topic

#1 Nexx

Nexx
  • New Members
  • Pip
  • Newbie
  • 3 posts

Posted 01 June 2006 - 03:07 AM

<?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();
?>

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.

#2 Barand

Barand
  • Moderators
  • Sen . ( ile || sei )
  • 18,017 posts

Posted 01 June 2006 - 06:25 AM

You need quotes round string values.
Also, use trim() to remove newline from end of each name
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','')");
}

If you are still using mysql_ functions, STOP! Use mysqli_ or PDO. The longer you leave it the more you will have to rewrite.

Donations gratefully received






moon.png

|baaGrid| easy data tables - and more
|baaChart| easy line, column and pie charts

#3 Nexx

Nexx
  • New Members
  • Pip
  • Newbie
  • 3 posts

Posted 01 June 2006 - 08:50 PM

Thanks, that did the trick.




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users