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?
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 am having some headaches with JSON not returning as JSON. I get no errors, just no data. The browser shows the data in the response.
I know it's not returning as JSON because setting the dataType in the AJAX section causes it to display nothing. If I remove the dataType statement, it displays the data.
I've played around with encoding in the connection string, in the queries, as a header, and in the AJAX section all to no avail. My database is in UTF-8, general_ci.
AJAX:
$.ajax({
contentType: 'application/json; charset=UTF-8',
data: {'career' : $career},
dataType: 'json',
url: 'functions.php',
success: function(data) {
$("careerdata").html(data);
},
PHP:
if (isset($_GET['career'])) {
require_once 'config.php';
$query = $dbconnect->prepare("select * from jobs where Category = :category");
$query->bindParam(':category', $category);
$category = $_GET['career'];
$query->execute();
$result = $query->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);
$dbconnect = null;
return;
} else {
echo 'No career data found.';
};
Connection file:
try {
$dbconnect = new PDO("mysql:host=$host;dbname=$database", $user, $pass, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
$dbconnect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
};
If any more info is needed, please let me know.
Working page is https://www.shardsmith.com/career.php and the actual query is https://www.shardsmith.com/functions.php (but it won't work independently because of the GET variable).
It seems that the MySQL (php) client does assume another client encoding than UTF-8. You can request the correct encoding using
$dbhconnect->exec("SET NAMES utf8");
directly after you connect to the database.
Alternatively, you can use PDO::MYSQL_ATTR_INIT_COMMAND (see http://php.net/manual/de/ref.pdo-mysql.php) in your connection config:
$dbconnect = new PDO("mysql:host=$host;dbname=$database", $user,
$pass, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
And be careful with unchecked frontend parameters: this is an open door for SQL injections. Either use a prepared statement like this:
$query = $dbconnect->prepare("select * from jobs where Category = :cat");
$query->execute(array(':cat' => $_GET['career']));
or escape the input paramerers first:
$cat = $dbhconn->quote($_GET['career']);
$res = dbhconnect->query("select * form jobs where Category = {$cat}")->fetchAll();
I ended up figuring it out myself. The json itself was fine. At some point I completely forgot about each-looping through the key-value pairs in order to actually display them. For example:
$.each(data, function(key,value) {
var $itemid = value.ItemID;
var $db = value.DB;
var $job = value.Job;
var $recipe = value.Recipe;
var $level_range = value.Level_Range;
var $level = value.Level;
var $grade = value.Grade;
var $rarity = value.Rarity;
var $complete = value.Complete;
$("careerdata table").append("<tr class=\"recipe\" id=\""+$recipe+"\">"
+"<td>"+$level+$grade+"</td>"
+"<td class=\"icon\"><img style=\"background: url(\'/images/items/"+$job+"/"+$itemid+".png\') 0 1px/42px 42px;\" src=\"/images/items/reflection.png\" /></td>"
+"<td class=\""+$rarity+"\">"+$recipe+"</td>"
+"<td><input class=\"complete\" type=\"checkbox\" value=\""+$complete+"\"></td>"
+"</tr>");
});
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." ";
Im my project only image name are stored to SQL So that i can display it using name and image file is stored in folder
My problem is unable to display image since i have to specify path
<?php
// Connection data (server_address, database, name, poassword)
$hostdb = 'localhost';
$namedb = '3ss';
$userdb = 'sanoj';
$passdb = '123456';
try {
// Connect and create the PDO object
$conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
$conn->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8
// Define and perform the SQL SELECT query
$sql = "SELECT * FROM `mobile` where id=50";
$result = $conn->query($sql);
// Parse returned data, and displays them
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo $row['id']. '/'. $row['mcat']. '/'. $row['image1']. '/'.'<li><img src=\poster\process\mobile\thumb\"',$row['image1'],'"></li>' .'/'. $row['image3']. '<br />';
}
$conn = null; // Disconnect
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
You can use php variables inside the html tag. This should work:
.'<li><img src=\poster\process\mobile\thumb\$row["image1"]></li>'
It is important that you are consistent with when to use double quotes and when not to. the $row should have different quotes than the ones surrounding the html tag.
I catch html from two files with javascript. In one of the files I include info to connect to my DB.
But when I do, php adds two " to my html. All files are saved with the encoding UTF8.
Index.php html
<div class="f-l" id="right-column"></div>
Javascript.js
$('#lead, #prospects').change(function() {
var kund_id = 'kund_id=' + $('#lead option:selected, #prospects option:selected').attr('value');
$.post(
'get_kund.php',
kund_id,
function(data){
$('#center-column').html(data)
});
$.post(
'get_kontaktperson.php',
kund_id,
function(data){
$('#right-column').html(data)
}); return false;
});
get_kontaktperson.php
include("db_connect.php");
$kund_id = $_POST['kund_id'];
$qry = "SELECT * FROM kontaktperson WHERE kund_id='$kund_id' ORDER BY id DESC";
$result=mysql_query($qry);
while($row=mysql_fetch_array($result)) {
echo 'some html'; }
db_connect.php
require_once('db_info_login.php');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: '
. mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die('Unable to select database');
}
mysql_query('SET NAMES utf8')
This adds "" above the html code from get_kontaktperson.php:
Why this seems to be a problem for me, the <div class="kontaktperson"> is missplaced by something. If I take away the include it will show the html content correct. But when I put in some data, this will occur. Margin on the right column...
Those two quotation marks are used by Chrome's web inspector to denote content inside the element. As there is no content, two quotation marks are shown without anything inside them.