Hi I have a problem displaying accents on a PDO connection.
I'm learning php a web developing and I started developing using the mysql old php connection
function db_connect()
{
$result = new mysqli('localhost', 'database', 'password', 'user');
if (!$result)
return false;
return $result;
}
my tables use latin1 and utf8 charset and the webpage works fine, showing the words with accents.
I know that the charset and collation is ok beacause it works in the old way.
But when i try to use PDO all the words with accents appers diferent.
Here is and example to optain a category name
$db = database_connect();
$query = " select xxx from yyy where xxxyid = :xxxyid ";
$query_params = array(
':xxxyid' => $xxxyid
);
// Execute the query against the database
$query = $db->prepare($query);
$result = $query->execute($query_params);
if (!$result)
trigger_error('Query failed: ' . mysql_error(), E_USER_ERROR);
$num_xxx = $query->rowCount();
if ($num_xxxs == 0)
return false;
$row = $query->fetch();
return $row['name'];
and my conection is set this way
$db_options = array(
PDO::ATTR_EMULATE_PREPARES => false // important! use actual prepared statements (default: emulate prepared statements)
, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION // throw exceptions on errors (default: stay silent)
, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC // fetch associative arrays (default: mixed arrays)
);
$database = new PDO('mysql:host=server;dbname=dbname;charset=utf8', 'user', 'password', $db_options); // important! specify the character encoding in the DSN string, don't use SET NAMES
// create prepared statement with one parameter for the category ID
I have search trying to find out a way to display letter with accents but i can't solve it.
I have found a solution in the same link you have posted. This solution is working for me:
http://forums.devshed.com/php-faqs-stickies/938827-pdo-security-php-5-3-6-a-post2851557.html#post2851557
function db_connect()
{
$result = new mysqli('localhost', 'database', 'password', 'user');
if (!$result) {
return false;
}
if (!$result->set_charset("utf8")) {
printf("Error loading character set utf8: %s\n", $result->error); exit();
} else {
printf("Current character set: %s\n", $result->character_set_name());
}
return $result;
}
My solution was completly different. Without any new options to PDO and so on.... My problem was when I filled in the values to db right through phpadmin or script, there was allways this kind of problem. But when I filled the db table in spreadsheet software and then import the filled file to db, problem was solved. This knowledge took me allmost one day of live. Hope it helps. Sorry for my english, I am slovakian.
Related
I'm currently using SLIM as an API framework to return some values from a Mysql database via JSON. Using PDO:
// PDO database library
$container['db'] = function ($c) {
$settings = $c->get('settings')['db'];
$pdo = new PDO("mysql:host=" . $settings['host'] . ";dbname=" . $settings['dbname'],
$settings['user'], $settings['pass']);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
return $pdo;
};
my json all returns good except before the return I get this character "l".
This is "l[{"id":"4523","order_date":"2017-04-12""...
That is just part of the response the rest is valid json. The problem is the "l" which is at the beginning. All my results have this.
Here is also one of the routes
// get orders
$app->get('/orders', function ($request, $response, $args) {
$sth = $this->db->prepare("SELECT dr_orderss.id, dr_orderss.order_date, dr_orderss.inspection_date, dr_orderss.inspection_time, dr_orderss.inspector_id,
inspector.name AS inspector, dr_orderss.address, dr_orderss.city
FROM
dr_orderss
INNER JOIN dr_persons AS inspector ON
dr_orderss.inspector_id = inspector.id
GROUP BY dr_orderss.id
ORDER BY dr_orderss.inspection_date DESC LIMIT 10 OFFSET 10");
$sth->execute();
$orders = $sth->fetchAll();
return $this->response->withJson($orders);
});
Any ideas?
There is a 1 just before a <?php tag in one of your files.
Alright, so I believe that there is a better way that I can fetch an array from the database, here's the code right now that I have.
$id = 1;
$userquery = mysql_query("SELECT * FROM login WHERE id='$id'");
while($row = mysql_fetch_array($userquery, MYSQL_ASSOC)) {
$username = $row['username'];
$password = $row['password'];
$email = $row['email'];
}
So If I am not wrong, you want a better way to get all the returned rows from mysql in a single statement, instead of using the while loop.
If thats the case, then I must say mysql_ drivers do not provide any such functionality, which means that you have to manually loop through them using foreach or while.
BUT, since mysql_ is already depricated, you are in luck! you can actually switch to a much better and newer mysqli_ or the PDO drivers, both of which DO actually have functions to get all the returned rows.
For mysqli_: mysqli_result::fetch_all
For PDO : PDOStatement::fetchAll
Eg.
mysqli_fetch_all($result,MYSQLI_ASSOC);
// The second argument defines what type of array should be produced
// by the function. `MYSQLI_ASSOC`,`MYSQLI_NUM`,`MYSQLI_BOTH`.
Like the comments already told you: PHP's mysql driver is deprecated. And you should use prepared statements and parameters.
for example in PDO your code would look something like this:
//connection string:
$pdo= new PDO('mysql:host=localhost;dbname=my_db', 'my_user', 'my_password');
//don't emulate prepares, we want "real" ones:
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
//use exception-mode if you want to use exception-handling:
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$id = 1;
//it's always better to strictly use backticks for db-names (db, tables, fields):
$sql = "SELECT * FROM `login` WHERE `id` = :id";
try
{
//create your prepared statement:
$stmt = $pdo->prepare($sql);
//bind a parameter and explicitly use a parameter of the type integer (in this case):
$stmt->bindParam(":id", $id, PDO::PARAM_INT);
//execute the query
$stmt->execute();
}
catch(PDOException $e)
{
exit("PDO Exception caught: " . $e->getMessage());
}
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$username = $row['username'];
$password = $row['password'];
$email = $row['email'];
}
here you go: your PHP-MySQL routine is save against SQL-injections now and no longer uses deprecated PHP-functions! it's kinda state of the art ;)
I'm trying to create a secure, SQL-injection proof connection to a database using PDO. I've know certain character sets are vulnerable, but that UTF-8 is not one of them. I also know that I should turn PDO's prepared statement emulation mode off. Below is the code that I've put together for the connection. My question is twofold.
Can someone please take a look at my code below to make sure that I'm doing everything correctly? I've tested it, and it works. But is there something else I could add to make it more secure or am I doing it right?
I'm not 100% positive that my syntax for what's inside the array is correct, though I don't get any errors when I do an insert, so I'm inclined to believe that it is. However, is there a way to test or confirm that those attributes are actually being set? Or can someone tell by looking that the syntax is correct and those attributes are definitely being set?
Thanks for any help in advance. My full code for the database connection and an insert using a prepared statement is below.
function addItem($category, $item, $price) {
$dsn = 'mysql:host=localhost;dbname=myDatabase;charset=utf8';
$username = "myUsername";
$password = "myPassword";
$options = array(
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
try {
$link = new PDO($dsn, $username, $password, $options);
$query = $link->prepare("INSERT INTO items (category, item, price)
VALUES (:category, :item, :price)");
$query->bindParam(':category', $category);
$query->bindParam(':item', $item);
$query->bindParam(':price', $price);
$query->execute();
echo "New item added successfully";
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$link = null;
}
I'm quite new to databases and have no idea where I have gone wrong. Please help me find out why I can't connect to my database.
I'm getting an error with Dreamweaver - Dynamicaly-related files cannot be discovered because there is no site definition for this document
My Site root is located in htdocs.
the main file I'm trying to run is "dataquery.php" - htdocs/LetsPlays/dataquery.php
<?php
include 'includes/databaseform.php';
$query = "SELECT * FROM userchanel";
$result = mysql_query($query);
while($person = mysql_fetch_array($result));
{
echo $person['chanelurl'];
}
?>
Dataquery is connected to "databaseform.php" - htdocs/LetsPLays/includes/databaseform.php
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass ='';
$db = 'mysql_tut';
$conn = mysql_connect($dbhost,$dbuser,$dbpas);
mysql_select_db($userchanel);
?>
So I'm trying to connect to userchanel table through user tbl
screenshot: http://imageshack.us/f/23/usertbl.png/
Files run through wordpress are set up to run on 127.0.0.1
Please help me.
Sorry for the noobishness! I have no idea what I'm missing!
When I run the html file all I get is a blank page!
Replace the line
$conn = mysql_connect($dbhost,$dbuser,$dbpas);
with
$conn = mysql_connect($dbhost,$dbuser,$dbpass);
notice the double 's' on $dbpass, also if I may you should not rely on deprecated features when writing new code, use PDO instead, also don't login to db as root, create a user, don't be lazy, with that your database connection code should like:
<?php
$db = new PDO('mysql:dbname=databasename', 'username', 'password',
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
the init command is not actually necessary I just included it cause I always use it, while the querying could be done as
<?php
include 'includes/databaseform.php';
$query = $db->prepare("SELECT * FROM userchanel");
$query->execute();
while(($person = $query->fetch(PDO::FETCH_ASSOC)) !== false);
{
echo $person['chanelurl'];
}
If you're only using one column you should fetch only that as below:
<?php
include 'includes/databaseform.php';
$query = $db->prepare("SELECT chanelurl FROM userchanel");
$query->execute();
while(($channelurl = $query->fetch(PDO::COLUMN)) !== false);
{
echo $channelurl;
}
I didn't include closing braces for php code as they are not necessary also do some error checking var_dump($db->errorInfo()); and var_dump($query->errorInfo()); - didn't include this in the code as I only use them in checking any issues with my code, good luck!
instead of htdocs/LetsPlays/dataquery.php
try localhost/dataquery.php
I recommend you to make and additional file for database connection and include it anywhere you need. Because when you need to push project live you need to change in every file incase file is includeed you need to change just at one place and it effects every where connection for localhost is
<?php
// Replace the variable values below
// with your specific database information.
$host = "localhost";
$user = "root";
$pass = "";
$db = "yourdatabase";
// This part sets up the connection to the
// database (so you don't need to reopen the connection
// again on the same page).
$ms = mysql_pconnect($host, $user, $pass);
if ( !$ms )
{
echo "Error connecting to database.\n";
}
// Then you need to make sure the database you want
// is selected.
mysql_select_db($db);
?>
Save all the above code in one file save it as dbConfig.php and include it any where
like
include ("dbConfig.php");
Now in that file you are connected to db you can interact with database.
Consider a table with three columns id,name and bgname where bgname is a cyrillic equivalent of name.The table is created with UTF-8 collation. After using the following:
<?php
$sql = 'SELECT bgname FROM categories';
function getZapisi($sql,$dbh) {
foreach ($dbh->query($sql) as $row) {
print $row['bgname'] . "<br/>";
}
}
try {
$dbh = new PDO("mysql:host=localhost;dbname=test", 'root', 'pass');
/*** echo a message saying we have connected ***/
getZapisi($sql,$dbh);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
I get ??? from the query no matter if I use cp1251 or utf-8 collation for the bgname column. Thanks in advance
Check the encoding of your page. maybe you're getting correct results but the output html created by apache+php tells the browser to use some other encoding.
Try to look at this : http://dev.mysql.com/doc/refman/5.0/en/charset-connection.html
In fact the problem was terminated using:
$dbh = new PDO("mysql:host=localhost;dbname=test;", 'root', 'pass');
$dbh -> exec("set names cp1251");
Thanks for the effort