I'm trying to insert data to my database using a custom php in wordpress. The entire php file contains this:
<?php global $wpdb;
if(isset($_POST['Import']))
{
$filename = $_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0)
{
$file = fopen($filename, "r");
$count = 0;
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
$count++;
if($count>1){ $wpdb->insert('wp_inventory_list',
array( 'project_code' => $emapData[0],
'phase' => $emapData[1],
'subphase' => $emapData[2],
'block' => $emapData[3],
'lot' => $emapData[4],
'lot_area' => $emapData[5],
'flr_area,' => $emapData[6],
'model_code' => $emapData[7],
'house_model' => $emapData[8],
'tcp' => $emapData[9] ),
array( '%s', '%s' ,'%s' ,'%s' ,'%s' ,'%s' ,'%s' ,'%s' ,'%s' ,'%s'));
}
}
fclose($file);
echo 'CSV File has been successfully Imported';
}
else
{
echo 'Invalid File:Please Upload CSV File';
}
}
?>
Whenever I try to run the script I get an error "Call to a member function insert() on a non-object". Is my $wpdb
not working right? I added the custom php file inside wp-content/themes/mytheme/
folder. Do I still need to configure something for the global $wpdb variable to work?
$wpdb
is probablynull
. You can chack this by runningvar_dump($wpdb)
. Declaring the variable global won't help if this script is not run within the wordpress framework. If this is an "extra" file, meaning not called inside of the template in your case, it won't work like this.In Wordpress 3.4+ you have to do it like this:
For older Wordpress see http://www.stormyfrog.com/using-wpdb-outside-wordpress/.