Nov 09 2009

Stop UTF8 problems with special characters

Category: MySql,PhpGiulio Pons @ 4:04 pm

I’m italian and I always need to use special chars like è é à ù. The same need belongs to french developers, and many other non-english developers. To use special chars without encoding problems try to follow this 4 rules:

  1. create fields on db with utf8_general_ci collation
  2. make the query ‘set names’ after any connection (look the block code below, you need mysql 5)
  3. put meta charset utf8 tag in the html head block
  4. read and write strings to db and to html without using utf8_encode or other functions
  //after connecting to your db make this query:
  mysql_query("SET NAMES 'utf8';");

NOTE (added on 2010-02-16)
Sometimes these steps do not work, and you start say f**ck f**ck! Well, it’s also happened to me, and I’ve notice that sometimes php.ini make some problems because it has a wrong default charset setted. So, if this is your problem, put this line at the beginning of your php files:

ini_set('default_charset', 'UTF-8');
Share

Tags: , , ,


Nov 09 2009

Execute Scalar and Execute Row for Php

Category: MySql,PhpGiulio Pons @ 3:36 pm

A couple of simple functions thar returns the first value and the first row of a result set.

Very usefull.

Need the connection to be opened.


$user = execute_row("select * from user where id='23'");
$value = execute_scalar("select name from users where id='23'");

// $user['name'] is the same of $value;

function execute_scalar($sql,$def="") {
	$rs = mysql_query($sql) or die("bad query");
	if (mysql_num_rows($rs)) {
		$r = mysql_fetch_row($rs);
		mysql_free_result($rs);
		return $r[0];
		mysql_free_result($rs);
	}
	return $def;
}

function execute_row($sql) {
	$rs = mysql_query($sql) or die("bad query");
	if (mysql_num_rows($rs)) {
		$r = mysql_fetch_array($rs);
		mysql_free_result($rs);
		return $r;
	}
	mysql_free_result($rs);
	return "";
}
Share

Tags:


« Previous Page