0

I changed the code so that i can insert directly into the database. Now I face an issue with line of code $database->bindParam(':name', $name[0][$i]);. Which gives me the error Fatal error: Call to undefined method PDO::bindParam() How can I fix this?

$hostname = 'XXX';
$database = 'XXX';
$username = 'XXX';
$password = 'XXX';
$database = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);

function get_data($url)
{
  $ch = curl_init();
  $timeout = 5;
  curl_setopt($ch,CURLOPT_URL,$url);
  curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
  curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
  $data = curl_exec($ch);
  curl_close($ch);
  return $data;
}

$html = get_data($_GET['url']);
preg_match_all('/\<font face\=\"Arial\"\>\<strong\>(.*)\<br\>\<font color/', $html, $name);
preg_match('/\<strong\>([A-Z\s0-9]+) BIRTHDAYS\<\/strong\>/', $html, $date);

for ($i=0, $n=count($name[1]); $i<$n; ++$i) {       
        try {
            $insert = $database->prepare("INSERT INTO bday (name, birthdate) VALUES (:name, :date)");

            $database->bindParam(':name', $name[0][$i]);
            $database->bindParam(':date', $date[1]);

            $insert->execute();
        }

        catch (PDOException $e) {
            echo $e->getMessage();
        }
}
1
  • 2
    simple insert with an auto increment primary key, the db will take care of the rest
    – user557846
    Dec 19, 2011 at 3:31

2 Answers 2

1

First fetch the content:

$content = file_get_contents('filename');

Get each line:

$line = explode('\n', $contents);

Now you have each line in an array; loop through each, explode it again on comma and insert to DB

$ct = count($arr);
while($i < $ct) 
{
     $arr = explode(',', $line[$i]);
     /* Insert into database value $i, $arr[1], $arr[2], just ignore $arr[0] which contains your original string */
     $i++;
}
3
  • the data is actually in a text file not in the database yet
    – bammab
    Dec 19, 2011 at 3:29
  • thanks i changed the code to add directly to the database can you take a look at it now?
    – bammab
    Dec 19, 2011 at 4:06
  • @bammab Though I have no experience with PDO.
    – check123
    Dec 19, 2011 at 4:11
1

I would make the database have a primary key which auto increments so you don't have to worry about it but if that isn't possible just throw it in a for loop:

$array = explode("\n",file_get_contents("file.txt"));
foreach($array as $count => $line) {
    $array[$count] = str_replace('xxx',$count+1,$line);
}
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.