I got the following script that returns me the data of a mssql databse, it works fine however special caracters like "ç" "á" "ã", etc is displayed in a weird way.
From what i saw, as it is a mssql this can be a pain.. didnt find any exact response.
I tried to add this line in order to fix:
ini_set('mssql.charset', 'UTF-8');
"Database"=>"programaplo","UID"=>"--","PWD"=>"--","CharacterSet"=>"UTF-8");
header('Content-type: application/json; Charset=UTF-8');
The script
<?php
error_reporting(1);
ini_set('mssql.charset', 'UTF-8');
$serverName = "mssql3.gear.host";
/* Get UID and PWD from application-specific files. */
$connectionInfo = array( "Database"=>"programaplo", "UID"=>"--", "PWD"=>"--","CharacterSet"=>"UTF-8");
$conn = sqlsrv_connect($serverName, $connectionInfo);
if( $conn ) {
echo "Connection established.<br />";
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
$tsql = "SELECT * FROM Obras";
$stmt = sqlsrv_query($conn, $tsql);
if( $stmt === false ) {
echo "Error in executing query.</br>";
die( print_r( sqlsrv_errors(), true));
}
echo "Query: sucesso \n";
$json = array();
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$json[] = $row;
}
header('Content-type: application/json; Charset=UTF-8');
echo json_encode($json);
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn); //Close the connnectiokn first
exit();
?>
The result:
{"Id":2,"NomeObra":"Super Olimpia","idCliente":"Associa\u00e7\u00e3o Super Olimpia","DataPLevantamento":"4 de agosto de 2016","DataRLevantamento":"4 de agosto de 2016","Estado":"Obra conclu\u00edda ","DataRMateriais":"6 de setembro de 2016","DataInicioObra":"18 de setembro de 2016","DataConclusao":"20 de outubro de 2016","DataVestoria":"18 de setembro de 2016","Obs":"","Prompor":"Gas Fenosa","Levantpor":"Ploran\/Paulo","executpor":"Ploran"}
The issue:
Associa\u00e7\u00e3o
Associa\u00e7\u00e3o is the official way to encode binary (or non-ASCII) characters in JSON.
Every Json parser [can|should] understand this notation.
See : JSON and escaping characters
Related
I have an issue where using sqlsrv_fetch_array is returning NULL. I am trying to do a simple query on a view in MS SQL that I have verified in SQL Server Management Studio provides results.
I am running PHP 7.4.4 on Windows Server 2016 x64, with version 5.8 of the PHP SQL drivers and 17.5.2.1 of the ODBC driver.
Similar queries are being run on 4 other views within this database and all work fine. Below is the code I'm testing:
<?php
include("../mscon.php");
$msConnInfo = array( "Database"=>"XYZ", "UID"=>"username", "PWD"=>"password");
$msConn = sqlsrv_connect( $msServerName, $msConnInfo);
if($msConn)
{
//echo "Connection established.\n";
}
else
{
//echo "Connection could not be established.\n";
die( print_r( sqlsrv_errors(), true));
}
$query = "SELECT * FROM Public_Web";
$result = sqlsrv_query($msConn, $query, array(), array( "Scrollable" => 'static' )) or die( print_r( sqlsrv_errors(), true));
if ($result === false) {
die(print_r(sqlsrv_errors(), true));
}
else
echo "We good fam, no errors<br/>\n";
var_dump($result);
if(sqlsrv_has_rows($result))
{
echo "<br/>Rows exist<br/>\n";
$numRows = sqlsrv_num_rows($result);
echo "There are $numRows rows<br/>\n";
while ($row = sqlsrv_fetch_array($result));
{
var_dump($row);
}
}
else
{
echo "no results were found<br/>\n";
}
sqlsrv_free_stmt( $result);
sqlsrv_close($msConn);
?>
The above code outputs lets me know that there are no errors and that 1493 rows exist in the view. But when I do a var_dump on $row it outputs NULL. All of the fields in the view I'm trying to access are varchar and there are only 7 fields total.
I have tried just grabbing one field in my query instead of all fields, no change in results. It seems like I have tried all possible troubleshooting methods.
Anything you can think of would be greatly appreciated. Thanks.
Problem solved. We ended up deleting the view in SQL and recreating it. No idea why it wasn't working properly.
I have a database connection that I have made with a odbc connector. The problem is that I have a field that has special characters, such as accents, and it does not recognize them.
This is my webservice:
<?php
define('CHARSET','UTF-8');
header('Content-Type: text/html; charset=UTF-8');
$usuario='';
$pass='';
$dsn='Tr3';
$conexion = odbc_connect($dsn,$usuario,$pass);
$sql="select total, name, domin from F_VENTA where Ve_FirmaCamion=true";
$rs = odbc_exec($conexion, $sql);
if (!$rs) {
exit("Error al conectar la base de datos");
}
$datos = array();
$i = 1;
while($row = odbc_fetch_array($rs)) {
$datos[] = $row;
$i++;
}
odbc_close($conexion);
$json = json_encode($datos);
echo $json;
?>
This works perfectly. But if the field "name" has some special character (accents, ñ, Ç ...) then the webservice does not return anything to me. The json leaves me blank.
I tried with:
utf8_decode($json);
and
$cadena= htmlentities($json, ENT_QUOTES, "UTF-8");
but don't work.
Any advice? Thanks!
I bring my solution to the problem in case it happens to someone else.
I have managed to solve if before coding the data to json, I pass the mb_convert_encoding() method to the data that comes to us from the database while it traverses it. So I'll encode them in the while loop:
while($row = odbc_fetch_array($rs)) {
$datos[] = mb_convert_encoding($row, "UTF-8", "iso-8859-1");
$i++;
}
It's not a duplicate question about UTF-8 Unicode.
I am new to php and I am trying to create a json response.
I added data into my database properly as follows.
Then I tried to connect to DB and i did it successfully .
but after that when I tried to create a json response by using the following code, it doesn't shows any json response .
My PHP code is :
<?php
define('HOST','localhost');
define('USER','root');
define('PASS','qwerty');
define('DB','carol');
$con = mysqli_connect(HOST,USER,PASS,DB);
if (!$con)
{
echo "Please try later..";
}
else
{
echo "DB Connected..";
}
$sql = "SELECT * from songs";
$res = mysqli_query($con,$sql);
if (!$res)
{
echo "query failed..";
}
else
{
echo "Query success..";
echo (mysqli_num_rows($res));
}
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('title'=>$row[0]),
array('url'=>$row[1]),
array('lyrics'=>$row[2])
);
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
?>
I'm getting only echo of DB Connected , Query Success and 14 (no of rows)
I'm trying PHP for the first time by using some online tutuorials.
if I did any mistake in my code,please help me to find my mistake.
Thank you in advance.
After I added echo var_dump($res);
I got
This question already has answers here:
json_encode() escaping forward slashes
(4 answers)
Closed 6 years ago.
I am trying to get html in a PHP array. When I print the variable out the table is in the correct format but be it is outputted to the array there are added backslashes to my html closing tags (Example: </th>). I didnt think there needed to be any escape characters for slash in PHP. When I print_r($table); it outputs without adding the backslash and outputs the table correctly in my browser but when I add the html table to a PHP array and then output the array as a JSON object it adds the backslash to my html closing tag as shown in the output below from my browser. Any thoughts would be helpful.
Output:
{"data":{"success":"true","carriers":"1,2","table":"
CarrierId<\/th>
CarrierName<\/th>
1<\/td> UHC<\/td><\/tr>
2<\/td> BlueCross<\/td><\/tr><\/table>"}}
PHP:
<?php
// Show all information, defaults to INFO_ALL
//phpinfo();
/*environment:
OS: windows Server 2012 Standard build 9200
IIS: IIS version 8.0.9200.16384 --> Authentication - win auth ->enabled, Anonymou auth -->disabled, CGI -> Impersonate User = true
http://www.microsoft.com/web/downloads/platform.aspx
http://blogs.msdn.com/b/brian_swan/archive/2010/02/10/sql-server-driver-for-php-understanding-windows-authentication.aspx
SQL: - MS SQL server 10.5.1600
PHP: PHP version 5.4.26 for IIS, copy php_sqlsrv_54_ts.dll to C:\Program Files (x86)\PHP\v5.4\ext directroy from
http://www.iis.net/learn/application-frameworks/install-and-configure-php-on-iis/install-the-sql-server-driver-for-php
php.ini file add
extension=php_pdo_sqlsrv_54_ts.dll
extension=php_sqlsrv_54_ts.dll
*/
//Connect to SQL with Authentication
$serverName = "PFIT-00-lync-03"; //serverName\instanceName
$connectionInfo = array( "Database"=>"spicewebinsurance", "UID"=>"spicerest", "PWD"=>"Password1");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
//echo "Connection established.<br />";
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
$tsql= "select convert(varchar,CarrierId) as CarrierId, CarrierName as CarrierName from dbo.Carrier ";
//print_r($tsql) ;
$stmt=sqlsrv_query($conn, $tsql);
$table = "<table> <th>CarrierId</th><th>CarrierName</th>";
// Create table body
if ($stmt) {
$rows = sqlsrv_has_rows( $stmt );
if ($rows === true)
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) )
{
$carriers[] = $row['CarrierId'];
$table .= "<tr><td>";
$table .= $row['CarrierId'];
$table .= "</td><td>";
$table .= $row['CarrierName'];
$table .= "</td></tr>";
}
$table .= "</table>";
$carriers=implode(',', $carriers);
$return=array(
"success"=>"true",
"carriers"=>$carriers,
"table"=>$table
);
}
else
{
$return['success']=false;
}
echo '{"data":'.json_encode($return).'}';
sqlsrv_free_stmt( $stmt);
?>
I haven't read up on why the / is escaped but use option JSON_UNESCAPED_SLASHES:
echo '{"data":'.json_encode($return, JSON_UNESCAPED_SLASHES).'}';
Why won't this table get Truncated? No error is returned. If I run the truncate SQL in SQL Server Management Studio, it truncates normally.
$truncate = "USE energyDB truncate table temp_energydata";
// Initiate connection to energyDB MS SQL server
$connection = sqlsrv_connect($serverName, $connectionInfo);
if( $connection ) {
echo "Connection established.";
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
// Start the query on the Database server
$statement = sqlsrv_query($connection,$truncate);
if( $statement ) {
echo "Truncate Query completed.";
}else{
echo "Query not completed.<br />";
die( print_r( sqlsrv_errors(), true));
#user1745767
$truncate = "USE energyDB truncate table [temp_energydata]";
try like this it tooks hours for met too.