James Ibrahimov James Ibrahimov - 3 years ago 106
MySQL Question

Code wordpress Plugin to save to Mysql Database

Whats the best way to create a wordpress plugin. I have started out learning to make plugins and i want to make a plugin to calculate 2 numbrs and save to a mysql database.

since i didnt know OOP in PHP i decided to code what i know.

my code looks like this only my instructor wants me to do something Awesome.. better than what i coded earlier.

Code looks like this

<?php

/*
Plugin Name: Addition Plugin
Description: Plugin to Add to Database and call back from database
Author: James Ibraimov
*/


function add_twoNumberssavetoDB(){

$num1 = '8';
$num2 = '3';
$ans = $num1 + $num2;


$host = '127.0.0.1';
$user = 'root';
$pass = '';
$db = 'wordpress_tut';

$con = new mysqli ($host, $user, $pass, $db) or die ('Bad connection : '.mysqli_error());
$sql = "insert into tut1 (num3) values ('".$ans."')";
mysqli_result($con,$sql)or die ('Bad Query : '.mysqli_error());
mysqli_close($con);

}

add_action('admin_menu','add_twoNumberssavetoDB');

function displayResultsFromDB()
{
$host = '127.0.0.1';
$user = 'root';
$pass = '';
$db = 'wordpress_tut';

$con = new mysqli($host, $user, $pass, $db) or die ('Bad connection : '.mysqli_error());
$sql = 'select * from tut1';
$result = mysqli_result($con, $sql) or die ('Bad Query: '.mysqli_error($con));
while( $row = mysqli_fetch_array( $result, MYSQLI_ASSOC ) ){

$row['id']." ".$row['num3'];
"</pre>";
}


}

add_action('admin_menu','displayResultsFromDB');

?>

Answer Source

you are using php for inserting dta into database. use wordpress functions to insert data into data.

change
$host = '127.0.0.1';
$user = 'root';
$pass = '';
$db = 'wordpress_tut';
to
 global $wpdb; 

use this to insert your data
$wpdb->insert( 
    'table_name', 
    array( 
        'column1' => 'value1', 
        'column2' => 123 
    ), 
    array( 
        '%s', 
        '%d' 
    ) 
);

for more information how to insert or get data click here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download