Character encoding error for .php file - php

Have made a route for MarkersController.php which returns json, but when i navigate to the route I get the following error:
The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must be declared in the document or in the transfer protocol.
My route is as follows:
$app->get('/markers/?', function () use ($app) {
$controller = new UF\MarkersController($app);
return $controller->getMarkersJSON();
});
MarkersController.php
<!DOCTYPE html>
<html lang="en">
<head>
{% include 'components/head.html' %}
</head>
<body>
<?php
include('DB_INFO.php');
function getMarkersJSON(){
// Opens a connection to a MySQL server.
$connection = mysqli_connect($server, $username, $password);
if (!$connection) {
die('Not connected : ' . mysqli_error());}
// Sets the active MySQL database.
$db_selected = mysqli_select_db($database, $connection);
if (!$db_selected) {
die('Can\'t use db : ' . mysqli_error());}
// Selects all the rows in the markers table.
$query = "SELECT * FROM tester WHERE 1";
$result = mysqli_query($connection, $query);
if (!$result) {
die('Invalid query: '. mysqli_error());
}
$markers = array();
while ($row = mysqli_fetch_assoc($result)) {
//Assuming "lat" is column name in tester table. Please change it if required.
$lat= $rows['lat'];
//Assuming "lng" is column name in tester table. Please change it if required.
$lng= $rows['lng'];
$markers = array('lat' => $lat, 'lng' => $lng);
}
echo json_encode($markers);
}
?>
</body>
</html>

Do you have Content-Type definition into your head.html?
If the answer is no, try to put
<meta http-equiv="Content-Type" content="text/html;charset=[your-charset]" />
into your head.html

Related

How to build simple page with data from MySQL table?

I spent few days, but since I am completely new in JSON or PHP programming, can't solve my problem without your help.
Here is my problem - I have MySQL DB, I need to extract data from the table and build simple (for e.g. 2 columns) page (html or whatever) with table which consist info from my DB.
I wrote php connector, here it is:
<?php
//require_once("data_connector.php"); //!connector
$dbtype = "MySQL";
$username = ''; // USERNAME
$password = ''; // PASSWORD
$hostname = ''; // HOSTNAME
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
$selected = mysql_select_db("MASTER_TRACKER_DB",$dbhandle)
or die("Could not select MASTER_TRACKER_DB");
/*
//execute the SQL query and return records
$result = mysql_query("SELECT SITE_ID, 3G_SITE_ID FROM MASTER_TRACKER WHERE SITE_ID LIKE '%ABK000%'");
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
echo "SITE_ID:".$row{'SITE_ID'}." 3G_SITE_ID:".$row{'3G_SITE_ID'}.
"<br>";
}
*/
$data = new JSONDataConnector($dbhandle, $dbtype);
//$data->render_table("MASTER_TRACKER_DB.MASTER_TRACKER","SITE_ID","SITE_ID, 3G_SITE_ID");
$data->render_sql("SELECT SITE_ID, 3G_SITE_ID FROM MASTER_TRACKER_DB.MASTER_TRACKER WHERE SITE_ID LIKE '%ABK000%'", "", "SITE_ID, 3G_SITE_ID");
$data->dynamic_loading(30);
//close the connection
//mysql_close($dbhandle);
?>
From this script I see that I am able to connect to DB (I am getting Connected to MySQL message).
Also, if I comment out PHP part which build table, I see that it can build table.
So, as next step, I would like to build table using JSON, so I will use it with Webix, so I made this page:
<!DOCTYPE html>
<html>
<head>
<title>Loading from DB</title>
<link rel="stylesheet" href="codebase/webix.css" type="text/css">
<script src="codebase/webix.js" type="text/javascript"></script>
</head>
<body>
<div class='header_comment'>Loading from DB (sqllite + php)</div>
<div id="testA" style='height:600px'></div>
<hr>
<script type="text/javascript" charset="utf-8">
webix.ready(function(){
grida = webix.ui({
container:"testA",
view:"datatable",
columns:[
{ id:"SITE_ID", header:"SIZE_ID", width:200 },
{ id:"3G_SITE_ID",header:"3G_SITE_ID", width:120 }
// { id:"size", header:"Size" , width:80 },
// { id:"architecture", header:"PC", width:60 }
],
autowidth:true,
url: "data/data.php"
});
});
</script>
</body>
</html>
But seems that I missed something since it shows empty table,
Can anyone please help me to make this page working?
Thanks to all in advance,
Roman

No longer able to connect to mysql using PHP

I keep getting the following error:
Fatal error: Call to a member function fetch_array() on boolean in C:\xampp\htdocs\DeletePlayerSOLN\DeletePlayerExample_SOLN\index.php on line 10
Any idea what the problem is? I searched previous threads and tried to identify the problem for the past few hours. I'm new to PHP.
I'm using Xampp + Mysql.
MySQL connection:
127.0.0.1
3306
root
Default Schema: test
I'm connected through port 443,4433 through Xampp. So I try to connect through /localhost:443/folder..filename..
Connection:
//make a database connection object
$mysqli = new mysqli($server, $user, $pass, $database);
//test if there are database connection errors
if ($mysqli->connect_error)
die("Connect Error " . $mysqli->connect_error);
?>
Index page:
<?php
require "serverCode/connect.php";
$selectPlayer = "SELECT * FROM player ORDER BY playerLastName, playerFirstName";
$results = $mysqli->query($selectPlayer);
$ddlString = "<select name='cboPlayer' size='10'>";
while($row = $results->fetch_array())
{
$ID = $row["playerID"];
$name = $row["playerLastName"] . ", " . $row["playerFirstName"];
$ddlString .= "<option value='$ID'>$name</option>";
}
$ddlString .= "</select>";
$mysqli->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>DELETE Player Page</title>
</head>
<body>
<form name="frmPlayer" action="serverCode/deletePlayer.php" method="get">
Select a player:<p><?php echo $ddlString;?>
<input type="submit" name="btnSubmit"></p>
</form>
</body>
</html>
Line 10 is "while($row = $results->fetch_array())"
It is likely that $mysqli->query() is not producing a proper object due to an error. Try replacing
$results = $mysqli->query($selectPlayer);
with
$results = $mysqli->query($selectPlayer) or trigger_error($mysqli->error."[$selectPlayer]");

HTML document was not declared

This is about retriving the data in form of CSV from Mysql Table : -
Code , I tried :-
<?php
// mysql database connection details
$host = "localhost";
$username = "root";
$password = "hello";
$dbname = "mysql2csv";
// open connection to mysql database
$connection = mysqli_connect($host, $username, $password, $dbname) or die("Connection Error " . mysqli_error($connection));
// fetch mysql table rows
$sql = "select * from tbl_books";
$result = mysqli_query($connection, $sql) or die("Selection Error " . mysqli_error($connection));
$fp = fopen('books.csv', 'w');
while($row = mysqli_fetch_assoc($result))
{
fputcsv($fp, $row);
}
fclose($fp);
//close the db connection
mysqli_close($connection);
?>
Errors Obtained...
04:12:27.093 The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must be declared in the document or in the transfer protocol.1 mysql2csv.php.
your help will be appreciated ...
Add those lines to your html header
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
Edit:
If you are using PHP file:
header('Content-Type: text/html; charset=utf-8');

data retrieved from database in Hebrew presented as question mark

I did all changes as the answer instructed in
this post
in order to be able to print hebrew strings coming from the database but didnt work.
this is my php code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<?php
header('Content-Type: text/html; charset=utf-8');
$servername = "127.0.0.1";
$username = "root";
$password = "";
$dbname = "dbName";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
mysql_query("SET NAMES 'utf8'");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Score: " . $row["score"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
</body>
</html>
every thing works accept that insted of the hebrew strings i only see question marks (???).
any idea why??
Set the Browser's Character Settings to Hebrew.
FireFox:Tools=>Options=>Content=>Advanced=>Fallback Character Encoding = Hebrew
Google Chrome: Menu=>Settings=>Show Advanced Settings=>Language and input settings
UPDATE:
When you save the text first recode the text.
Try using GNU Recode?
$text = mysqli_real_escape_string(recode_string(characterSet,$text));
Where characterSet complies with RFC-1345, e.g. 'latin1'
Valid Character sets: http://www.faqs.org/rfcs/rfc1345.html

PHP Include another php that queries MySQL

In my site im trying to include on the top of each page a "banner" that is itself a separate php page that queries a MySQL database to return a number that displays.
When i goto the exact URL of the banner php url (www.sitename.com/banner.php) it works perfectly.
However, when i include the banner into another page include'banner.php' it returns the following error: Database access error 2002: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
I have 2 ways i need to include this, my main site pages are all php. My forum is phpbb and the file i need to include is HTML so i used (Note, i did ../ back out to the banners root, its not a matter of my file not being found.
Im assuming that when including the scope is different. How would i correctly accomplish this include?
Banner.php
<?php
require("../mysql.inc.php");
check_get($tp, "tp");
$tp = intval($tp);
$link = sql_connect();
$result = sql_query($link, "SELECT COUNT(*) FROM online_count");
if (!$result) {
echo "Database error.<br>\n";
exit;
}
list($total) = mysql_fetch_row($result);
mysql_free_result($result);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="menu_css.css" media="screen"/>
</head>
<body>
<div class="menucenter">
<div class="Online"> <? echo"$total" ?> Online</div>
</body>
</html>
mysql.inc.php
<?php
$SQLhost = "****.db.****.hostedresource.com";
$SQLport = "3306";
$SQLuser = "****";
$SQLpass = "****";
$SQLdb = "****";
function sql_connect()
{
global $SQLhost, $SQLport, $SQLdb, $SQLuser, $SQLpass;
if ($SQLport != "")
$link = #mysql_connect("$SQLhost:$SQLport","$SQLuser","$SQLpass");
else
$link = #mysql_connect("$SQLhost","$SQLuser","$SQLpass");
if (!$link) {
echo "Database access error ".mysql_errno().": ".mysql_error()."\n";
die();
}
$result = mysql_select_db("$SQLdb");
if (!$result) {
echo "Error ".mysql_errno($link)." selecting database '$SQLdb': ".mysql_error($link)."\n";
die();
}
return $link;
}
function sql_query($link, $query)
{
global $SQLhost, $SQLport, $SQLdb, $SQLuser, $SQLpass;
$result = mysql_query("$query", $link);
if (!$result) {
echo "Error ".mysql_errno($link).": ".mysql_error($link)."\n";
die();
}
return $result;
}
function check_get(&$store, $val)
{
$magic = get_magic_quotes_gpc();
if (isset($_POST["$val"])) {
if ($magic)
$store = stripslashes($_POST["$val"]);
else
$store = $_POST["$val"];
}
else if (isset($_GET["$val"])) {
if ($magic)
$store = stripslashes($_GET["$val"]);
else
$store = $_GET["$val"];
}
}
?>
#Craig, there is a possibility that the include file contains other includes which are not getting the right path. Can you paste some codes of the include file for us to validate the error ?
EDIT:
You have a missing quote at the end of the query.
$result = sql_query($link, "SELECT COUNT(*) FROM online_count);
It should be
$result = sql_query($link, "SELECT COUNT(*) FROM online_count");
EDIT:
You have a problem with the quotes. See you check_get function. $val is a variable and you dont need quotes around it. Check the below code.
if (isset($_POST[$val])) {
if ($magic)
$store = stripslashes($_POST[$val]);
else
$store = $_POST[$val];
}
else if (isset($_GET[$val])) {
if ($magic)
$store = stripslashes($_GET[$val]);
else
$store = $_GET[$val];
}
EDIT:
Also remove the quotes from $query:
$result = mysql_query($query, $link);
First things first:
Remove the # from your mysql statements and see if you are getting any other errors related to variables or so. You should not suppress errors while debugging.
Try printing the host, port, user and password variables inside the sql_connect() function and see if you are getting the correct values in your function.
If you have access to your server, check if /var/lib/mysql/mysql.sock exists, and has sufficient permissions.
srwxrwxrwx 1 mysql mysql 0 Sep 21 05:50 /var/lib/mysql/mysql.sock
If all is well till this point, you might want to troubleshoot your MySQL service further. A restart would help flush the connections, if that is the issue. Check a similar thread in SO too.

Categories