Trouble retrieving MySQL data using JSON - php

I am trying to use JSON w/PHP to retrieve data from MySQL database and have run into a problem. I get my table back from Server except when I include the Comments field in my query. I checked out the JSON in JSON LInt and that came back ok. The MySQL query checks out on its own. And looking in firebug I see SyntaxError: JSON.parse: bad control character in string literal at line 1 column 184 of the JSON data. I just get my header on the page. the code is:
example.php
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$conn = new mysqli("localhost", "*****", "*****", "inventory_form");
$result = $conn->query("SELECT Comments, FName, LName, Eqpmnt_Brwd, Date_Taken, Brwd_Rsn, Service_Tag FROM Inventory");
$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "[") {$outp .= ",";}
$outp .= '{"Comments":"' . $rs["Comments"] . '",';
$outp .= '"FirstName":"' . $rs["FName"] . '",';
$outp .= '"Eqpmnt_Brwd":"'. $rs["Eqpmnt_Brwd"] . '",';
$outp .= '"Date_Taken":"'. $rs["Date_Taken"] . '",';
$outp .= '"Brwd_Rsn":"'. $rs["Brwd_Rsn"] . '",';
$outp .= '"ServiceTag":"'. $rs["Service_Tag"] . '"}';
}
$outp .="]";
$conn->close();
echo($outp);
?>
index.html:
<!DOCTYPE html>
<html>
<head>
<style>
h1 {
border-bottom: 3px solid #cc9900;
color: #996600;
font-size: 30px;
}
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f1f1f1;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style>
</head>
<body>
<h1>SHS Inventory Form</h1>
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "inventory_table.php";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var arr = JSON.parse(response);
var i;
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].Comments +
"</td><td>" +
arr[i].FirstName +
"</td><td>" +
arr[i].Eqpmnt_Brwd +
"</td><td>" +
arr[i].Date_Taken +
"</td><td>" +
arr[i].Brwd_Rsn +
"</td><td>" +
arr[i].ServiceTag +
"</td></tr>";
}
out += "</table>"
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
</html>
and a sample of response text is:
"[{"Comments":"","FirstName":"Nadine","Eqpmnt_Brwd":"Apple Video Dongle","Date_Taken":"2014-09-05","Brwd_Rsn":"Returned","ServiceTag":""},{"Comments":"Wants to check out hovercam. Can retrieve it if anyone needs a hovercam.","FirstName":"Nicole ","Eqpmnt_Brwd":"Hovercam","Date_Taken":"2014-09-04","Brwd_Rsn":"Borrowed","ServiceTag":"075642"},{"Comments":"with SD card All six cameras borrowed on 9/8/14 will be used throughout that school week.Expected return date is Monday 9/15/14","FirstName":"George","Eqpmnt_Brwd":"Nikon D3100 Camera","Date_Taken":"2014-09-08","Brwd_Rsn":"Borrowed","ServiceTag":"074753"},{"Comments":"w/ SD card "
Is there a problem with some of the text in the Comments field needing to be escaped? I've looked online but cant find much on the topic. Realize you should probably use PDO for this but good luck finding examples. I will work on that once I get this example working properly.

As #Barmar said use json_encode instead of trying to construct a JSON string by hand. For example:
$data = array();
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
$data[] = $rs;
}
$conn->close();
echo json_encode($data);
In response to your comment/question about PDO... With PDO you can simplify this by using PDOStatement::fetchAll:
$pdo = new PDO($dsn, $user, $pass);
$stmt = $pdo->query("SELECT Comments, FName, LName, Eqpmnt_Brwd, Date_Taken, Brwd_Rsn, Service_Tag FROM Inventory");
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($data);

Related

How to fetch data from php to html

Good Day! i would like to know on how to fetch data from php to html. I'm newbie with this kind of code can you help me? Here is my codes.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.6.0/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet#1.6.0/dist/leaflet.js"></script>
<style>
#map {position: absolute; top: 0; bottom: 0; left: 0; right: 0;}
</style>
</head>
<body>
<?php
$mysql_hostname = "localhost";
$mysql_username = "root";
$mysql_password = "root";
$mysql_database = "dtable";
$conn= mysqli_connect($mysql_hostname,$mysql_username,$mysql_password,$mysql_database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, Longitude, Latitude FROM androidtable where Emp_ID = '212' order by Date_log desc";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["id"]. "</td><td>" . $row["Longitude"] . "</td><td>"
. $row["Latitude"]. "</td></tr>";
}
echo "</table>";
} else { echo "0 results"; }
$conn->close();
?>
<div id = "map"></div>
<script>
var map = L.map('map').setView([7.1309155, 125.6402975], 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
L.marker([7.1309155, 125.6402975]).addTo(map)
.bindPopup('Employee 212 Location.<br> RealTime Tracker.')
.openPopup();
</script>
</body>
</html>
instead of this var map = L.map('map').setView([7.1309155, 125.6402975], 13); to this var map = L.map('map').setView([$row["Latitude"], $row["Longitude"]], 13);. I was hoping that you can help me with this problem.
You use JavaScript on your code so you can not directly do what you want with JavaScript and PHP. You may use AJAX to do this.
Here is a close question: How do I pass variables and data from PHP to JavaScript?
You can use this link, have a nice day.
You can echo out the array inside <script></script> like this
var ar = <?php echo json_encode($ar) ?>; <br>
then use loop to set the map

Update the contents of table rather then complete table using ajax and PhP

I am beginner in the PhP and Jquery. So, may be the solution to this question will be easy. I am successfully updating table using ajax and PhP. The issue is that table is updated by removing the all the data, and then populating new data.
I am looking for any other approach. After getting new data through PhP, compare new data with old data,...if there is some issue in hardware, then change the status..also keep the time from which the hardware stopped working. I ask question before Put data from Postgresql database to table using Ajax and PhP, in which #Mcsky suggested me a solution, but I did not get his approach. So, How to update table data only?, instead of complete refresh of table, which feels like page refresh. here is my client code: estat_hardware.php
<!DOCTYPE html>
<html>
<head>
<style> <?php include './../css/estat_hardware.css'; ?> </style>
</head>
<body>
<div class="maindiv">
<div id="tagsDiv">
<h3>Estat Tags</h3>
<?php
echo '<table id="tags_table">';
echo "<thead>";
echo "<tr>";
echo '<th>' . "TAG" . '</th>';
echo '<th>' . "BATERIA" . '</th>';
echo '<th>' . " VIST ÚLTIMA COP " . '</th>';
echo '<th>' . "ESTAT" . '</th>';
echo "</tr>";
echo "</thead>";
echo "<tbody>";
echo "</tbody>";
echo '</table>';
?>
</div>
</div>
<script src='http://code.jquery.com/jquery-3.1.1.min.js'></script>
<script>
$(document).ready(function(){
UpdateHTMLTable();
setInterval(function() {
UpdateHTMLTable();
}, 5000); // 5000 millisecond(5 second)
function UpdateHTMLTable(){
/* $('#tags_table tbody').empty(); */
$('#tags_table tbody').html("");
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
data = JSON.parse(this.responseText);
for (i = 0; i < data.length; i++) {
console.log(data[i]);
var row = $("<tr />");
$("<td />").text(data[i].mac).appendTo(row);
$("<td />").text(data[i].battery).appendTo(row);
$("<td />").text(data[i].ts).appendTo(row);
$battery_beacon=data[i].battery;
if($battery_beacon<15)
{
$status="Canvi Batteria";
}
else{
$status="Correcte ";
}
$("<td />").text($status).appendTo(row);
row.appendTo('#tags_table');
}
}
};
xmlhttp.open("GET", "pages/estat_hardware_server.php", true);
xmlhttp.send();
}
});
</script>
</body>
</html>
Server code is:
<?php
header("Content-Type: application/json; charset=UTF-8");
$host = ip";
$port ="portNumber";
$user = "abc";
$pass = "....";
$db = "name";
$con = pg_connect("host=$host dbname=$db user=$user password=$pass")
or die ("Could not connect to server\n");
$query = "query string for database";
$result = pg_query($con, $query) or die("Cannot execute query: $query\n");
if(pg_num_rows($result))
{
$data=array();
while($row=pg_fetch_array($result))
{
$data[] = array(
'mac'=>$row['mac'],
'ts' =>$row['ts'],
'battery'=>$row['battery']
);
}
echo json_encode($data);
pg_free_result($result);
pg_close($con);
}
?>

How to return more than one LIKE from MySQL in PHP?

SOLVED.
When I do search in my database (through a console) the return shows rows where the word "keywordOne" and "keywordTwo" occurs:
SELECT name FROM tablename WHERE name LIKE '%keywordOne&' OR name LIKE '%keywordTwo%';
but when I try to run that query from .php code, the return only shows the rows with keywordOne:
$result = $conn->query($sql);
if($result->num_rows == 0){
echo "<br>No rows found. ";
} else {
$how_many = 0;
echo '<table style="border: 1px solid black; padding: 10px; ">';
while($row = mysqli_fetch_array($result)) {
$name = $row['name'];
echo '<tr><td style="border-bottom: 1px solid black;">Found (by name): </td>' . '<td>' . $name . '</td></tr>';
$how_many = $how_many + 1;
}
echo '</table>';
echo "<br>";
echo "In total: " . $how_many . " rows found.";
Why that happened? Or am I printing the rows incorrectly on .php script?
When I run
$sql = "SELECT * FROM tablename WHERE name REGEXP 'keywordOne|keywordTwo' ";
command, the return on .php script is correct (with both keywords).
What's missing?

Angular crashing while there is a "Enter" in json file

So basically i have json file made from SLQ database by PHP script
Geting angular to read json and binds to scope
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://kserwach.nazwa.pl/extremerun/data.php")
.success(function (response) {$scope.names = response.records;});
});
You can look at json file by simply enterning this link
[http://kserwach.nazwa.pl/extremerun/data.php][1]
My problem is that, while i put any "new line" in SQL angular crashes. How can i make angular to not crash while someone press "enter button" while writing new desc? Or else how to make json file to replace this "enter" with some html tag, and then how to make angular to read this html tag?
This is how i read mySQL data
<?php
$user='user_name';
$password='password';
$dbname='db_name';
$host='host';
try
{
$db = new PDO('mysql:host='.$host.';dbname='.$dbname.';',$user,$password,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
}
catch (PDOException $e)
{
print "Error!: " . $e->getMessage() . "<br/>"; die();
}
$stmt = $db-> query('SELECT name,description,surname,photo FROM mates');
$temp = 0;
$outp = "";
foreach($stmt as $row)
{
if($temp == 0) {
$outp .= '{"Name":"'.$row['name'].'",';
$outp .= '"Photo":"'.$row['photo'].'",';
$outp .= '"Surname":"'.$row['surname'].'",';
$outp .= '"Desc":"'.$row['description'].'"}';
$temp = 1;
} else {
$outp .= ',{"Name":"'.$row['name'].'",';
$outp .= '"Photo":"'.$row['photo'].'",';
$outp .= '"Surname":"'.$row['surname'].'",';
$outp .= '"Desc":"'.$row['description'].'"}';
}
}
$outp ='{"records":['.$outp.']}';
echo($outp);
?>
And then, sorry for my bad english. Just not primary, or even secondary language.

How can I get column names via PDO/Sqlite when query returns no records?

The following code allows me to pass an SQL statement to a class and call its method to display a nice table of the results, including column names.
However, if there are no results, I still want the column names to be displayed.
Unfortunately, getColumnMeta is not returning any data as it does in other examples I have found.
Does anyone know how to get getColumnMeta() working in this example, or another way I can get the names of the fields from the SQL statement when the query returns zero rows?
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
table thead tr td {
background-color: #ddd;
padding: 5px;
font-weight: bold;
}
table tbody tr td {
background-color: #eee;
padding: 5px;
color: navy;
}
div.sqlCommand {
font-family: courier;
}
h2 {
border-bottom: 1px solid #777;
}
</style>
</head>
<body>
<?php
$sql = 'SELECT LastName,FirstName,Title FROM employee WHERE 1=2 ORDER BY LastName';
echo '<h2>sqlite</h2>';
$dbSqlite = new DbSqlite($sql);
echo $dbSqlite -> displayHtmlTable();
class DbSqlite {
protected $sql;
protected $records = array();
protected $columnNames = array();
public function __construct($sql) {
$this -> sql = $sql;
$this -> initialize();
}
protected function initialize() {
$db = new PDO('sqlite:chinook.sqlite');
$result = $db -> query($this -> sql);
$result -> setFetchMode(PDO::FETCH_ASSOC);
$columnsAreDefined = false;
while ($row = $result -> fetch()) {
$this -> records[] = $row;
if (!$columnsAreDefined) {
foreach ($row as $columnName => $dummy) {
$this -> columnNames[] = $columnName;
}
$columnsAreDefined = true;
}
}
if (count($this -> records) == 0) {
$total_column = $result -> columnCount();
var_dump($total_column);
for ($x = 0; $x < $total_column; $x++) {
$meta = $result -> getColumnMeta($x);
//var_dump($meta);
//bool(false)
//$column[] = $meta['name'];
}
}
}
public function displayHtmlTable() {
$r = '';
$r .= '<div class="sqlCommand">' . $this -> sql . '</div>';
$r .= '<table>';
$r .= '<thead>';
$r .= '<tr>';
foreach ($this->columnNames as $columnName) {
$r .= '<td>' . $columnName . '</td>';
}
$r .= '</tr>';
$r .= '</thead>';
$r .= '<tbody>';
foreach ($this->records as $record) {
$r .= '<tr>';
foreach ($record as $data) {
$r .= '<td>' . $data . '</td>';
}
$r .= '</tr>';
}
$r .= '</tbody>';
$r .= '<table>';
return $r;
}
}
?>
</body>
</html>
Meta table sqlite_master contains all information. Following code will parse sqlite_master into column names as $colnames:
$colnames = array() ;
$stmt = $dbh->prepare("SELECT sql FROM sqlite_master WHERE tbl_name = 'put_table_name_here'") ;
$stmt->execute() ;
$row = $stmt->fetch() ;
$sql = $row[0] ;
$r = preg_match("/\(\s*(\S+)[^,)]*/", $sql, $m, PREG_OFFSET_CAPTURE) ;
while ($r) {
array_push( $colnames, $m[1][0] ) ;
$r = preg_match("/,\s*(\S+)[^,)]*/", $sql, $m, PREG_OFFSET_CAPTURE, $m[0][1] + strlen($m[0][0]) ) ;
}
First approach I would try:
run the query
check if there were results returned
if yes, run Your initialize() and displayHtmlTable
if no, run Your initializeEmptyResult() that will run the next query and just fills $this->columnNames[]:
SELECT column_name FROM information_schema.columns WHERE table_name = 'my_table_name'
The query is dependent on MySQL bu there should be more alternatives for other databases, or still You can run DESCRIBE table and parse columns names from the result (should be SQL DBMS undependent).
Second that is I think easier to accomplish: if there are no results returned from the query, do not display a coulmn names nor table at all, just display a message: 'No results found.'. This could be achieved within Your displayHtmlTable method:
public function displayHtmlTable() {
$r = '';
$r .= '<div class="sqlCommand">' . $this -> sql . '</div>';
if(count($this->records) > 0) {
$r .= '<table>';
$r .= '<thead>';
$r .= '<tr>';
foreach ($this->columnNames as $columnName) {
$r .= '<td>' . $columnName . '</td>';
}
$r .= '</tr>';
$r .= '</thead>';
$r .= '<tbody>';
foreach ($this->records as $record) {
$r .= '<tr>';
foreach ($record as $data) {
$r .= '<td>' . $data . '</td>';
}
$r .= '</tr>';
}
$r .= '</tbody>';
$r .= '<table>';
} else {
$r .= '<div class="no-results">No results found for query.</div>';
}
return $r;
}
And You do not have to bother with column names...
EDIT: For the first case found a query for SQLite that should do the same as select * from information_schema.columns where table_name = 'xxx':
PRAGMA table_info(table-name);
Just to expand on #shadyyx comment:
PRAGMA table_info(table-name);
I don't have a PDO_SQLITE sandbox handy, but using the native SQLite3 driver, this snippet will get you the column names for table table-name in $arrColumns:
$db = new SQLite3('db.sqlite');
$db->query('PRAGMA table_info(table-name)');
while ($col = $res->fetchArray(SQLITE3_ASSOC)) {
$arrColnames[]=$col['name'];
}
print_r($arrColnames);

Categories