Using wpdb to display non-wordpress database data not working - mysql

I have created a section in my functions.php file and registered a shortcode which is intended to echo some data from a custom mysql database table.
I have an external system which will insert data into the database.
My wordpress install should be able to read from this database, and I would like to echo some rows on a wordpress page via shortcode.
The problem I am having is that the table data is not being echoed out. I can do echo "test"; and the word test will get displayed but the problem I having is not showing table data. Heres my code.
function vstp_feed_function(){
//$x++;
//$alternatingclass = ($x%2 == 0)? 'whiteBackground': 'graybackground';
$mydb = new wpdb('root','cencored','testdb','localhost');
$rows = $mydb->get_results("select * from services");
echo "<ul>";
foreach ($rows as $obj) :
echo "<li>".$obj->headcode."</li>";
endforeach;
echo "</ul>";
}
add_shortcode('vstp_feed', 'vstp_feed_function');
So the above code will create a new variable mydb, with the database credentials and information. A new variable called $rows will store the sql query which uses the mydb variable. I get all columns from services table. Thereafter I am echoing an unordered list, running a for loop to display the contents of the column "headcode" in list item html.
Once the select query is done, the for loop ends and so does the html list.
The shortcode is registered as [vstp_feed] which is tested and working with static html.
Any help would be greatly appreciated. Worked with sql before but not with new wordpress db instances. Thanks.
Just to confirm, its apache ubuntu. Its also worth noting that my ##datadir is stored on a different disk seperate from my OS disk, for faster IO and freedom to expand storage on the fly

Place your connection code inside wp-config.php file ( $mydb = new wpdb('root','cencored','testdb','localhost'); )
And use it in your function file as "global $mydb;"

Related

How to import a csv file into MySQL server?

I am very new to MySQL. I have started learning MySQL today only.
I have been given a task.
In this task I need to create a sample csv file in excel and then upload it on MySQL server, then make some changes and then write it back as a csv file on the hard drive.
I looked up many links available on internet but they are too complicated to understand.
Can somebody explain it to me in simple words assuming that I am a beginner and I just know how to create a connection on MySQL.
Thank You.
Try this,
<?php
$csvFile = 'test_data.csv';
$csv = readCSVFile($csvFile);
if(!empty($csv))
{
foreach($csv as $file)
{
//inserting into database
$query_insert = "insert into csv_data_upload set
name = '".$file[0]."',
value = '".$file[1]."'";
echo $query_insert;
$insert = mysql_query($query_insert);
}
} else {
echo 'Csv is empty';
}
//Reading CSV File
function readCSVFile($csvFile)
{
$file_handle = fopen($csvFile, 'r');
while (!feof($file_handle) )
{
$line_of_text[] = fgetcsv($file_handle, 1024);
}
fclose($file_handle);
return $line_of_text;
}
?>
And for writing CSV File, Try this,
<?php
$list = array (
array('aaa', 'bbb', 'ccc', 'dddd'),
array('123', '456', '789'),
array('"aaa"', '"bbb"')
);
$fp = fopen('file.csv', 'w');
foreach ($list as $fields)
{
fputcsv($fp, $fields);
}
fclose($fp);
?>
I would recommend uploading the data via Microsoft Access. Access is just like Excel part of the office suite from microsoft. You can easily import the CSV / Excel file via a wizzard. Then use the database wizzard to upload everything to MySQL.
By the way you could probably do the same changes to the data in MS Access. It runs with some adaptations the same SQL commands and you could also use the GUI. I would recommend MySQL more for on line purposes, not for stuff you can do off line. And lets be fair using a command line might not be for everybody the most easy point of entry to databases. There are more using friendly command line alternatives for MySQL, for example mysql workbench and phpmyadmin. You could use them to directly import in to MySQL, but I have no experience with that option.
Good luck with you task.
You should put your code what you have tried, even you can search over google before posting question. Suggested link to check - http://www.php-guru.in/2013/import-csv-data-to-mysql-using-php/

Adding a record to mysql reusing a phpbb connection

I have integrated PHPbb to my website and I am using the phpbb connection to read data from an additional table I created on the database. below is the read code to query the databse:
$sql = 'SELECT tetsin, prod_desc_short, prod_price_old, prod_price_new, prod_img
FROM ' . tet_product;
$result = $db->sql_query($sql);
$data = array();
while ($row = $db->sql_fetchrow($result))
{
$data[] = $row;
}
What I am having trouble with is finding the function to add records to the databse, can someone direct me on what technology I may be using and unaware? I saw something about the Data Absraction layer and was a little more than sketchy on if there are some "variants" on functions or something like that, anyway I know the quer function above is "$db->sql_query" so any help in the insert query would be greatly appriciated. thanks!
See the official wiki, it has guides to most things you will need https://wiki.phpbb.com/Queries_in_phpBB3

How to execute large sql query in magento?

I want to store huge content in db and my sample text is 16129 characters in length when i tried to execute this query it is showing "error:The requested URL could not be retrieved" in firefox and "no-data received" in chrome.
Moreover I use LONGTEXT as datatype for text in DB.
I also tried to execute the query directly in phpmyadmin it is working correctly.
The code is shown below.
public function _getConnection($type = 'core_write') {
return Mage::getSingleton('core/resource')->getConnection($type);
}
public function testdbAction(){
$db = $this->_getConnection();
$current_time=now();
$text="The European languages are members of the same family...... ...Europe uses the same vocabulary. The ";//text is 16129 characters in length
$sql = "INSERT into test(`usercontent_id`,`app_id`,`module_id`,`customer_id`,`content`,`created_time`,`updated_time`,`item_id`,`index_id`,`position_id`) VALUES (NULL, 15, 9,2,'" .$text. "','" . $current_time . "','" . $current_time . "',1003,5,4)";
$db->query($sql);
}
How do i handle this? any suggestions or help..
Try using $db->exec($sql) instead of $db->query($sql)
For manipulating with database structure and data Magento has a dedicated place. It is called install / upgrade scripts. It was made to keep track of modules version for easy updates. So you should use a script to add new data.
Here's an example.
config.xml of your module:
<modules>
<My_Module>
<version>0.0.1</version>
</My_Module>
</modules>
<global>
<resources>
<my_module_setup>
<setup>
<module>My_Module</module>
<class>Mage_Core_Model_Resource_Setup</class>
</setup>
</my_module_setup>
</resources>
</global>
Now, you need to create following file:
My_Module/sql/my_module_setup/install-0.0.1.php
Now, depending on your Magento version, file would need to have a different name. If you're using Magento CE 1.4 or lower (EE 1.8) then you should name it mysql4-install-0.0.1.php.
This script will be launched at next website request. Class Mage_Core_Model_Resource_Setup will execute code inside install-0.0.1.php. From within the install script you will have access to the Setup class by using $this object;
So now, you can write in script following code:
$this->startSetup();
$text = <<<TEXT
YOUR LONG TEXT GOES HERE
TEXT;
$this->getConnection()
->insert(
$this->getTable('test'),
array(
'usercontent_id' => null,
'app_id' => 15,
'content' => $text,
//other fields in the same fashion
)
);
$this->endSetup();
And that's it. It's a clean and appropriate way of adding custom data to the database in Magento.
If you want to save a user input on a regular basis using forms, then I recommend creating w model, resource model and collection, define entities in config.xml. For more information please refer to Alan Storm's articles, like this one.
I hope that I understood your question correctly.

reading from a database using WordPress

I am very new to WordPress, I have very little knowledge with PHP.
I read about PODS and I know how to create one and use pages / templates to display data.
The issue I am havingis, the PODS I was creating use static data entered via the WP dashboard, what I want is to read data from a database, I am using MySql (same DB that wordpress is using). is there a way to use PODS and read the data from the DB, or wordpress has a better way to handle data coming from the DB ?
Thanks
You should Look into the $wpdb variable (and class)
http://codex.wordpress.org/Class_Reference/wpdb
Do remember to declare it a global:
<?php global $wpdb; ?>
I am however not sure what you want.
I advise staying close to wordpress.
If you want to create your own custom post types without using code use moretypes
Usual way to read from database in WordPress is the following:
get global variable $wpdb
global $wpdb
prepare the output and SQL command
$output = "";
$sql = "SELECT ".$wpdb->prefix."posts.post_title,
".$wpdb->prefix."posts.post_name FROM ".
$wpdb->prefix."posts WHERE ".$wpdb->prefix.
"posts.post_status='publish' AND ".$wpdb->prefix.
"posts.post_parent=0 AND ".$wpdb->prefix.
"posts.post_type='sometype'";
method get_results() retrieves values from db
$posts = $wpdb->get_results($sql);
$output .= '';
foreach ($posts as $post) {
$output .= 'post_name).
'">'.strip_tags($post->post_title).'';
}
$output .= '';
echo $output;
Wordpress CSM has a very good class to work with db, i think the better bet on this is learn how db connects and get data from mysql

Help Importing an Excel File into MySQL using phpMyAdmin

I am uploading Excel files (.xls) containing numeric values such as 884.557 and 731.0547 into a MySQL database using phpMyAdmin's built-in Import function. However, I am having horrible rounding/truncation issues. For some reason, some values like 884.557 and 731.0547 are changed to 99.99999 or 9.99999. However, other values like 127.0947 are imported correctly. Can anyone help? If possible, I would still like to use the built-in phpMyAdmin Import function because it is useful.
If you are familiar with html and php, by using this script simplex excel library you can create your own excel import to mysql. It may take few minutes to create but once your create you can use it for life time.
CREATE A HTML FORM TO UPLOAD EXCEL SHEET
THEN CREATE A PHP SCRIPT LIKE BELOW
require 'simplexlsx.class.php';
if (isset($_FILES['Filedata'])) {
$file = $_FILES['Filedata']['tmp_name']; // UPLOADED EXCEL FILE
$xlsx = new SimpleXLSX($file);
list($cols, $rows) = $xlsx->dimension();
foreach( $xlsx->rows() as $k => $r) { // LOOP THROUGH EXCEL WORKSHEET
$q = "INSERT INTO TABLENAME(COL1, COL2) VALUE(";
$q .= "'".mysql_escape_string($r[0])."', "; // EXCEL DATA
$q .= "'".mysql_escape_string($r[1])."', "; // EXCEL DATA
$q .= ")";
$sql = mysql_query($q);
} // IF ENDS HERE
} // FOR EACH LOOP
}
This is what i normally do:
Save the excel file as CSV format
I will manually create the database table by indicating the data-types for every column of my interest.
I will upload the csv file to the selected table by ignoring the "column names" as i have defined it at step 2. Decimals are truncated because phpmyadmin has some unexplained algorithm to determine the data type and the size allocated to a column. To prevent that, you create the table as mentioned above at step 2.
Hope it helps!