So I'm trying my hand at creating php methods from scratch. My classes aren't exactly classes yet, I'm still working on that. Anyway, my issue's I can't seem to get the values I expect from my database. Here's a snippet of my code:
file1.php
<?php function dbConnect() {
$connection = mysqli_connect("localhost", "music_root", "", "music");
if($connection->connect_error) {
return null;
}
return $connection;}
function getCategory() {
$cn = dbConnect();
if($cn == null) {
echo "Failed to connect to database.";
} else {
$fetchQuery = mysqli_query($cn, "SELECT * FROM tbl1 ORDER BY 'Name'") or die(mysqli_error($cn));
if(mysqli_num_rows($fetchQuery) > 0) {
while($item = mysqli_fetch_array($fetchQuery)) {
return $item["Name"];
}
}
}} ?>
Here's the snippet of how I call the above method in file2.php
<?php ini_set("display_errors", 1);
include_once("file1.php");
$con = dbConnect();
$updateStat = false; ?>
<div>
<label>Genre</label>
<select id="genre" name="genre" value="Please select genre">
<option value="<?php $con->getCategory() ?>"></option>
</select>
</div>
I've tried printing a message at the start of the method to see if the it's being called but the message did not print either so I was wondering, what am I possibly missing here?
I think you have serveral mistakes in your code ... i guess, you don't use OOP (classes) so i modfiy a example which should work .. .if not, please post error messages
file1.php
function getCategory($cn) {
$out = array();
if($cn == null) {
echo "Failed to connect to database.";
} else {
$fetchQuery = mysqli_query($cn, "SELECT * FROM tbl1 ORDER BY 'Name'") or die(mysqli_error($cn));
if(mysqli_num_rows($fetchQuery) > 0) {
while($item = mysqli_fetch_array($fetchQuery)) {
$out[] = $item["Name"];
}
}
return $out;
}
}
fil2.php
<?php
ini_set("display_errors", 1);
require_once("file1.php");
$con = dbConnect();
$updateStat = false;
$res = getCategory($con);
?>
<div>
<label>Genre</label>
<select id="genre" name="genre" value="Please select genre">
<?php
foreach($res as $cat):
?>
<option value="<?php echo $cat ?>"><?php echo $cat ?></option>
<?php endforeach;?>
</select>
Related
I have developed a function which runs a query and then uses the resulting variables in a logic in another file. I have used global variables to achieve this. I have read global variables are to be avoided, is there another way to write this function to avoid use of global variables.
File 1 (Function File)
<?php
function usertype()
{
include "../classes/sessionstart.php";
include "../config/dbconnect.php";
$user_id = $_SESSION['user_id'];
$select = $con->prepare("SELECT user_usertype, user_gender FROM tbl_user WHERE user_id = $user_id");
$select->setFetchMode(PDO::FETCH_ASSOC);
$select->execute();
while($data=$select->fetch()){
$GLOBALS['gender'] = $data['user_gender'];
$GLOBALS['usertype'] = $data['user_usertype'];
}
}
?>
File 2 (File Using the Function File)
<?php
usertype();
?>
<div>
<select class="searchpropertyinputs" name="user_usertype" id="user_usertype">
<?php if ($gender == "Male" && $usertype != "Marriage Bureau") { ?> <option value="Bride">Bride</option> <?php } ?>
<?php if ($gender == "Female" && $usertype != "Marriage Bureau") { ?> <option value="Groom">Groom</option> <?php } ?>
<?php if ($usertype == "Marriage Bureau") { ?>
<option value="" hidden>Bride or Groom</option>
<option value="Bride">Bride</option>
<option value="Groom">Groom</option>
<?php } ?>
</select>
</div>
You should return the value from the function:
Updated code, also fixed prepared query, and set an alias for the return columns.
<?php
function usertype()
{
include_once "../classes/sessionstart.php";
include_once "../config/dbconnect.php";
$select = $con->prepare("
SELECT user_usertype as `type`,
user_gender as `gender`
FROM tbl_user
WHERE user_id = :user_id LIMIT 1
");
$select->bindValue(':user_id', (int) $_SESSION['user_id'], PDO::PARAM_INT);
$select->execute();
return $select->fetch(PDO::FETCH_ASSOC);
}
?>
.
<?php
$usertype = usertype();
?>
<div>
<select class="searchpropertyinputs" name="user_usertype" id="user_usertype">
<?php if ($usertype['gender'] == "Male" && $usertype['type'] != "Marriage Bureau") { ?> <option value="Bride">Bride</option> <?php } ?>
<?php if ($usertype['gender'] == "Female" && $usertype['type'] != "Marriage Bureau") { ?> <option value="Groom">Groom</option> <?php } ?>
<?php if ($usertype['type'] == "Marriage Bureau") { ?>
<option value="" hidden>Bride or Groom</option>
<option value="Bride">Bride</option>
<option value="Groom">Groom</option>
<?php } ?>
</select>
</div>
You may also want to move out the includes to connect, session start, or you will have issues for future functions. So that should most likely lead you on to grouping functions into a user class, for example:
<?php
include_once "../classes/sessionstart.php";
include_once "../config/dbconnect.php";
class User {
public function __construct(PDO $con)
{
$this->con = $con;
}
public function type($user_id = 0)
{
$select = $this->con->prepare("
SELECT user_usertype as `type`,
user_gender as `gender`
FROM tbl_user
WHERE user_id = :user_id LIMIT 1
");
$select->bindValue(':user_id', (int) $user_id, PDO::PARAM_INT);
$select->execute();
return $select->fetch(PDO::FETCH_ASSOC);
}
//...
}
$user = new User($con);
$usertype = $user->type($_SESSION['user_id']);
?>
Okay, so I am trying to display text when something goes wrong. I want to have it so that if the page number is too high (above 3 in my case) it will display an error. Disregard the accessing mySQL database.
<?php
function get($name)
{
return isset($_REQUEST[$name]) ? $_REQUEST[$name] : '';
}
function is_valid_index($index,$array)
{
return $index >= 0 && $index < count($array);
}
?>
<?php
//Variables
$dbhost = "localhost";
$dbuser = "admin";
$dbpass = "pass";
$dberror = "You have failed to connect to the database!";
$conn = mysqli_connect($dbhost,$dbuser,$dbpass) or die ($dberror);
$select_db = mysqli_select_db($conn, "database") or die ("Couldn't Select Database");
?>
<form>
<?php
$page = array('Select List','Users', 'Groups');
echo '<select name="Lists">';
for($i = 0;
$i < count($page);
$i++)
{
echo '<option value="'.($i + 1).'">'.$page[$i].'</option>';
}
echo '</select>';
?>
<input type='submit'>
</form>
<?php
if(get('page'))
{
$page_id = get('page');
if(is_valid_index($page_id-1,$page))
{
echo "You have selected".$page[$page_id-1];
}
else
{
echo '<span style="color:red">Invalid Page</span>';
}
}
?>
Got the tutorial from this video: https://www.youtube.com/watch?v=SaRh2HauIXY
change this
echo '<select name="Lists">';
into this
echo '<select name="page">';
this way the function get('page') will return true and the if block will execute and so will your echo calls
I've been using mysql and it did what I want, but as my project is getting larger, I decided to opt for mysqli.
I looked at the tutorial at enter link description here which was really straight forward up until the point where I want to display some data
stored procedure (connect.php)
<?php
function db_connect() {
// Define connection as a static variable, to avoid connecting more than once
static $con;
// Try and connect to the database, if a connection has not been established yet
if(!isset($con)) {
// Load configuration as an array. Use the actual location of your configuration file
$config = parse_ini_file('config.ini');
$con = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
}
// If connection was not successful, handle the error
if( $con === false) {
// Handle error - notify administrator, log to a file, show an error screen, etc.
return mysqli_connect_error();
}
return $con;
}
function db_query($query) {
// Connect to the database
$con = db_connect();
// Query the database
$result = mysqli_query( $con,$query);
return $result;
}
function db_error() {
$con = db_connect();
return mysqli_error($con);
}
function db_select($query) {
$rows = array();
$result = db_query($query);
// If query failed, return `false`
if($result === false) {
return false;
}
// If query was successful, retrieve all the rows into an array
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
return $rows;
}
function db_quote($value) {
$con = db_connect();
return "'" . mysqli_real_escape_string($con,$value) . "'";
}
?>
php/html
<div class="grid_4">
<div class="left-1">
<h2 class="top-1 p3">Find a property</h2>
<form id="form-1" method="post" class="form-1 bot-1" action="prop_result.php">
<div class="select-1">
<label>Select Area</label>
<select name="field4" id="field4" >
<?php
$rows = db_select("SELECT id,city_id,area FROM area");
if($rows === false) {
$error = db_error();
}else
{
while($rows=mysqli_fetch_assoc($result))
{
?>
<option value=""><?php $rows['
area'];?></option>
<?php
}}
?>
</select>
</div>
What I don't understand is how to use the stored procedure in a while loop so it will output the data in the fields ID and Area so my select box and any other input can be properly populated based on the query
current
I've tried different ways :
<?php
$rows = db_select("SELECT id,city_id,area FROM area");
if($rows === false) {
$error = db_error();
}
while($rows=mysqli_fetch_assoc($result))
{
?>
<option value=""><?php $rows['
area'];?></option>
<?php
}
?>
and
$rows = db_select("SELECT id,city_id,area FROM area");
if($rows === false) {
$error = db_error();
}
{
?>
<option value=""><?php $rows['
area'];?></option>
<?php
}
?>
and
<?php
$rows = db_select("SELECT area_id from property");
if($rows === false) {
$error = db_error();
}
{
echo "<option value='".$rows['id']."'>".$rows[$col4]."</option>";
}
?>
None of these output any data. Echoing $rows gives no data. I don't know what the logic is for using the stored procedure to display the output.
Any help would be appreciated, if any other information is required to assist in resolving this issue, please let me know.
Awesome to hear that the data is returning. Try this out for size...
foreach($rows as $key => $value){
foreach($value as $k => $v){
if($k == 'id'){
$newID = $v;
}
if($k == 'type'){
$newType = $v
}
}
echo "<option value='".$newID."'>".$newType."</option>";
}
with this you should be able to make it work for you liking.
Edit: Didnt see the additional arrays until later...the nested loop should suite you better.
Siniseus way works but its too much code for a simple task. I did work with it to finally come to this
<select name="field4" id="field4" >
<?php
$rows = db_select("SELECT id, city_id,area FROM area");
foreach($rows as $row){
echo "<option value='".$row['id']."'>".$row['area']."</option>";
}
?>
</select>
Simple, clean and really straight forward without too many variables.
$rows = db_select ("Select Query")foreach($rows as $row){
do this
}
I'm trying to make a survey using php and mysql but I have a little inconvinient with the code, because when I submit the form with the survey, it only saves the last question of the survey, and It is because of the INPUT name.
here is the code.
DATABASE STRUCTURE.
"Questions" (idquestion, question)
"Surveys" (idsurvey, idquestion, answers, survey_number)
config.php
<?php
class Connection{
//variables para los datos de la base de datos
public $server;
public $userdb;
public $passdb;
public $dbname;
public function __construct(){
//Iniciar las variables con los datos de la base de datos
$this->server = 'localhost';
$this->userdb = 'root';
$this->passdb = '';
$this->dbname = 'sistema_bss';
}
public function get_connected(){
//Para conectarnos a MySQL
$con = mysql_connect($this->server, $this->userdb, $this->passdb);
//Nos conectamos a la base de datos que vamos a usar
mysql_select_db($this->dbname, $con);
}
}
?>
Questions.php
public function show_questions(){
$query = "SELECT * FROM questions Where questionsnumber = 1";
$this->result = $this->objDb->select($query);
return $this->result;
}
public function new_survey(){
$query = "INSERT INTO survey VALUES('',
'".$_POST["questi"]."',
'".$_POST["answer"]."')";
$this->objDb->insert($query);
}
Survey_form.php
hint: The form it's ok, it execute the query but the problem is, that it only store one question and answer of the survey, instead store all the questions and answers (array's rows) at the time.
<form name="newDona" action="new_survey_exe.php" method="post" value= "">
<?php
//it calls the function that shows all the questions that are stored in the db
$numrows = mysql_num_rows($survey);
if($numrows > 0){
while($row=mysql_fetch_array($survey)){?>
<td>
<?php
echo $row["question"];?></td>
<th><select name="answer" >
<option value=""></option>
<option value="yes">yes</option>
<option value="NO">NO</option>
</select>
<tr><td colspan="5" align="center"><input type="submit" name="send" id="send" value="SAVE" /></td></tr>
I think the problem is the "select" name, maybe because it rewrites the other questions and answers for every question of the survey so it only stores the last question and answer.
I want to store multiple rows using one form :D
Thanks in advance. :)
Here is your answer. Your insert command was not assigning columns, just values:
USE PDO CONNECTION OUTSIDE OF CLASS
In your case, if you want to just run sql queries you will want to use the raw format of the DB. That requires two changes in my DBEngine. Where it says protected $con; change it to public $con; then when you want to call any kind of sql statement do as follows:
// If the DB is already set don't do this step portion
require_once('includes/classes/dbconnect.php');
$db = new DBConnect('localhost','sistema_bss','root','');
// Here is where you use the PDO class
$query = $db->con->prepare("SELECT MAX(surveynumber) FROM survey");
$query->execute();
if($query->rowCount()>0) {
while($result = $query->fetch(PDO::FETCH_ASSOC)) {
print_r($result);
}
}
newsurvey.php
<?php
// Not sure if this is proper path back to root then back
//to files, so you'll have to fix that if wrong
// Include db
require_once('includes/classes/dbconnect.php');
// Include questions class
require_once('apps/survey/classes/questions.php');
// Create connection
$con = new DBConnect('localhost','sistema_bss','root','');
// If answers not submitted, show form
if(!isset($_POST['answer'])) {
include_once('apps/survey/new.form.php');
}
// If answers submitted process the form
else {
// Create questions class, forward DB connection
$objDona = new Questions($con);
// Run the insert class
$objDona->NewSurveyMulti($_POST['answer']);
$display = $con->Fetch("select * from survey");
print_r($display);
} ?>
new.form.php
<?php
// Fetch questions
$cuestionario = $con->Fetch("SELECT * FROM questions"); ?>
<form name="newDona" action="" method="post">
</table><?php
// Confirm there are questions being drawn from database
$numrows = (is_array($cuestionario))? count($cuestionario): 0;
if($numrows > 0) {
// Loop through questions
foreach($cuestionario as $row) { ?>
<tr>
<!-- Write the question -->
<td><?php echo $row["question"];?></td>
</tr>
<th>
<!-- Set the question id -->
<select name="answer[<?php echo $row['idquestion']; ?>][]">
<option value=""></option>
<option value="1">yes</option>
<option value="no">NO</option>
</select>
</th><?php } ?>
<tr>
<td colspan="5" align="center">
<input type="submit" name="send" id="send" value="SAVE" />
</td>
</tr>
</table>
</form>
<?php } ?>
dbconnect.php
<?php
// I'm adding my PDO database because yours is deprecated
class DBConnect
{
public $con;
// Create a default database element
public function __construct($host = '',$db = '',$user = '',$pass = '')
{
try {
$this->con = new PDO("mysql:host=$host;dbname=$db",$user,$pass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
}
catch (Exception $e) {
return 0;
}
}
// Simple fetch and return method
public function Fetch($_sql)
{
$query = $this->con->prepare($_sql);
$query->execute();
if($query->rowCount() > 0) {
while($array = $query->fetch(PDO::FETCH_ASSOC)) {
$rows[] = $array;
}
}
return (isset($rows) && $rows !== 0 && !empty($rows))? $rows: 0;
}
// Simple write to db method
public function Write($_sql)
{
$query = $this->con->prepare($_sql);
$query->execute();
}
} ?>
questions.php
<?php
class Questions
{
//atributos
public $nameDono;
public $objDb;
public $result;
public $connect;
public function __construct($dbconnection){
// My PDO connection
$this->MyDB = $dbconnection;
}
public function NewSurveyMulti($answer = array())
{
if(!empty($answer)) {
foreach($answer as $questi => $value) {
$this->MyDB->Write("INSERT INTO survey (`idquestion`,`answers`) VALUES('".$questi."', '".$value[0]."')");
}
}
}
public function mostrar_survey()
{
$this->result = $this->MyDB->Fetch("SELECT * FROM questions");
return $this->result;
}
public function new_survey()
{
$this->MyDB->Write("INSERT INTO survey (`idquestion`,`answers`,`surveynumber`) VALUES("'".$_POST["questi"]."','".$_POST["answer"]."','".$_POST["numsurvey"]."')");
}
} ?>
Here is the code Rasclatt
QUESTIONS.PHP
<?php
class Questions{
//atributos
public $nameDono;
public $objDb;
public $result;
public function __construct(){
$this->objDb = new Database();
}
public function NewSurveyMulti($answer) {
if(!empty($answer)) {
foreach($answer as $questi => $value) {
$query = "INSERT INTO survey VALUES('','".$questi."', '".$value."')";
$this->objDb->insert($query);
}
}
}
// I don't know what the class name is but this is how
// you would apply this method
//--------------------------------I don't know where I have to put it, the class name is Questions.
if(isset($_POST['answer']))
Questions->NewSurveyMulti($_POST['answer']);
//this functions shows all the questions for the survey
public function mostrar_survey(){
$query = "SELECT * FROM questions ";
$this->result = $this->objDb->select($query);
return $this->result;
}
}
?>
Survey_form.php
<?php
require'../class/questions.php';
$cuestionario= $objBdonar->show_questions();
$survey= $objBdonar->NewSurveyMulti($answer) ;
<form name="newDona" action="new_survey_exe.php" method="post">
</table><?php
//it calls the function that shows all the questions that are stored in the db
$numrows = mysql_num_rows($cuestionario);
if($numrows > 0) {
while($row = mysql_fetch_array($cuestionario)) { ?>
<tr>
<td>
<?php echo $row["question"];?>
</td>
</tr>
<th>
<select name="answer[<?php echo $row['questi']; ?>][]">
<option value=""></option>
<option value="yes">yes</option>
<option value="NO">NO</option>
</select>
</th><?php } ?>
<tr>
<td colspan="5" align="center">
<input type="submit" name="send" id="send" value="SAVE" />
</td>
</tr>
</table>
</form>
<?php } ?>
New_survey_exe.php
<?php
require'../class/questions.php';
$objCon = new Connection();
$objCon->get_connected();
$objDona = new Questions();
$objDona->NewSurveyMulti($answer) ;
header('Location: ' . $_SERVER['HTTP_REFERER']);
?>
This question already has answers here:
Issue with PHP MySQL and insert into UTF-8 [closed]
(3 answers)
Closed 10 years ago.
I have a problem with php & mysql, insert to database using utf-8.
first file:
addsite:
<?php
include 'header.php';
if(isset($data)) {
foreach($_POST as $key => $value) {
$posts[$key] = filter($value);
}
if(isset($posts['type'])){
if($posts['url'] == "http://" || $posts['url'] == ""){
$error = "Add your page link!";
}else if($posts['title'] == ""){
$error = "Add your page title!";
}else if(!preg_match("/\bhttp\b/i", $posts['url'])){
$error = "URL must contain http://";
}else if(!preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $posts['url'])){
$error = "Please do not use special characters in the url.<";
}else{
include "plugins/" . $posts['type'] . "/addsite.php";
}
}
?>
<div class="contentbox">
<font size="2">
<li>Pick the type of exchange you are promoting from the dropdown menu.</li>
<li>Set the amount of coins you wish to give per user complete(CPC).</li>
<li>The higher the amount of coins the higher the Links position.</li>
</div>
<div class="contentbox">
<div class="head">Add Site</div>
<div class="contentinside">
<?php if(isset($error)) { ?>
<div class="error">ERROR: <?php echo $error; ?></div>
<?php }
if(isset($success)) { ?>
<div class="success">SUCCESS: <?php echo $success; ?></div>
<?php }
if(isset($warning)) { ?>
<div class="warning">WARNING: <?php echo $warning; ?></div>
<?php } ?>
<form class="contentform" method="post">
Type<br/>
<select name="type"><?php $select = hook_filter('add_site_select', ""); echo $select; ?></select><br/><br/>
Link<br/>
<input name="url" type="text" value="<?php if(isset($posts["url"])) { echo $posts["url"]; } ?>"/><br/><br/>
Title<br/>
<input name="title" type="text" value="<?php if(isset($posts["title"])) { echo $posts["title"]; } ?>"/><br/><br/>
Cost Per Click<br/>
<?php if($data->premium > 0) { ?>
<select name="cpc"><?php for($x = 2; $x <= $site->premcpc; $x++) { if(isset($posts["cpc"]) && $posts["cpc"] == $x) { echo "<option selected>$x</option>"; } else { echo "<option>$x</option>"; } } ?></select><br/><br/>
<?php }else{ ?>
<select name="cpc"><?php for($x = 2; $x <= $site->cpc; $x++) { if(isset($posts["cpc"]) && $posts["cpc"] == $x) { echo "<option selected>$x</option>"; } else { echo "<option>$x</option>"; } } ?></select><br/><br/>
<?php } ?>
<input style="width:40%;" type="Submit"/>
</form>
</div>
</div>
<?php
}
else
{
echo "Please login to view this page!";
}
include 'footer.php';
?>
second file , plugin addsite.php
<?php
$num1 = mysql_query("SELECT * FROM `facebook` WHERE `url`='{$posts['url']}'");
$num = mysql_num_rows($num1);
if($num > 0){
$error = "Page already added!";
}else if(!strstr($posts['url'], 'facebook.com')) {
$error = "Incorrect URL! You must include 'facebook.com'";
}else{
mysql_query($qry);
mysql_query("INSERT INTO `facebook` (user, url, title, cpc) VALUES('{$data->id}', '{$posts['url']}', '{$posts['title']}', '{$posts['cpc']}') ");
$success = "Page added successfully!";
}
?>
when i write arabic language in the form and submit ,
it went to database with unkown language like :
أسÙ
database collaction : utf8_general_ci
<?php
error_reporting(E_ALL);
ini_set('display_errors', '0');
$host = "localhost"; // your mysql server address
$user = "z*******"; // your mysql username
$pass = "m********"; // your mysql password
$tablename = "z*******"; // your mysql table
session_start();
$data = null;
if(!(#mysql_connect("$host","$user","$pass") && #mysql_select_db("$tablename"))) {
?>
<html>
MSQL ERROR
<?
exit;
}
include_once 'functions.php';
require_once "includes/pluggable.php";
foreach( glob("plugins/*/index.php") as $plugin) {
require_once($plugin);
}
hook_action('initialize');
$site = mysql_fetch_object(mysql_query("SELECT * FROM settings"));
?>
after removing
$posts[$key] = filter($value); "
from header.php
The output shift from:
To:
& Oslash; & pound; & Oslash; ³& Ugrave
to : Ù Ù Ù
header file : http://zwdha.com/header.txt
You might need to add some ini_set statements if your db is full utf8: http://www.polak.ro/php-mysql-utf-8.html
This a very basic insert query to see if you can insert data in you database with PHP.
<?php
function inserting_data() {
$host = "host";
$user = "username";
$password = "password";
$database = "database";
$charset = "utf8";
$link = mysqli_connect($host, $user, $password, $database);
mysql_set_charset($charset, $link);
IF (!$link) {
echo('Unable to connect to the database!');
} ELSE {
/*
* this just to test if something gets inserted into your table.
* If some of your columns are set to not null you should add them tot this insert query.
*/
$query = "INSERT INTO facebook (`title`) VALUES('test_title'), ('test_title1')";
mysqli_query($link, $query);
}
mysqli_close($link);
}
?>
This is a very basic select query to retrieve data form your database.
<?php
function selecting_data(){
$host = "host";
$user = "username";
$password = "password";
$database = "database";
$charset = "utf8";
$link = mysqli_connect($host, $user, $password, $database);
mysql_set_charset($charset, $link);
IF (!$link) {
echo('Unable to connect to the database!');
} ELSE {
/*
* this just to test if something gets returned from your table.
*/
$query = "SELECT * FROM facebook";
$result = mysqli_query($link, $query);
while ($rows = mysqli_fetch_array($result, MYSQLI_BOTH)){
echo $rows['title'];
}
}
mysqli_close($link);
}
?>
My advise is to first test if you can get data in your database and retrieve it. By trial and error you will need to solve your question. B.T.W. I have used MYSQLI_ function instead of MYSQL. The mysql_ functions will depreciate soon. Hope this helps.
a - you should not use mysql_ functions. use PDO. this error is one of the reasons.
b - mysql_set_charset('utf8');
c - are the columns you are trying insert data using utf8_general_ci ?
d - on my.cf set default-character-set and character-set-server
if this doesn't work read this:
http://www.oreillynet.com/onlamp/blog/2006/01/turning_mysql_data_in_latin1_t.html
and this:
http://www.phpwact.org/php/i18n/utf-8
if after that you still dont get it right, make sure to listen to people and use PDO.