Run a MySql Script from Command Line in Windows

Locate MySql.exe.  It’s probably here:

c:\mysql\bin\

Open a command prompt and type:

c:\mysql\bin\mysql.exe -h [database] -u [username] -p [scriptpath] --force

The –force switch ignores all errors the script may run into.  When you press enter, you’ll be asked for a password.  Enter the password and your script will start running.

Leave a Comment

Getting XDebug to work with PHP and Eclipse

I’m used to .net, so when I started coding in PHP, I really missed the remote debugging features that come with Visual Studio (being able to step through a web application). I was also looking for a good, free IDE.  I found the answers in eclipse and xdebug.  If your’e looking for the same thing, here are some starters:

Here are the steps to follow:

1. Download XAMPP or install and configure Apache, PHP, MySql.

Xampp is one package that installs and configures apache, php and mysql.  Very easy to set up a development environment.  Just download and run the exe specific to your  environment.

2. Download Eclipse Classic
http://www.eclipse.org/downloads/
Eclipse is an IDE (i.e. code editor on steroids).  Download and install it.  Open Eclipse.  When it asks, make your workspace the xampp directory (i.e. c:\xamp\htdocs\mysite)

3. Download PDT by following these instructions

http://wiki.eclipse.org/PDT/Installation

4. Download the xdebug dll
http://www.xdebug.org/download.php
Follow the instructions here: http://www.xdebug.org/docs/install.  The difficult thing for me was finding the right version to install and making sure that the entries in the php.ini were correct.  To test whether the correct version is installed, create a page with phpinfo.  If there’s an xdebug section, you’re good to go.

5. Instructions on putting it all together:
http://devzone.zend.com/article/2930

I hope this helps someone else.  I spent a good afternoon trying to piece all of this together.  Once you’ve gone through these steps

Leave a Comment

Create a Simple JSON Web Service with PHP and JQuery

Here’s what you need to get started creating a simple JSON Web Service with PHP and JQuery. You’ll need to download JQuery and include it in your page as I’ve done.

The HTML page just has a couple of links that are hooked up to JQuery methods which post values to a PHP page.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<html>
 
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<script src="jquery-1.3.2.js" type="text/javascript"></script>
 
<script type="text/javascript">
 
        $(document).ready(function () {  //The DOM is now loaded and can be manipulated.
 
          //Wire up the divs to do stuff whenclicked
          $("#CallAddPost").click(function () {
              callAddPost();
          });
 
 
          $("#CallMultiplyAjax").click(function () {
              callMultiplyAjax();
          });
 
          //Option1: Use JQuery Post Method. Two Parameters. First Parameter is
          //the functionName.  Second Parameter is a json-formatted string
          function callAddPost(){
                   $.post("jsontest.php",
                   {functionName: 'add',params:'{"first":8, "second":2}'},
                   function(data){
                       alert(data);
  	         }
              );
          }
 
          //Option 2: Use JQuery Ajax Method.
            function callMultiplyAjax(){
            $.ajax({
                  url: "jsontest.php",
                  global: false,
                  type: "POST",
                  data: {functionName : "multiply",params:'{"first":8, "second":2}'},
                  dataType: "html",
                  success: function(data){
                     alert(data);
                  }
               }
            );
          }
 
        });// //End Document Ready
 
</script>
 
</head>
 
<body>
    <a href="#" id="CallAddPost">Call Add Post</a>
    <a href="#" id="CallMultiplyAjax">Call Multiply Ajax</a>
</body>
 
 
</html>

The PHP Script reads the values posted from the HTML page and calls one of two methods based on which method is specified in the POST.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?php
 
function add($par) {
    $result = 0;
    //You see we can loop through the parameters irrespective of key
    foreach($par as $key=>$val) {
        $result += $val;
    }
    return array("result"=>$result);
}
 
function multiply($par) {
    //Here we reference the variables in the array by their keys
    $result = $par['first'] * $par['second'];
    return array("result"=>$result);
}
 
$postmethod = $_POST["functionName"];  //Gets the 'functionName' string value from the POSTed json
$params = $_POST["params"];    //Gets the 'params' string value from the POSTed json
 
//Turn the json string of parameters into an associative array
$params = json_decode($params,true); //true means we're creating an array (not an object)
 
$functionCall = $postmethod."(\$params);";
eval("\$retObj=".$functionCall.";");
 
//Echo sends the result back to the page
 
echo $retObj['result'];  //If I just want to return the result, I don't have to json encode it
//Otherwise, if I want to return the array, I just use the json_encode method to turn the array into JSON
?>

Here are some useful links:
http://docs.jquery.com/Ajax
http://php.net/manual/en/function.json-encode.php
http://php.net/manual/en/function.json-decode.php

Leave a Comment

Using Python with MySql and Unicode Characters

To the Point:

To insert unicode values into MySql from Python, use these two parameters:

charset = “utf8″, use_unicode = True

db = MySQLdb.connect(host=”localhost”, user=”root”, passwd=”secret”,db=”dbname”,charset = “utf8″, use_unicode = True)

Additional Information:

You may also need to change the database encoding in your MySql database to utf8.  Do something like this:

ALTER DATABASE DatabaseNameGoesHere DEFAULT CHARACTER SET UTF8;

Leave a Comment

Free Experts Exchange Membership — Just scroll to the bottom :)

Ever been looking for an answer to a question on google to find that the only relevant question/answer is on ExpertsExchange?  Want a free membership to the site?  The great thing is that all the answers are there.  Just scroll down to the VERY bottom of the page and you’ll be able to see all the answers they try to get you to pay for.

Leave a Comment

Insert Unicode Chinese Characters into SQL Server

Problem: Insert Chinese characters (or other Unicode) into SQL Server (or SQL Server Express).  The characters are inserted as question marks.  What gives?

Solution:

Instead of this: insert into table(field) values (’惨’)

Do this:  insert into table(field) values (N’惨’)

Just use the N prefix on any unicode field and it should work.

Source:http://www.experts-exchange.com/Microsoft/Development/MS-SQL-Server/Q_21699281.html (just scroll down to the bottom)

Leave a Comment

Create a Simple XML Document

Here’s how you can create a simple XML document in .net without saving it first to a file.  This lets you create an xml document in memory and do what you want with it.

Imports System.Xml
 
...
 
'Create StringWriter to write the xml return string
Dim sw As System.IO.StringWriter = New System.IO.StringWriter
Dim writer As XmlTextWriter = New XmlTextWriter(sw)
 
writer.WriteStartDocument()
writer.WriteStartElement("Movies")
 
writer.WriteStartElement("Movie")
writer.WriteAttributeString("name", "Forrest Gump")
writer.WriteStartElement("Actors")
writer.WriteStartElement("Actor")
writer.WriteAttributeString("name", "Tom Hanks")
writer.WriteEndElement() 'End Actor
writer.WriteStartElement("Actor")
writer.WriteAttributeString("name", "Gary Sinise")
writer.WriteEndElement() 'End Actor
writer.WriteEndElement() 'End Actors
writer.WriteEndElement() 'End Movie
 
writer.WriteEndElement() 'End Movies
writer.WriteEndDocument()
writer.Close()
 
Return sw.ToString()

This code returns the following XML string:

Leave a Comment

Free Skateboard Videos from Element

100+ short skateboard videos can be found at the Element Skateboards Video Podcast page.  You can also subscribe to the podcast on iTunes.

Leave a Comment

Pop-Up Translator & Dual-language Chinese Newspaper

You can quickly and easily learn to read Chinese newspapers with a dual-language newspaper and a pop-up dictionary.

I’ve just started using this chinese pop-up translator. I’ve been using it to read:

I like the Wall Street Journal one the best because some of the articles are available in English and Chinese. Some of them are not dual language, but many are (see screenshot below). This dual-language newspaper in English and Chinese is very useful.

This is a screen-shot of an article that has the English translation.

Anybody know of other useful tools for reading Chinese online?

Leave a Comment

Using ASP.NET DataSources Without TableAdapters

You don’t have to use TableAdapters to use some of the advantages of strongly-typed DataSets and declarative DataSources.  In fact, leaving out table adapters can make your code more flexible, and frees you from some of the TableAdapter’s awkward behavior.

If you’re not familiar with typed datasets and table adapters, take a look at these tutorials.  Here’s what I did to avoid using TableAdapters while still taking advantage of BLLs and declarative DataSources.

1. Created a blank dataset called CustomDataSet. Added a blank table to the dataset, and then added columns to that table.

Add DataTable to the DataSet

Add DataTable to the DataSet

2. Created a Business Logic Layer (BLL), and put the results of my executed command into the table I created in step 1.

'I'm using the Oracle Data Provider, not the Microsoft one, but you can use whatever gets you connected to the db
Imports System.Data
Imports Oracle.DataAccess.Client
Imports Oracle.DataAccess.Types
 
Imports CustomDataSet  'Reference the custom dataset we just created
 
 _
Public Class aBLL
     _
    Public Function getStuff() As CustomDataTable  'Reference the CustomDataTable we created
 
        'Create a connection to the db
 
        'Create a command (called cmd is my case)
 
        'Create a data adapter, which we use to move data from my database to the table
        Dim MyDA As New OracleDataAdapter
 
        'Create an instance of the CustomDataSet
        Dim ds As CustomDataSet = New CustomDataSet
 
        'Put your command results into the table we created
        MyDA.SelectCommand = cmd
        MyDA.Fill(CustomDataTable)
        Return ds.CustomDataTable
    End Function
End Class

3. Then all you’ve got to do is create an Object DataSource in the .aspx page, and link that datasource to your datagrid.

I’ve also found this to be a lot more flexible than having to work with table adapters–which I think are too complicated and restrictive. This way, I get to create the code like I want it and still take advantage of some of the cool stuff .net offers.

Leave a Comment

Create and Send CSV Without Saving File to a Drive

You want to dynamically create a CSV file and make it available for download for your user.  But you don’t want to save the file to the drive.  You just want to create the file on the fly, send it to the user, and let it evaporate into thin air after it’s downloaded.  You can do that using a memorystream and streamwriter.

In this example, I take a datagrid, write its contents to a bytearray, and then send the array to the user as an http response.

Dim mstream As MemoryStream = New MemoryStream()
Dim writer As StreamWriter = New StreamWriter(mstream)
 
Dim Str As String
Dim i As Integer
Dim j As Integer
 
Dim headertext As String = "Col1,Col2,Col3"
writer.WriteLine(headertext)
For i = 0 To (Me.GridView1.Rows.Count - 1)
    For j = 0 To (Me.GridView1.Columns.Count - 1)
 
        'this IF statement stops it from adding a comma afterthe last field
        If j = (Me.GridView1.Columns.Count - 1) Then
            Str = (Me.GridView1.Rows(i).Cells(j).Text.ToString)
        Else
            Str = (Me.GridView1.Rows(i).Cells(j).Text.ToString &amp; ",")
        End If
 
        writer.Write(Str)
    Next
    writer.WriteLine()
Next
 
writer.Flush()
writer.Close()
 
Dim byteArray As Byte() = mstream.ToArray()
 
mstream.Flush()
mstream.Close()
 
Response.Clear()
Response.AddHeader("Content-Disposition", "attachment; filename=aFile.csv")
Response.AddHeader("Content-Length", byteArray.Length.ToString())
Response.ContentType = "application/octet-stream"
Response.BinaryWrite(byteArray)
Response.Flush()
Response.Close()

Leave a Comment