Archive for the ‘SQL’ Category

Connect to MSSQL 2005 using PHP

Here’s a couple of quick tips to connecting to a MSSQL 2005 server using PHP on a Windows webserver. You will need to enable the php_mssql.dll in your php.ini file.

Here’s the code to connect to the server.

<?php

$conn = mssql_connect(‘my_server’, ‘db_username’, ‘db_password’);
if (!$conn) { die(‘ERROR: Unable to connect to the database.’); }
mssql_select_db(‘database_name’);

?>

Here is a helpful function I found that will help escape strings. I found this at http://stackoverflow.com/questions/574805/how-to-escape-strings-in-mssql-using-php.

<?php

function ms_escape_string($data) {
//if ( !isset($data) or empty($data) ) return ”;
if ( !isset($data) or empty($data) ) return “””;         // modified to handle empty $data
if ( is_numeric($data) ) return $data;

$non_displayables = array(
‘/%0[0-8bcef]/’, // url encoded 00-08, 11, 12, 14, 15
‘/%1[0-9a-f]/’, // url encoded 16-31
‘/[\x00-\x08]/’, // 00-08
‘/\x0b/’, // 11
‘/\x0c/’, // 12
‘/[\x0e-\x1f]/’ // 14-31
);
foreach ( $non_displayables as $regex )
$data = preg_replace( $regex, ”, $data );
$data = str_replace(“‘”, “””, $data );
//return $data;
return “‘”.$data.”‘”;        // modified to handle empty $data
}

?>

Here is a sample query to the database.

<?php

$id = ms_escape_string($_GET['id']);    // escape variable
$sql = ‘SELECT id FROM table_name WHERE id=’.$id.”;
$rs = mssql_query($sql);

if (!$rs)
{
echo ‘ERROR: Unable to get records. ‘.mssql_get_last_message();    // equivalent to mysql_error()
}else{
while ($row = mssql_fetch_assoc($rs))
{
echo ‘The id = ‘.$row['id'].’<br />’;
}
}

?>

Another thing I learned from the article is the equivalent of “mysql_insert_id()”. It is “SELECT @@IDENTITY”. To handle dates and make them friendly to PHP use CONVERT(VARCHAR, [date], 20). This will display it as if you are using date(‘Y-m-d H:i:s) – 24 hour format. So an example would be…

SELECT CONVERT(VARCHAR, getdate(), 20) AS now

I tried to use PDO but was having a hard time getting it to work. I kept getting errors that had something to do with functions. I searched for solutions and tried them but none worked for me. Also, the rowCount() will always return less than or equal to 0.

I had trouble on both sides PHP and Microsoft. This seems to be the best solution that works for me. Hope it helps others.

  • Share/Bookmark

Using PEAR Pager with PHP PDO

This post will be addressing 2 things.

  1. How to use PEAR’s Pager class with PHP PDO
  2. Addressing PDO bug #44639 (http://bugs.php.net/bug.php?id=44639)

Two queries will be used for this task. The first query, you will count the rows of the recordset. The second query is the same as the first but it will have the LIMIT – this is what will be used to display the data on each page.

Let’s say we have the following table.

CREATE TABLE IF NOT EXISTS`blog`
(
`blog_id` int(11) not null auto_increment,
`blog_text` varchar(4000) not null default ”,
PRIMARY KEY `pk_blog_id` (`blog_id`)
) ENGINE=INNODB;

Now we’ll query the database and get the row count using PDO.

<?php

require_once(‘file-with-pdo-db-connection.php’);

$sql = “SELECT * FROM `blog`”;
$stmt = $dbh->prepare($sql);

if ($stmt->execute())
{
// begin pager
require_once(‘Pager/Pager.php’);
$params = array
(
‘totalItems’ => $stmt->rowCount,
‘perPage’ => 10,
‘delta’ => 5,
‘mode’ => ‘Sliding’
);

$pager =& Pager::factory($params);

$links = $pager->getLinks();
echo $links['all'];

// offset setup
list($from, $to) = $pager->getOffsetByPageId();
$from = $from – 1;
$perPage = $params['perPage'];

// 2nd query based on 1st with LIMIT – this will be displaying data per page
$stmt2 = $db->prepare($sql.’ LIMIT :from, :perPage’);

// address bug 44639 – forces the variables to have the property of integer instead of string so no quotes will surround it
$stmt2->bindValue(‘:from’, $from, PDO::PARAM_INT);
$stmt2->bindValue(‘:perPage’, $perPage, PDO::PARAM_INT);
$stmt2->execute();

while ($row_blog = $stmt2->fetch())
{
echo ‘<div>’.$row_blog['blog_text'].’</div>’;
}

}

$dbh = null;

?>

If you don’t use the bindValue, you will get an error in your query. Your second query would look something like this… SELECT * FROM `blog` LIMIT ’0′, ’10′ and the error would occur right after LIMIT. You cannot have quotes surrounding the numbers. It took a few hours of Googling but found the solution.

If you want to read more about PEAR Pager, visit http://pear.php.net/package/Pager/docs.

Here’s a tutorial I found that helped me out a lot – http://www.codediesel.com/php/simple-pagination-in-php/.

  • Share/Bookmark

MSSQL Stored Procedures and Classic ASP

A client at work wanted us to create a way to duplicate existing records on their website with a click of a button. These records involve multiple tables in the database. Some of the tables contained a lot of columns. We tried to do most of work using ASP but sometimes the browser would time out and Dreamweaver would crash.

Then I thought, why don’t we have our SQL server do most of the heavy lifting. I created a stored procedure that query the database for the record(s) that need to be duplicated and have them duplicated. Below is a short example to get you started.

First you need to create a stored procedure in SQL Server.

CREATE PROCEDURE stored_procedure_sample
@record_id INT OUTPUT

AS
BEGIN

INSERT INTO table_name (column1, column2, column3)
SELECT column1, column2, column3
FROM table_name
WHERE record_id = @record_id

END;

GO

Next you need to create the ASP page that process the request. You can use form variable or URL query string. For the example, I will use a form variable. Let’s imagine on page1.asp there is a form with a hidden variable that contains the record_id you want to duplicate. You submit this to page2.asp and here’s a sample of what page2.asp should look like.

<%

Dim connString, rsCmd

connString = “your connection string”
Set rsCmd  = Server.CreateObject(“ADODB.Command”)
rsCmd.ActiveConnection = connString
rsCmd.CommandType = 4
rsCmd.CommandText = “stored_procedure_sample”

rsCmd.Parameters.Append rsCmd.CreateParameter(“@record_id”, 200, 1, 4, Request.Form(“record_id”))

rsCmd.Execute

%>

What page2.asp does is it takes the form variable “record_id” from page1.asp and tells the stored procedure to get the values for this record and insert it as a new record. That’s pretty much it. Just a short, simple example on how you can create a stored procedure in MSSQL Server and use it with classic ASP.

  • Share/Bookmark

Allowing network connections to MySQL in OS X Leopard Server

For the past couple of days I’ve been trying to set up one of our XServe running Leopard Server at work for web hosting. I was able to configure the Web, AFP, and SMB properly. The problem I was having was configuring MySQL. It was easy to enable but trying to connect to it from other computers in the same domain was the problem. There’s a checkbox with “Allow network connections” in the Server Admin section of MySQL. So I checked it, save, and restarted it. I still wasn’t able to connect. I checked for firewall settings. I pinged the host and got a response. I couldn’t figure out what was wrong. So I googled it.

The common answer I found was to edit the /etc/mysql/my.cnf file. Well it’s not there but I did find a /etc/my.cnf file. So I tried editing that file and restarting. It didn’t work.

Then I remembered that the php.ini file that Leopard Server is using isn’t in the default location /etc/php.ini, but it ran the /private/etc/php.ini. So I looked in there and found another my.cnf file. I edited the file by adding # in front of skip-networking entry. I restarted it and it finally worked.

So here’s what you need to do:

  • Go into Server Admin and check the Allow network connections and save
  • Comment out the skip-networking entry from /private/etc/my.cnf
  • Add the IP address of the computer you will be accessing MySQL remotely
  • Give it the privileges it needs
  • Restart MySQL

That should allow you to connect to MySQL running on Leopard Server remotely.

  • Share/Bookmark

MySQL backup and restore databases with views

We recently installed OS X Leopard Server at work. I had to take MySQL databases from our old Tiger Server and restore them onto the new XServes. Both servers are running MySQL Server version 5.0.45 but our Tiger server is running MySQL Client version 5.0.22 while our Leopard servers are running MySQL Client version 5.1.18. According to MySQL’s documentation (http://dev.mysql.com/doc/refman/5.0/en/mysqldump.html):

Prior to release 5.0.48, this option did not create valid SQL if the database dump contained views. The recreation of views requires the creation and removal of temporary tables and this option suppressed the removal of those temporary tables. As a workaround, use --compress with the --add-drop-table option and then manually adjust the dump file.

I tried the –compress option but it didn’t work. I still had to manually adjust the SQL file. The I tried the GUI tool from MySQL, http://dev.mysql.com/downloads/gui-tools/5.0.html (MySQL Administrator).

mysql_admin.jpg

Once you create the backup, you can restore it using the same application on the newer server. It will even include the views. Once you start using the newer client, you shouldn’t have a problem restoring databases with views from backups made with the mysqldump command.

  • Share/Bookmark
Categories