I want to store special characters in oracle sql, like á, é, ő etc. How can i do it? Every character turns into ?? when i select them. Never used oracle sql its a real pain in the ass for me.
PHP code:
$id = $_POST['id'];
$comment = $_POST['comment-content'];
$username = $_SESSION['username'];
$q = "INSERT INTO hozzaszolasok (username, image_id, content, date_added) VALUES ('$username',$id,'$comment',(SELECT sysdate FROM dual))";
$s = oci_parse($c, $q);
oci_execute($s);
oci_free_statement($s);
oci_close($c);
echo '<script>window.location.href = "comments.php?id=' . $id . '";</script>';
When you open the connection to Oracle DB, specify the character set parameter as AL32UTF8, see the oci_connect() documentation:
$c = oci_connect($username, $password, $connection_string, 'AL32UTF8');
Some of the older globalization information in The Underground PHP and Oracle Manual may still be relevant.
Review the globalization recommendations for your PHP version to make sure your HTML pages are sending characters to the browser correctly.
Related
<?php
$host_name = '***';
$database = '***';
$user_name = '***';
$password = '***';
$link = mysqli_connect($host_name, $user_name, $password, $database);
$con = $_POST['User_ID'];
echo "Se ha ascendido al usuario $con";
$meta= 'a:1:{s:13:"administrator";b:1;}';
$consulta = 'UPDATE ***usermeta
SET
meta_value = $meta
WHERE
User_ID=$con and meta_key = "***capabilities"';
mysqli_query($link, $consulta);
echo "<br><br><br><a href='***'>Volver</a>";
In this code im trying to update an specific column from a table but it just wont work, it appears like it is working but when i go into phpmyadmin the data wont update, here is some info to keep in mind:
mysqli_connect works
query works when i execute it on phpmyadmin
i can do other queries (select) that works
data is correctly received by POST method
those " from variable $meta have to stay
I honestly dont have any idea of what is causing the code to just not work, not a single syntax error displayed or anything else. At first i thought it had something to do with the quote marks but now i dismissed that posibility.
Any help?
There's a catalog of issues here.
Your update statement is wrapped in single quotes - so your variables will not be substituted.
You've used double quotes as a delimiters for strings inside the query - that's not supported by SQL - they should be single quotes.
Table names cannot cannot contain asterisk characters.
That you are not seeing "a single syntax error" is a major issue - the DBMS will be screaming for help when it sees this.
Embedding composite data (json) in a scalar value is just asking for trouble.
Your code is vulnerable to SQL injection.
Whenever your thread of execution leaves PHP (in your code, when you call mysqli_conect() and mysqli_query()) you should be explicitly checking the result of the operation.
For one, you should have some kind of error handling so you know what the problem is. Secondly, you're calling mysqli_query directly instead of using it as a method from your already instantiated class $link.
Also, you really should be using back-ticks for column names and single quotes for column values.
Lastly, you need to escape certain special characters using mysqli_real_escape_string. Alternatively, you could use prepared statements, but I'll keep it simple. Instead of prepared statements, you can use PHP's sprintf function.
<?php
$host_name = '***';
$database = '***';
$user_name = '***';
$password = '***';
$link = mysqli_connect($host_name, $user_name, $password, $database);
$con = $_POST['User_ID'];
echo "Se ha ascendido al usuario $con";
$meta= 'a:1:{s:13:"administrator";b:1;}';
$consulta = "UPDATE `usermeta`
SET
`meta_value` = '%s'
WHERE
`User_ID`='%s' and `meta_key` = 'capabilities'";
$consulta = sprintf(
$consulta,
esc($meta),
esc($con)
);
$link->query($consulta);
echo "<br><br><br><a href='***'>Volver</a>";
function esc($v)
{
global $link;
return $link->real_escape_string($v);
}
?>
Not sure what the asterisks are in the table name, but they shouldn't be there. Also, note that I created a function for handling escaping for brevity.
EDIT:
For error handling, you should check $link->error.
Example:
<?php
$dbError = $link->error ?? null;
if (!empty($dbError))
{
die("A database error occurred: {$dbError}!");
}
?>
I'm trying to convert some php code that uses mysql into mysqli code. I'm not sure why it doesn't work - I didn't write the original code and am not that comfortable with the hash part of it, and it seems to be where the issue is. As I show in the code below, the "error" part gets echo'ed so it's something to do with the hash strings, but I don't really understand why changing to mysqli has broken the code. Both versions of the code are below, and the original code works. I deleted the variables (host name, etc.) but otherwise this is the code I am working with.
Mysql Code:
// Send variables for the MySQL database class.
function db_connect($db_name)
{
$host_name = "";
$user_name = "";
$password = "";
$db_link = mysql_connect($host_name, $user_name, $password) //attempt to connect to the database
or die("Could not connect to $host_name" . mysql_connect_error());
mysql_select_db($db_name) //attempt to select the database
or die("Could not select database $db_name");
return $db_link;
}
$db_link = db_connect(""); //connect to the database using db_connect function
// Strings must be escaped to prevent SQL injection attack.
$name = mysql_real_escape_string($_GET['name'], $db_link);
$score = mysql_real_escape_string($_GET['score'], $db_link);
$hash = $_GET['hash'];
$secretKey=""; # Change this value to match the value stored in the client javascript below
$real_hash = md5($name . $score . $secretKey);
if($real_hash == $hash) {
// Send variables for the MySQL database class.
$query = "insert into scores values (NULL, '$name', '$score');";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
}
Mysqli code (doesn't work):
// Send variables for the MySQL database class.
function db_connect($db_name)
{
$host_name = "";
$user_name = "";
$password = "";
$db_link = mysqli_connect($host_name, $user_name, $password) //attempt to connect to the database
or die("Could not connect to $host_name" . mysqli_connect_error());
mysqli_select_db($db_link, $db_name) //attempt to select the database
or die("Could not select database $db_name");
return $db_link;
}
$db_link = db_connect(""); //connect to the database using db_connect function
// Strings must be escaped to prevent SQL injection attack.
$name = mysqli_real_escape_string($_GET['name'], $db_link);
$score = mysqli_real_escape_string($_GET['score'], $db_link);
$hash = $_GET['hash'];
$secretKey=""; # Change this value to match the value stored in the client javascript below
$real_hash = md5($name . $score . $secretKey);
if($real_hash == $hash) {
// Send variables for the MySQL database class.
$query = "INSERT INTO `scores` VALUES (NULL, '$name', '$score');";
$result = mysqli_query($db_link, $query) or die('Query failed: ' . mysqli_error($db_link));
echo $result;
}
else {
echo "error"; //added for testing. This part gets echoed.
}
mysqli_close($db_link); //close the database connection
One notable "gotchu" is that the argument order is not the same between mysql_real_escape_string and mysqli_real_escape_string, so you need to swap those arguments in your conversion.
$name = mysqli_real_escape_string($db_link, $_GET['name']);
$score = mysqli_real_escape_string($db_link, $_GET['score']);
It's good that you're taking the time to convert, though do convert fully to the object-oriented interface if mysqli is what you want to use:
// Send variables for the MySQL database class.
function db_connect($db_name)
{
$host_name = "";
$user_name = "";
$password = "";
// Enable exceptions
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli($host_name, $user_name, $password);
$db->select_db($db_name);
return $db;
}
$db = db_connect(""); //connect to the database using db_connect function
$secretKey=""; # Change this value to match the value stored in the client javascript below
$real_hash = md5($name . $score . $secretKey);
if($real_hash == $_GET['hash']) {
// Don't include ; inside queries run through PHP, that's only
// necessary when using interactive MySQL shells.
// Specify the columns you're inserting into, don't leave them ambiguous
// ALWAYS use prepared statements with placeholder values
$stmt = $db->prepare("INSERT INTO `scores` (name, score) VALUES (?, ?)");
$stmt->bind_param("ss", $_GET['name'], $_GET['score']);
$result = $stmt->execute();
echo $result;
}
else {
echo "error"; //added for testing. This part gets echoed.
}
// Should use a connection pool here
$db->close();
The key here is to use prepared statements with placeholder values and to always specify which columns you're actually inserting into. You don't want a minor schema change to completely break your code.
The first step to solving a complex problem is to eliminate all of the mess from the solution so the mistakes become more obvious.
The last if statement is controlling whether the mysql query gets run or not. Since you say this script is echoing "error" form the else portion of that statement, it looks like the hashes don't match.
The $hash variable is getting passed in on the URL string in $_GET['hash']. I suggest echo'ing $_GET['hash'] and $real_hash (after its computed by the call to MD5) and verify that they're not identical strings.
My hunch is that the $secretKey value doesn't match the key that's being used to generate the hash that's passed in in $_GET['hash']. As the comment there hints at, the $secretKey value has to match the value that's used in the Javascript, or the hashes won't match.
Also, you may find that there's a difference in Javascript's md5 implementation compared to PHP's. They may be encoding the same input but are returning slightly different hashes.
Edit: It could also be a character encoding difference between Javascript and PHP, so the input strings are seen as different (thus generating different hashes). See: identical md5 for JS and PHP and Generate the same MD5 using javascript and PHP.
You're also using the values of $name and $score after they've been escaped though mysqli_real_string_escape, so I'd suggest making sure Javascript portion is handling that escaping as well (so the input strings match) and that the msqli escape function is still behaving identically to the previous version. I'd suggest echo'ing the values of $name and $score and make sure they match what the Javascript side is using too. If you're running the newer code on a different server, you may need to set the character set to match the old server. See the "default character set" warning at http://php.net/manual/en/mysqli.real-escape-string.php.
I am trying to make an article poster that works perfectly until I put special characters in the html form (like ;,! etc.). I Googled it and found something about the table collation (which is utf8_unicode_ci by default).
I have <meta charset="utf-8"> into the header file and mysqli_set_charset($conn, 'utf8') after connection to the database. Also the form has accept-charset="utf-8" attribute.
Here is what happens after sending the form:
if(isset($_POST['sendForm']))
{
$articleTitle = $_POST['title'];
$articleText = $_POST['text'];
$name = $_SESSION['name'];
$currentDateMySQL = date("Y.m.d");
$sql = "INSERT INTO articles (title, text, owner, date_added) VALUES ('$articleTitle', '$articleText', '$name', '$currentDateMySQL')";
$result = mysqli_query($conn, $sql);
if($result === false)
{
$color = "red";
$infoText = "Could not insert your information into the database. Error number: <b>" . mysqli_errno($conn) . "</b>. :( Try again.";
}
else
{
$color = "green";
$infoText = "Succesfully writen the article into the database. :)";
}
}
Also the given error number is 1064. There is no error in the SQL code, it works perfectly without special characters.
You need do escape every input you trying to insert into a database otherwise you risking sql-injection attacks:
$articleText = mysql_real_escape_string($articleText);
Also you shouldn't use native sql directly anymore, it is deprecated. You should use prepared statements instead.
If you changed your table collation after creation, it does not mean your column collation does match.
All of the following charsets should match so that your data is inserted correctly:
column charset collation
connection charset
Even better, to have the same charset everywhere:
defaut charset
database charset
table charset
column charset
connection charset
I get a text from a database in UTF-8 using JSON and it is in a file right now. When I print the data it is:
توحید در نگاه امام علی (علیه السلام)
But when I insert it in database I get this error:
Insertion Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '�وحید در نگاه امام علی ' at line 1
This is my code
<?php
header('Content-Type: application/json; charset=utf-8');
$con = mysql_connect("localhost","bbbbbbb","bbbbbbb");
mysql_select_db("db", $con);
if(file_exists('./json/file.json')){
$jsondata = file_get_contents('./json/file.json');
$data = json_decode($jsondata, true);
foreach ($data['nodes'] as $node){
$data_element = $node['node'];
$title = $data_element['title'];
$summary = $data_element['summary'];
$body = $data_element['body'];
$id = $data_element['id'];
print $title."\n";
$insert = "INSERT INTO main(title) VALUES ($title)";
mysql_query($insert) or die("Insertion Error: ". mysql_error());
}
}
else
print "File doesn't exist";
The database and its columns are all utf8_general_ci. Why the printed text is not same as the one that is inserted in Database?
The database-connection needs to know it is utf8 too. mysql_set_charset('utf8').
Instead of the deprecated mysql_con, you should have a look at mysqli.
use this
$mysqli = new mysqli("localhost","root","","your_db_name");
$mysqli->query("SET NAMES 'utf8'");
$mysqli->query("SET CHARACTER SET utf8");
Although #ericwenn and #SahilManchal bring up valid points, the immediate error is the failure to quote the string in ... VALUES ($title) ....
Do not blindly put a string into the query.
This will work but it is not safe: ... VALUES ('$title') .... It is subject to a hack called "sql injection". See real_escape_string.
Also, after connecting with mysqli, use
$mysqli->set_charset('utf8');
That is preferable to SET NAMES.
I post the data of dynamically generated textbox in PHP. When I post the data using real_escape_string(), i.e:
$ingredient = mysql_real_escape_string($_POST['ingredient']);
...it doesn't post data from textbox and I use simple $_POST['']; method i.e:
$ingredient = $_POST['ingredient'];
...it gives me error when I use a single quote (') in my text.
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's', 'fgad', '55')' at line 2
this was my old post i solved the problem locally by enabling magic_quotes_gpc = On but when upload this on my server it does't work again so how can i turn on magic quotes on server.
Do you have an open database connection? mysql_real_escape_string needs a MySQL server to talk to in order to function.
You might want to try
$ingredient = $_POST['ingredient'];
$ingredient = mysql_real_escape_string($ingredient);
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$firstname = mysqli_real_escape_string($con, $_POST['firstname']);
$lastname = mysqli_real_escape_string($con, $_POST['lastname']);
$age = mysqli_real_escape_string($con, $_POST['age']);
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('$firstname', '$lastname', '$age')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
you must used connection db see
http://php.net/manual/en/mysqli.real-escape-string.php
you can use also
string mysqli::real_escape_string ( string $escapestr )
I think this might be related to the "magic" quotes feature -- see this page for details: Magic Strings & SQL
Basically, because of problems with SQL injection attacks, they pre-escaped strings with quotes after a certain version of PHP (I think it was 5.0, but I could be wrong). So the end result is that now your software has to check for the software version and behave differently depending on whether the string is already escaped or not.