Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetching corrupted data from MySQL DB using PDO in php

Tags:

php

mysql

pdo

This is my code in phpstorm.

Fname in MySQL database is a varchar field of student table which contains Persian characters. I set DB collation to UTF8, but still, this code returns me "??? ???" as result.

What is the problem in using it?

<?php
$conn = new PDO("mysql:host = localhost;dbname=university;charset = utf8","root","");
$query = "SELECT * FROM student WHERE status = 1";
$result = $conn->query($query);
while($row = $result->fetch(PDO::FETCH_ASSOC)){
    echo $row['Fname'],"<br>";
}
?>
like image 395
ramin_b Avatar asked Aug 07 '26 13:08

ramin_b


1 Answers

Try

$conn = new PDO("mysql:host=localhost;dbname=university;charset=utf8","root","",
                array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));

instead of

$conn = new PDO("mysql:host = localhost;dbname=university;charset = utf8","root","");
like image 168
Hassaan Avatar answered Aug 09 '26 02:08

Hassaan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!