How can I save symbols like πŸŽ… πŸŒ πŸŽ„πŸ° in mysql? - mysql

I've searched for about the last 3 hours for a solution, but it doesn't work.
MySQL doesn't support utf8mb4 (this is one solution I can't test).
Thank you!

Here is an example DB connection using PHP and MySQL 5.5.3:
public function_construct($host, $db, $user, $pass){
try {
$this->conn = new PDO("mysql:host = {$host};
dbname = {$db};
charset = utf8mb4",
$user,
$pass);
} else { exit(); }
}
As of release 5.5.3 utf8mb4 is fully backwards compatible with utf8. If you are working with an existing database look for the MySQL configuration file and change instances of 'utf8' to 'utf8mb4' accordingly.

Use Mysql blob field, save images directly there, although I personally don't like saving images in DB, save links to files instead.
$img = mysql_escape_string(file_get_contents('imagefile.gif'));
Then you would insert this $img into db.

Related

Website Display's ?'s instead of Korean

I uploaded my website to the new server. It works perfectly on my test server at home, there is not a different setup the databases were copied over word for word. But on the site anything that is in Korean displays as ??????. The database stored it correctly and the pages all have <meta charset="UTF-8"> I can not figure out what I am missing.
EDIT: The text displays fine in the database when I use phpMyADMIN
In PDO (php api), you need set charset $conn->exec('SET CHARACTER SET utf8');.
PHP example:
<?php
//ν•œκ΅­μ–΄/쑰선말
header('Content-Type: text/html; charset=utf8');
$username = 'user';
$password = 'password';
$host = 'domain';
$db = 'dbtest';
try {
$conn = new PDO('mysql:host=' . $host . ';dbname=' . $db . ';charset=utf-8', $username, $password);
$conn->exec('SET CHARACTER SET utf8');//This solve the problem
$stmte = $conn->prepare('SELECT id, text FROM test LIMIT 10');
$exec = $stmte->execute();
if ($exec) {
while($reg = $stmte->fetch(PDO::FETCH_OBJ)){
echo 'id: ' . $reg->id . '<br />';
echo 'text: ' . $reg->text . '<br /><hr />';
}
} else {
echo 'Error SELECT';
}
} catch(PDOException $e){
echo 'PDOException: ', $e->getMessage();
}
?>
Mysql example:
CREATE DATABASE `dbtest` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
USE `dbtest`;
CREATE TABLE IF NOT EXISTS `test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`text` varchar(300) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `test` (`id`, `text`) VALUES (1, 'ν•œκ΅­μ–΄/쑰선말');
Use phpmyadmin in your server to verify that the DATABASE on your server is "utf8", see:
In your database must be something else.
if your database is correct (after checking with the utf8) then the problem is in some PHP file.
To resolve you should save all php files (both the major and the includes)
Save your html file (or php file) in "utf8 without boom", using notepad++, see:
Add in your PHP files (in top file):
<?php
header('Content-Type: text/html; charset=utf8');
?>
Files included should be saved in utf8-without-boom also, example:
<?php
include('YOUR FILE INCLUDED.php');// Save "YOUR FILE INCLUDED.php" in UTF8-without-boom
?>
Maybe its some page is in ANSI (for example "form.php").
Note: All PHP files must be in UTF8-without-boom format
Try adding lang attribute to your html tag
<html lang="ko">
The issue is most likely a different in database collation settings between your home test server & your new remote server. Meaning that while your database was transferred correctly, the way that data is then spit out of database is a whole other thing.
What is the data collation of the database giving you an issue? By default, most MySQL installs set latin1_swedish_ci instead of utf8_general_ci for newly created databases.
Change the collation of the database & try again.
ALTER DATABASE [name of your database] CHARACTER SET utf8;
If this is a specific table, the collation can be changed as so:
ALTER TABLE [name of your table] CONVERT TO CHARACTER SET utf8;
And if it is a specific column in a table:
ALTER TABLE [name of your table] MODIFY [name of your column] [other settings] CHARACTER SET utf8 COLLATE utf8_general_ci;
Or perhaps you could export the current database, create a new database with this command & reimport the data:
CREATE DATABASE [name of your database] CHARACTER SET utf8 COLLATE utf8_general_ci;
And if you want to make a permanent change to the MySQL install on the machine giving you an issue, go and edit my.cnf. The following would set the whole chain to UTF-8:
[client]
default-character-set=utf8
[mysql]
default-character-set=utf8
[mysqld]
collation-server = utf8_unicode_ci
init-connect='SET NAMES utf8'
character-set-server = utf8
EDIT: The original poster states that the connection & DB are all UTF8 clean. But what about trying an edit to the Apache default character set. Go here & open the character set file for Apache like so:
sudo nano /etc/apache2/conf.d/charset
And uncomment the line that looks like this:
#AddDefaultCharset UTF-8
So it looks like this:
AddDefaultCharset UTF-8
And restart Apache. This is not a great idea for a long term setup in my humble opinion, but if t solves the issue it indicates there is something in your codebase that can be changed to affect the same results without having to force Apache to force UTF8.

How to import a csv file into MySQL server?

I am very new to MySQL. I have started learning MySQL today only.
I have been given a task.
In this task I need to create a sample csv file in excel and then upload it on MySQL server, then make some changes and then write it back as a csv file on the hard drive.
I looked up many links available on internet but they are too complicated to understand.
Can somebody explain it to me in simple words assuming that I am a beginner and I just know how to create a connection on MySQL.
Thank You.
Try this,
<?php
$csvFile = 'test_data.csv';
$csv = readCSVFile($csvFile);
if(!empty($csv))
{
foreach($csv as $file)
{
//inserting into database
$query_insert = "insert into csv_data_upload set
name = '".$file[0]."',
value = '".$file[1]."'";
echo $query_insert;
$insert = mysql_query($query_insert);
}
} else {
echo 'Csv is empty';
}
//Reading CSV File
function readCSVFile($csvFile)
{
$file_handle = fopen($csvFile, 'r');
while (!feof($file_handle) )
{
$line_of_text[] = fgetcsv($file_handle, 1024);
}
fclose($file_handle);
return $line_of_text;
}
?>
And for writing CSV File, Try this,
<?php
$list = array (
array('aaa', 'bbb', 'ccc', 'dddd'),
array('123', '456', '789'),
array('"aaa"', '"bbb"')
);
$fp = fopen('file.csv', 'w');
foreach ($list as $fields)
{
fputcsv($fp, $fields);
}
fclose($fp);
?>
I would recommend uploading the data via Microsoft Access. Access is just like Excel part of the office suite from microsoft. You can easily import the CSV / Excel file via a wizzard. Then use the database wizzard to upload everything to MySQL.
By the way you could probably do the same changes to the data in MS Access. It runs with some adaptations the same SQL commands and you could also use the GUI. I would recommend MySQL more for on line purposes, not for stuff you can do off line. And lets be fair using a command line might not be for everybody the most easy point of entry to databases. There are more using friendly command line alternatives for MySQL, for example mysql workbench and phpmyadmin. You could use them to directly import in to MySQL, but I have no experience with that option.
Good luck with you task.
You should put your code what you have tried, even you can search over google before posting question. Suggested link to check - http://www.php-guru.in/2013/import-csv-data-to-mysql-using-php/

MySQL encoding on insert PHP

I'm getting encoding problem when I insert names in a mySQL table, that contains special characters, like "ΓΆ", "Γ€" etc.
For example, the word "Γ–l" becomes "âl".
I've tried to write the names to a text file and then they show up properly.
I've tried to insert the names in phpMyAdmin using SQL-statements, and that works good as well.
Now I found a solution in setting mysql_query('SET NAMES utf8;'); before the insert query.
Is this how it should be done, or is there a better way?
yeah running the SET NAMES utf8; is needed to make the MySQL know that the client connection is using ut8 while sending the data. You can though now define it inside the PDO connection (if you are using PDO for connecting to the MySQL).
If running PHP version older than 5.3.6 then you can use the following code:
$pdo = new PDO(
'mysql:host=mysql.example.com;dbname=example_db',
"username",
"password",
array(PDO::MYSQL\_ATTR\_INIT\_COMMAND => "SET NAMES utf8"));
else use the following:
$pdo = new PDO("mysql:host=localhost;dbname=world;charset=utf8", 'my_user', 'my_pass');

MySQL resource in Zend Framework

I'm starting a new project built on Zend Framework. I know all about controllers, layouts and views. But I don't know how to add a MySQL resource.
Basically, I would like to have some model classes with getters and setters and for each, a resource class witch would handle MySQL queries. These resources classes need access to a DB class which performs the actual queries. The configuration for the DB would have to be in a separate file somewhere as either XML data, .ini or PHP array.
How can I obtain that? Where should I put each the files (right now, I have the default Zend directory structure)?
You dont need to create an instace of connection to database ,Zend does it automatically..just add these following to your config file
resources.db.adapter = "PDO_MYSQL"
resources.db.isDefaultTableAdapter = true;
resources.db.params.host = "yourserver"
resources.db.params.username = "username"
resources.db.params.password = "pwd"
resources.db.params.dbname = "dbname"
you can use it later
$DB = Zend_Db_Table_Abstract::getDefaultAdapter();
Zend comes with a set of DB classes that you can use. Documentation is here: http://framework.zend.com/manual/en/zend.db.html Before asking questions like this please do a bit of Googling.
[general]
db.adapter = PDO_MYSQL
db.params.host = server
db.params.username = username
db.params.password = password
db.params.dbname = dbname
$config = new Zend_Config_Ini(ROOT_DIR.'/application/config.ini', 'general');
$DB = Zend_Db::factory($config->db);
Zend_Db_Table::setDefaultAdapter($DB);
$DB = Zend_Db_Table_Abstract::getDefaultAdapter();

Set MySQL session variable - timezone - using Doctrine 1.2 and Zend Framework

Got a Zend Framework web application using Doctrine 1.2 connecting to a MYSQL 5.1 server.
Most data needs to be entered and displayed in local timezone. So following the advice here, I'd like (I think) to set PHP and MySQL to use UTC and then I'll handle the conversion to local time for display and to UTC prior to insert/update. [If this is totally goofy, I'm happy to to hear a better approach.]
So, how do I tell Doctrine to set the MySQL session to UTC? Essentially, how do I tell Doctrine to issue the MySQL command SET SESSION time_zone = 'UTC'; when it opens the connection?
Thanks in advance!
It appears that this can be done by attaching to the Doctrine_Connection object an Doctrine_EventListener with a postConnect() method.
Doctrine ORM for PHP - Creating a New Listener
Something like:
class Kwis_Doctrine_EventListener_Timezone extends Doctrine_EventListener
{
protected $_timezone;
public function __construct($timezone = 'UTC')
{
$timezone = (string) $timezone;
$this->_timezone = $timezone;
}
public function postConnect(Doctrine_Event $event)
{
$conn = $event->getInvoker();
$conn->execute(sprintf("SET session time_zone = '%s';", $this->_timezone));
}
}
[Using sprintf() here is probably amateurish, but I couldn't figure out how to do a proper parameter bind. (embarrassed smiley).]
Then in my app's Bootstrap.php, I have something like:
protected function _initDoctrine()
{
// various operations relating to autoloading
// ..
$doctrineConfig = $this->getOption('doctrine');
$manager = Doctrine_Manager::getInstance();
// various boostrapping operations on the manager
// ..
$conn = Doctrine_Manager::connection($doctrineConfig['dsn'], 'doctrine');
// various boostrapping operations on the connection
// ..
// Here's the good stuff: Add the EventListener
$conn->addListener(new Kwis_Doctrine_EventListener_Timezone());
return $conn;
}
[One slightly off-topic note: on my local development machine, I kept running into a MySQL error in which no timezone I entered seemed to be accepted. Turns out that the standard MySQL install creates all the timezone tables in the mysql database, but doesn't actually populate them; you need to populate them separately. More info at MySQL site.]