WordPress.org

Ready to get started?Download WordPress

Forums

Creating table from wordpress (2 posts)

  1. 24adithya
    Member
    Posted 2 years ago #

    Hi,

    I have written a plugin which will create a table when the plugin is activated. I followed this tutorial :

    Creating Table using plugins

    When i activate the plugin, it seems the table isn't getting created.

    Following is the code i have written:

    global $wpdb;
    global $create_table_version;
    $create_table_version = "1.0";

    function create_table()
    {
    	global $wpdb;
    	global $create_table_version;
    
    	$table_name = $wpdb->prefix . "url_parse";
    
    	$wpdb->show_errors();
    
    	$sql = "CREATE TABLE $table_name (
    	  id mediumint(10) NOT NULL AUTO_INCREMENT,
    	  url VARCHAR(60) NOT NULL,
    	  tag VARCHAR(60) NOT NULL,
    	  UNIQUE KEY id (id)
    	);";
    
    	require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    	dbDelta($sql);
    
    	$wpdb->print_error();
    
    	add_option("create_table_version", $create_table_version);
    
    	register_activation_hook(__FILE__,'create_table');
    }

    I am saying this because when i wrote an insert query to insert a row in the table i got the following error :

    WordPress database error: [Table 'wordpressdb.url_parse' doesn't exist]
    INSERT INTO url_parse (url,tag) VALUES ('timesofindia.indiatimes.com','<div class=\"Normal\">')

    I also get an error like for the select query :

    WordPress database error: [You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '<div class="Normal"&gt' at line 1]
    select url,tag from url_parse where url = timesofindia.indiatimes.com and tag = <div class="Normal">

    My select and insert queries are as follows:

    $wpdb->show_errors();
    
    	if($url[url_name] != null && $url[tag_name] != null)
    	{
    		$results = $wpdb->get_results("select url,tag from url_parse where url = $url[url_name] and tag = $url[tag_name]");
    	}
    	$wpdb->print_error();
    if($results == null)
    	{
    		$results = $wpdb->insert(
    						'url_parse',
    						array(
    							'url' => $url[url_name],
    							'tag' => $url[tag_name]
    						)
    					);
    	}
    	$wpdb->print_error();
  2. Kakoma
    Member
    Posted 2 years ago #

    Hi 24adithya,
    You aren't using the DB Prefix in your query.
    For the select query,

    $results = $wpdb->get_results("select url,tag from url_parse where url = $url[url_name] and tag = $url[tag_name]");

    That should be:

    //Get table name
    $table_name = $wpdb->prefix . "url_parse";

    Then

    //Use the table name in the select query
    $results = $wpdb->get_results("select url,tag from  $table_name  where url = $url[url_name] and tag = $url[tag_name]");

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags