I can see query results but I also see � character with some characters like "Á".
Basic connection is like this:
$mysqli = new mysqli(server, user, pass, db);
mysqli_set_charset($mysqli, 'utf8');
I also tried with:
$mysqli->query("SET NAMES 'utf8'");
$mysqli->set_charset("utf8");
mysql_query("SET NAMES 'utf8'");
But characters are still watching.
Query
function connection($mysqli) {
mysql_query("SET NAMES 'utf8'");
if ( ! $link = mysqli_connect("localhost", "user", "pass") ) {
echo ("Error");
return false;
}
if ( ! mysqli_select_db($link, "db") ) {
echo ("Error");
return false;
}
if ( ! $consulta = mysqli_query($link, $mysqli) ) {
echo ("Error");
return false;
}
return $consulta;
}
All files are saved with UTF8, VAR columns in DB are with UTT8 too.
What or where is the problem?
Thank you!
Maybe your php file is saved as an ANSI doc, try with UTF8 without BOM.
Also try to declare the charset UTF8 on your output file.
Hope it help
Related
I have created mssql connection in php via odbc correctly. I can Insert some data into database but if I want to send some special characters it displayed bad way. I have set UTF-8 charset in my website and UTF-8 file encoding. When i try Insert data from the command line using isql command it works. I've tried already all conversion method but its no effects.
$user = 'admin';
$password = 'pass123';
$dsn = 'mydsn';
$connection = odbc_connect($dsn, $user, $password);
if ($connection) {
$data_array = array(
"string" => "ąĄę12",
);
$sql = "INSERT INTO Table (column_1) VALUES ('".$data_array['string']."')";
$res = odbc_exec($connection, $sql);
if (!$res) {
error_log("Insert failed");
}
odbc_close($connection);
}
else {
die("Connection could not be established.");
}
I've been working on some beginner php exercise recently and have encountered an error to which I have no idea what is causing it.
It says
"Error: SQLSTATE[HY000] [1049] Unknown database 'otkrica'"
The sql file is correctly named "otkrica" and my db.php looks like this:
<?php
$dsn = "mysql:host=127.0.0.1;charset=utf8;dbname=otkrica";
try{
$pdo = new PDO($dsn,"root","");
}catch(PDOException $e){
die("Error: " . $e->getMessage());
}
?>
I would really appreciate input on this one. What am I missing?
The correct answer is found in the comments (credit to cmnardi). Posted as a clear answer for anyone looking:
Set the port you are using like: mysql:host=localhost;port=3307;dbname=testdb
I fix this problem wait this way
$connect = new PDO($dsn, $user, $pass);
$connect->exec("SET character_set_connection = 'utf8'");
$connect->exec("SET NAMES 'UTF8'");
<?php
$server="localhost";
$user="root";
$pass="";
$dbname="clicksite";
$dsn="mysql:host=$server;dbname=$dbname";
try{
$connect=new PDO($dsn,$user,$pass);
$connect->exec("SET character_set_connection = 'utf8'");
$connect->exec("SET NAMES 'UTF8'");
}catch(PDOException $error) {
echo "unable to connect".$error->getMessage();
}
?>
attention: use as wampserver ver2.5 for build database in the server
after run wampserver, click left on the icon in notify bar and then click on phpmyadmin and create the database.
I'm building a project with angular and php. I have a "file" table in my database that I can send file and retrieve all information that I need. I added a delete button but I don't know why it doesn't work. There are no errors in my console. Can someone please have a look at my code?
php for deleteing:
<?php
header('Content-Type: text/html; charset=utf-8');
$connect = mysqli_connect("localhost", "root", "", "hamatkin");
include_once 'file.php';
mysqli_query($connect, "SET character_set_client = utf8");
mysqli_query($connect, "SET character_set_connection = utf8");
mysqli_query($connect, "SET character_set_results = utf8");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//$customer = new Customer();
$data = json_decode(file_get_contents("php://input"));
$x = $data->reffer_customer_id;
$reffer_customer_id = $data->reffer_customer_id;
$del = "DELETE FROM file WHERE reffer_customer_id = " . $reffer_customer_id;
//echo $del;
mysqli_query($connect, $del);
$newURL = "/hamatkin/#/allPriceOffers";
header('Location: '.$newURL);
?>
Controller:
$scope.delete = function(deletingId, $index) {
$http.post('api/customers-tab/delete-priceOffer.php', { "reffer_customer_id" : deletingId })
.success(function(data) {
var arr = JSON.parse(JSON.stringify(data));
$scope.files = arr;
var arr2 = arr.split(",");
arr2.splice($index, 1);
$route.reload();
});
};
Html delete button:
<td><a ng-click="delete(x.reffer_customer_id, $index)" class="btn btn-primary btn-active">מחיקה</td>
First of all you should fix your HTML:
I don't know what you mean putting delete function on ng-click attribute, probably you want to use on-click instead? Correct me if I'm wrong
You have opened <a> tag, but </a> is absent
Corrected HTML button in <td> is:
<td><a on-click="delete(x.reffer_customer_id, $index); return false;" class="btn btn-primary btn-active">מחיקה</a></td>
In the second I propose to check your MySQL scheme of table file and be sure that you provide same type of refferal_customer_id.
For example, I've wondered that this should be numeric value, than:
<?php
header('Content-Type: text/html; charset=utf-8');
/*
* I propose to check all data before you will open connection to MySQL,
* because if data is not correct - connection will not be used
* I strongly propose to process errors in your client scripts
*/
$data = json_decode(file_get_contents("php://input"));
if (!isset($data) ||
!isset($data->reffer_customer_id) ||
!is_numeric($data->reffer_customer_id)
) {
echo 'Incorrect data specified';
exit;
}
/*
* Connecting
*/
$connect = mysqli_connect("localhost", "root", "", "hamatkin");
/*
* I don't know why you using it for delete query if your id is numeric
*/
mysqli_query($connect, "SET character_set_client = utf8");
mysqli_query($connect, "SET character_set_connection = utf8");
mysqli_query($connect, "SET character_set_results = utf8");
/*
* I don't recommend you to pass mysql connection error in raw format,
* because it can be used against you
* And don't forget to halt your script if error occurred
*/
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL";
exit;
}
/*
* Here your delete query
*/
$delId = mysqli_real_escape_string($connect, $data->reffer_customer_id);
if (!$delId) {
echo 'Incorrect id for delete query specified';
exit;
}
/*
* Don't forget to check errors
*/
if (!mysqli_query($connect, "DELETE FROM file WHERE reffer_customer_id = $delId")) {
echo "Failed to delete reffer_customer with id: $delId";
exit;
}
/*
* And close the connection
*/
mysqli_close($connect);
/*
* As for me: better to put next route into response for redirecting from client
* but I don't know what you will do with this, so, putting header
*/
header('Location: /hamatkin/#/allPriceOffers');
I think your query should be like these:
$del = "DELETE FROM file WHERE reffer_customer_id=".$reffer_customer_id." ";
I have a MySQL database encoded with the default characterset UTF8. I have also a PHP code encoded with the same charset meta charset="UTF-8".
My connection to the database is configured to use UTF8 too
new PDO("mysql:host=" .$host. ";dbname=".$database,$username,$password,
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
But I have a problem when I use Ajax to get the content of a textbox and insert it into the database.
If I do not use special characters it works fine but when I use a quote or something everything stops working.
I tried to use UTF8_encode and UTF8_decode but nothing changed
EDIT
PHP
...
<meta charset="UTF-8">
...
<textarea class="commentBox" id="<?php echo $id_case;?>"></textarea>
<button class="saveComment" id="<?php echo $id_case;?>"> Save comment </button>
//id_case is different for each textarea
Javascript
$('.saveComment').click(function()
{
var idComment = this.id;
var content = $('#'+idComment+'.commentBox').val();
add_comment(idComment, content);
});
function add_comment(case_id, content)
{
$.post("../functions/ajax/add_comment.php",
{
id_case: case_id,
content: content
},
function(data,status)
{
alert("It worked !");
console.log("Function add_comment : "+status);
});
}
add_comment.php
<?php
if(isset($_POST['id_case'], $_POST['content']))
{
$case = $_POST['id_case'];
$content = $_POST['content'];
}
else
{
echo "Error during sending data to [add_comment.php]";
}
if($db != null)
{
try
{
$sql = ("UPDATE cases SET progress_remarks = '$content' WHERE id_cases = $case");
$result = $db->exec($sql);
echo $content;
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
}
else echo "Erreur interne (fill_progress.php)";
?>
My database connection is done somewhere else but looks like this
$this->con = new PDO("mysql:host=" .$host. ";dbname=".$database,$username,$password,
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
when I use a quote or something everything stops working.
It is unclear whether the problem is (1) just an escaping issue, or (2) also a utf8 issue.
Since PDO has a builtin way to take care of escaping, use it:
$sql = ("UPDATE cases SET progress_remarks = ? WHERE id_cases = $case");
$result = $db->exec($sql, $content);
This is probably the preferred way to set the charset with PDO: $db = new PDO('dblib:host=host;dbname=db;charset=UTF-8', $user, $pwd);
meta charset="UTF-8" refers to the tag in HTML, not PHP or MySQL.
SHOW CREATE TABLE -- Is the column in question declared CHARACTER SET utf8?
I had this previously in my normal mysql_* connection:
mysql_set_charset("utf8",$link);
mysql_query("SET NAMES 'UTF8'");
Do I need it for the PDO? And where should I have it?
$connect = new PDO("mysql:host=$host;dbname=$db", $user, $pass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
You'll have it in your connection string like:
"mysql:host=$host;dbname=$db;charset=utf8mb4"
HOWEVER, prior to PHP 5.3.6, the charset option was ignored. If you're running an older version of PHP, you must do it like this:
$dbh = new PDO("mysql:host=$host;dbname=$db", $user, $password);
$dbh->exec("set names utf8mb4");
Prior to PHP 5.3.6, the charset option was ignored. If you're running an older version of PHP, you must do it like this:
<?php
$dbh = new PDO("mysql:$connstr", $user, $password);
$dbh -> exec("set names utf8");
?>
This is probably the most elegant way to do it.
Right in the PDO constructor call, but avoiding the buggy charset option (as mentioned above):
$connect = new PDO(
"mysql:host=$host;dbname=$db",
$user,
$pass,
array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
)
);
Works great for me.
For completeness, there're actually three ways to set the encoding when connecting to MySQL from PDO and which ones are available depend on your PHP version. The order of preference would be:
charset parameter in the DSN string
Run SET NAMES utf8 with PDO::MYSQL_ATTR_INIT_COMMAND connection option
Run SET NAMES utf8 manually
This sample code implements all three:
<?php
define('DB_HOST', 'localhost');
define('DB_SCHEMA', 'test');
define('DB_USER', 'test');
define('DB_PASSWORD', 'test');
define('DB_ENCODING', 'utf8');
$dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_SCHEMA;
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
);
if( version_compare(PHP_VERSION, '5.3.6', '<') ){
if( defined('PDO::MYSQL_ATTR_INIT_COMMAND') ){
$options[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES ' . DB_ENCODING;
}
}else{
$dsn .= ';charset=' . DB_ENCODING;
}
$conn = #new PDO($dsn, DB_USER, DB_PASSWORD, $options);
if( version_compare(PHP_VERSION, '5.3.6', '<') && !defined('PDO::MYSQL_ATTR_INIT_COMMAND') ){
$sql = 'SET NAMES ' . DB_ENCODING;
$conn->exec($sql);
}
Doing all three is probably overkill (unless you're writing a class you plan to distribute or reuse).
$conn = new PDO("mysql:host=$host;dbname=$db;charset=utf8", $user, $pass);
$con="";
$MODE="";
$dbhost = "localhost";
$dbuser = "root";
$dbpassword = "";
$database = "name";
$con = new PDO ( "mysql:host=$dbhost;dbname=$database", "$dbuser", "$dbpassword", array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$con->setAttribute ( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
I think you need an additionally query because the charset option in the DSN is actually ignored. see link posted in the comment of the other answer.
Looking at how Drupal 7 is doing it in http://api.drupal.org/api/drupal/includes--database--mysql--database.inc/function/DatabaseConnection_mysql%3A%3A__construct/7:
// Force MySQL to use the UTF-8 character set. Also set the collation, if a
// certain one has been set; otherwise, MySQL defaults to 'utf8_general_ci'
// for UTF-8.
if (!empty($connection_options['collation'])) {
$this->exec('SET NAMES utf8 COLLATE ' . $connection_options['collation']);
}
else {
$this->exec('SET NAMES utf8');
}
I just want to add that you have to make sure your database is created with COLLATE utf8_general_ci or whichever collation you want to use, Else you might end up with another one than intended.
In phpmyadmin you can see the collation by clicking your database and choose operations. If you try create tables with another collation than your database, your tables will end up with the database collation anyways.
So make sure the collation for your database is right before creating tables. Hope this saves someone a few hours lol
I test this code and
$db=new PDO('mysql:host=localhost;dbname=cwDB','root','',
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$sql="select * from products ";
$stmt=$db->prepare($sql);
$stmt->execute();
while($result=$stmt->fetch(PDO::FETCH_ASSOC)){
$id=$result['id'];
}
in my case, i had to add this line:
$conn->exec("set names utf8"); //Support utf8
How it will look:
$conn = new PDO("mysql:host=$servername;dbname=$db", $username, $password);
$conn->exec("set names utf8"); //Support utf8