mysql – connection example

Mysql is a database, and to gain access to the data within C++ you will need to be able to “talk” to the database via queries (just like on the mysql command line interface e.g. select * from tablename), the connection process is very similar to the command line interface you will need to supply connection details as in hostname (localhost normally), username, password, database to use and also there are other details that you can pass e.g port number more information can be gained from the MYSQL API pages

To start with I created a struct that will hold the username, host etc details.

struct connection_details
{
    char *server;
    char *user;
    char *password;
    char *database;
};

In essence to connect to a database I have created a function that will connect and return a MYSQL pointer to the new connection using the structure above connection_details.

MYSQL* mysql_connection_setup(struct connection_details mysql_details)
{
     // first of all create a mysql instance and initialize the variables within
    MYSQL *connection = mysql_init(NULL);
 
    // connect to the database with the details attached.
    if (!mysql_real_connect(connection,mysql_details.server, mysql_details.user, mysql_details.password, mysql_details.database, 0, NULL, 0)) {
      printf("Conection error : %s\n", mysql_error(connection));
      exit(1);
    }
    return connection;
}

That is it, you are connected now, now you can perform some sql queries, once again I have created a function to accomplish this and it returns a MYSQL_RES (mysql result pointer)

MYSQL_RES* mysql_perform_query(MYSQL *connection, char *sql_query)
{
   // send the query to the database
   if (mysql_query(connection, sql_query))
   {
      printf("MySQL query error : %s\n", mysql_error(connection));
      exit(1);
   }
 
   return mysql_use_result(connection);
}

since you are now connected and also preformed a query, lets say the query was

SHOW TABLES;

You can traverse the results with a while loop in C++ and use the mysql_fetch_row function from within the mysql library set where a row is a type of MYSQL_ROW.

MYSQL_ROW row;
  while ((row = mysql_fetch_row(res)) !=NULL)
      printf("%s\n", row[0]);

Here is the full code that will display all of the tables within the mysql database database, you will need to alter the username and password for the mysql access details.

#include <mysql.h>
#include <stdio.h>
#include <stdlib.h>
 
// just going to input the general details and not the port numbers
struct connection_details
{
    char *server;
    char *user;
    char *password;
    char *database;
};
 
MYSQL* mysql_connection_setup(struct connection_details mysql_details)
{
     // first of all create a mysql instance and initialize the variables within
    MYSQL *connection = mysql_init(NULL);
 
    // connect to the database with the details attached.
    if (!mysql_real_connect(connection,mysql_details.server, mysql_details.user, mysql_details.password, mysql_details.database, 0, NULL, 0)) {
      printf("Conection error : %s\n", mysql_error(connection));
      exit(1);
    }
    return connection;
}
 
MYSQL_RES* mysql_perform_query(MYSQL *connection, char *sql_query)
{
   // send the query to the database
   if (mysql_query(connection, sql_query))
   {
      printf("MySQL query error : %s\n", mysql_error(connection));
      exit(1);
   }
 
   return mysql_use_result(connection);
}
 
int main()
{
  MYSQL *conn;		// the connection
  MYSQL_RES *res;	// the results
  MYSQL_ROW row;	// the results row (line by line)
 
  struct connection_details mysqlD;
  mysqlD.server = "localhost";  // where the mysql database is
  mysqlD.user = "mysqlusername";		// the root user of mysql	
  mysqlD.password = "mysqlpassword"; // the password of the root user in mysql
  mysqlD.database = "mysql";	// the databse to pick
 
  // connect to the mysql database
  conn = mysql_connection_setup(mysqlD);
 
  // assign the results return to the MYSQL_RES pointer
  res = mysql_perform_query(conn, "show tables");
 
  printf("MySQL Tables in mysql database:\n");
  while ((row = mysql_fetch_row(res)) !=NULL)
      printf("%s\n", row[0]);
 
  /* clean up the database result set */
  mysql_free_result(res);
  /* clean up the database link */
  mysql_close(conn);
 
  return 0;
}

To compile up this program you will need to link to the mysql libraries and headers that are used within the program, e.g. mysql.h at the top of the program. To gain access to these, there is a nice mysql_config (you may need to install it via your package manager system if you do not have it already).

Here are my outputs of what is required on the command line for the g++ compiler

mysql_config --cflags
-I/usr/include/mysql  -DBIG_JOINS=1  -fno-strict-aliasing   -DUNIV_LINUX
mysql_config --libs
-Wl,-Bsymbolic-functions -rdynamic -L/usr/lib/mysql -lmysqlclient

These are the g++/c++ switches that tell the compiler where the libraries (-L) are and the headers (-I) and to insert into the g++/c++ compiler line within linux you can do something like

g++ -o mysqlconnect $(mysql_config --cflags) mysqlconnect.cpp $(mysql_config --libs)

Where the mysqlconnect.cpp is the c++ file of the above program and the output would be

./mysqlconnect
MySQL Tables in mysql database:
columns_priv
db
event
func
general_log
help_category
help_keyword
help_relation
help_topic
host
ndb_binlog_index
plugin
proc
procs_priv
servers
slow_log
tables_priv
time_zone
time_zone_leap_second
time_zone_name
time_zone_transition
time_zone_transition_type
user

Equals why ? and why not ==

In Object oriented programming languages, there is a nice keyword that is “new” what this does is create a new instance of a object and run the objects constructor method and setup up the internal variables, for example.

class classA 
{
	private int x;
 	public	classA() { x= 0;}
	public	classA(int value) { x = value;}
}
...
classA a = new classA();

this will create a new instance of A with the constructor (same name as the class) setting x equal to 0. What is happening is that the variable “a” is pointing to a memory location of the newly created object on the memory heap for example.

Local variables

Object Memory location / value
a 0x0102

which the 0x0102 memory location is pointing to a newly constructed classA space

Memory location Object values
0x0102 classA – a instance over head (garage collection etc)
0x0104 x value 0

There is over head details associated with the classA (a instance) for the garage collection/polymorphism for example. So the actual “a” variable is just pointing to this place in memory, if you created a new classA instance then another place in memory will be created, for example lets create classA a2 as

classA a2 = new classA();

and now a example of the memory locations / values would be similar to

Local variables

Object Memory location / value
a 0x0102
a2 0x0108

with the memory heap as such.

Memory location Object values
0x0102 classA – a instance over head (garage collection etc)
0x0104 x value 0
0x0108 classA – a2 instance over head (garage collection etc)
0x010a x value 0

so you would have thought that if you did,

if (a == a2)

then they would be equal, since both have a value of 0 ? well this is not the case, since the == is just comparing the value within the variable and thus the a = 0x0102 and a2 = 0x0108 which are not equal. To compare two different instances of a class you need to override the Equals function within the class (all classes are derived from object class)

So the code would be

		// override the inhertant object object Equals function
		public override bool Equals(object obj)
		{
			// cast the obj into a classA and then compare the x values
			if (x == ((classA)obj).x)
				return true;
			else
				return false;
		}

and now you can compare the two classA instances with

if (a.Equals(a2))

since the Equals function is actually comparing the values within the class instance and not the a/a2 variable values (which point to memory locations).

Here is the full code

using System;
 
namespace equaltest
{
	class classA 
	{
		private int x;
	 	public	classA() { x= 0;}
		public	classA(int value) { x = value;}
 
		public int xValue {
			get { return x;}
			set { x = value;}
		}
 
		// override the inhertant object object Equals function
		public override bool Equals(object obj)
		{
			// cast the obj into a classA and then compare the x values
			if (x == ((classA)obj).x)
				return true;
			else
				return false;
		}
	}
 
	class MainClass
	{
		public static void Main(string[] args)
		{
			classA a = new classA();
			a.xValue = 10;
			Console.WriteLine("A x value = " + a.xValue);
 
			classA a2 = new classA();
			a2.xValue = 10;
			Console.WriteLine("A2 x value = " +a2.xValue);
			//so they are the same in x values, but are they the same !! ==
 
			if (a == a2)
				Console.WriteLine("a does equal a2");
			else
				Console.WriteLine("a does not equal a2");
 
			// of course they are NOT the same value, because the equals is comparing there actual object values
			// and not there x value inside them, and with the "new" keyword they are both pointing to different 
			// places on the heap of storage, thus they are NOT the same..
			// a may equal heap storage = 0x1010
			// a2 may equal heap storage= 0x1020
			// both have the same x value but different memory location values.
 
			// but implementing a Eqauls comparsion function you can compare the two variables internals 
			// as you see fit.
			if (a.Equals(a2))
				Console.WriteLine("a does equal a2");
			else
				Console.WriteLine("a does not equal a2");
 
		}
	}
}

and the output would be

A x value = 10
A2 x value = 10
a does not equal a2
a does equal a2

since I am overriding the Equals from the base object class, the compiler may warn that I am not overriding the GetHaseCode(), but that is k for this example.

Example of the compiler warning message

Description=`equaltest.classA' overrides Object.Equals(object) but does not override Object.GetHashCode()(CS0659)]

Alter img (image) tag – on click

With javascript you can do allot of fun things that a static page, in this example I am going to use the getDocumentID to obtain a image (img) HTML tag, and whilst I have this as a javascript object I can then alter the src image details.

I have created a “a” href HTML tag that will not go anywhere, but I am using the onclick javascript method to call the javascript function which references the id name within the img HTML tag.

  <a onclick="javascript:alterImg()">Alter Image</a>
  <img src="pic1.jpg" width="250" height="350" id="imagesrc"/>

and within the alterImg javascript function, getting the image (img HTML tag) via the ID

  function alterImg()
  {
    // get the element img into the imgobject variable
    var imgobject = document.getElementById('imagesrc');
    // change the src of the image to the other image to display.
    imgobject.src = pictureImage;
    // change the image to the other image.
    if (pictureImage == "pic2.jpg") 
      pictureImage = "pic1.jpg";
    else
      pictureImage = "pic2.jpg";
  }

Here is the full code and if you save the below as changeimage.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<script language="javascript">
  var pictureImage = "pic2.jpg";
  function alterImg()
  {
    // get the element img into the imgobject variable
    var imgobject = document.getElementById('imagesrc');
    // change the src of the image to the other image to display.
    imgobject.src = pictureImage;
    // change the image to the other image.
    if (pictureImage == "pic2.jpg") 
      pictureImage = "pic1.jpg";
    else
      pictureImage = "pic2.jpg";
  }
</script>
<body onload="alterImagenow()">
  <a onclick="javascript:alterImg()">Alter Image</a>
  <img src="pic1.jpg" width="250" height="350" id="imagesrc"/>
</body>
</html>

The output would be this.. click on “Alter Image”.


Alter Image

You can save the images by selecting the image and right clicking save as..

WordPress – plugin – hello world

WordPress is a blogging software that runs on a webserver, the great thing about wordpress is that you are able to extend the functions to create the pages/comments/archives etc on the blogging site. You are also able to create your own themes that will use the functions that you can create within that theme So lets it straight, a plugin for the wordpress is the way that you can extend the functional aspects of the whole site that is not dependent on the theme that you using (a theme is what you view on the web page the “style” (css) of the site for example).

There is two main directories within the wordpress directory structure to add in new themes (wp-content/themes) and the plugins (wp-content/plugins) this is where you place the code to extend the basic wordpress install.

In this example I going to extend the action get_header, if you save the code below into the directory wp-content/plugins/codingfriends_helloworld as codingfriends_helloworld.php

<?php
/*
Plugin Name: Coding friends hello world
Plugin URI: http://www.codingfriends.com/
Description: Outputs hello world
Version: 0.1
Author: Genux
Author URI: http://www.codingfriends.com
License: GPL2
*/
 
function codingfriends_helloworld()
{
  echo "hello world";
}
 
add_action('get_header', 'codingfriends_helloworld');
?>

once you have saved that file, then goto your wordpress admin page, on the left is the Plugins link, click on that and within there will be the “new” plugin called coding friends hello world, you just need to activate it and then hey presto it works. There will be “hello world” at the top of the wordpress installed pages within the main site (not the wp-admin part of the site).

What is happening is that you have created a function called codingfriends_hellworld, which outputs “hello world”, but the main part is the

add_action

this will add this function to a defined plugin action (to get a list of all of the actions (these happen within the core site), and filters (alter text within the site, e.g. pages that you add to the site, comments etc) you can use look here).

So when the action get_header is called within the main wordpress application, it will call your new function (codingfriends_helloworld).

There is tons of things that you can do with these, alter the comments when posted back to the site, pages etc, just look at the API list.

Method adding two numbers

Method programming with C++ is a way to save time when you need to redo same/similar code, and also it allows for clearer code because when you read the code you can tell what is happening instead of just having the same code over and over again within the main method of the program.

To declare a method within c++ there is syntax for the way that a method is defined.

[return type] methodname(parameters if required...)

So for example if you want to pass in two integer variables and then to return a integer variable (the function could add the parameters together so shall we call it addTwoNumbers,

int addTwoNumbers(int value1, int value2);

this means that the return value is a int (integer), you “call” the method by its name (addTwoNumbers) and pass in local variables to the method in the parameters (value1 and value2).

Here is a full c++ code example that will read in two values from the keyboard and output the result to the screen.

#include <iostream>
#include <exception>
#include <stdio.h>
 
//using the namespace std (standard) for the cin -> console input
using namespace std;       
 
int addTwoNumbers(int val1, int val2)
{
    return (val1 + val2);
}
 
int main()
{
       // setup the defaul values.
       int val1 =0, val2 =0;
       try 
       {
              // output to the console
              printf("Please enter number 1 : ");
              // read in the input, if not a integer value, this will
              // cause a error 
              cin >> val1;       
              printf("Please enter number 2 : ");
              cin >> val2;
       }
       catch (exception& e)
       {
              // write out any error exception
              printf("Not a valid input %s\n", e.what());
       }
       // output the answer of the two inputted values.
       printf("Answer : %d\n", addTwoNumbers(val1, val2));
       return 0;
}

and here is the output

Please enter number 1 : 20
Please enter number 2 : 10
Answer : 30

Library of your own – object file.

Sometimes you want to have a library of your functions within one object file that you can use for other applications without having to re-compile and import each time to each project.

Well, if you create a object of the list of functions because a object file is the intermediate between code and linking (to create the executable file), but with this object file you will need to have created a header file (.h) that will allow the projects to know what functions are within the object file and how to call them. So to start with here is the header file (I have called it libraryHelloWorld.h)

#include <iostream>
 
using namespace std;
 
void SayHelloWorld();
void SayWord(std::string st);

It just defines the two functions that I have written, and here are the implementation of the two functions above.

#include "libraryHelloWorld.h"
#include <iostream>
 
using namespace std;
 
void SayHelloWorld()
{
    cout << "Hello World" << endl;
}
 
void SayWord(string st)
{
    cout << "Line is \"" << st << "\"" << endl;
}

if you save that as libraryHelloWorld.cpp, if you notice that at the top I am including the header file to this cpp file because the header files normally have a class definition inside them and also struct’s etc, which the functions within the cpp file may require.

To compile up, to create the object file you just need to do

g++ libraryHelloWorld.cpp -c

which basically means (-c) just compile and do not link, this will create a libraryHelloWorld.o file (the object file).

To make use of this object file, you just need to add in the header file to your project and then call the functions as though you have re-written them within your new project, like so.

#include "libraryHelloWorld.h"
 
int main()
{
  SayHelloWorld();
  SayWord("Genux is great");
  return 0;
}

Then the main part, which is including the object file created before into the linking part of the computation of this program. (save the above as callHelloWorld.cpp)

g++ callHelloWorld.cpp libraryHelloWorld.o -o callHelloWorld

the above includes the object file, libraryHelloWorld and after the linking part of the compilers job, the output file name (-o) will be callHelloWorld.

This just saves allot of time when you are coding, try to keep different projects having similar libraries that you know and trust to work.

Blob to store data in mysql database

To store data within a blob in a database can be a good thing at times because then you can just copy the database from one place to another and use the access rights on the database to restrict access to the “files” within the database.

There could be a few reasons why you want to store the data within a blob in the database, but here how the basics would work.

To start with you have to create a database and a table to store the data/file within the blob, of course if you have already created the database and/or the tables then alter as you think, but here is the basics.

  CREATE DATABASE phptestplace;
  CREATE TABLE storingData (id INT NOT NULL auto_incremenet, lblob BLOB, PRIMARY KEY (id));

And then within a php file you can access the database and a file.

  $link = mysql_connect('localhost', 'username', 'userpassword');
  if (!$link) {
      die('Could not connect: ' . mysql_error());
  }
// alter to your database name
  mysql_select_db("phptestplace", $link);

and now access the file and read in file

  $filename = "filetoload.txt";
  $handle = fopen($filename, "r");
  $contents = fread($handle, filesize($filename));
  fclose($handle);
 
// to insert into the database you need to add in the slashes for characters like / \ etc.
  $contents = addslashes($contents);

to insert into the blob you just, change the table and table name to what may have called it.

  $sqlquery = "insert into storingData(largeblob) values ('$contents')";
  mysql_query($sqlquery) or die("ERROR");*/

to get the data back (I am calling back the last inserted value into the table)

// get the data into a result variable
  $return = mysql_query ("select lblob from storingData where id = (select max(id) from storingData)") or die("LLL");
// get the contents of the blob from the return variable (it returns a array of data) and the list takes out the data from a array each part at time.
  list($newcontents) = mysql_fetch_array($return);

and then store the data from the database pull into a file, I have called it newfile.txt, but it is up to you.

  $fp = fopen('NEWFILE.txt', 'w');
  fwrite($fp, $newcontents);
  fclose($fp);

Of course can do it via a web page, using a HTML FORM enctype=”multipart/form-data” within the form tag otherwise it may not work.