I am trying to display the contents of a "users" table in my MYSQL database using PHP,JQUERY and JSON.
Here is the PHP file:
<?php
$host = "localhost";
$user = "root";
$pass = "";
$databaseName = "ITSM";
$tableName = "signup_and_login_table";
include 'database_connection.php';
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$result = mysql_query("SELECT * FROM $tableName");
$array = mysql_fetch_row($result);
echo json_encode($array);
?>
On my HTML page i have a simple table im trying to target:
<table id="personDataTable">
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</table>
This is the jquery ajax, I want it to loop through all the users and other table entities to display all the contents of the Database table on the page, Im currently just getting "undefined".
$(function ()
{
$.ajax({
url: 'CMGetdata.php',
data: "",
dataType: 'json',
success: function(data, textStatus, jqXHR) {
drawTable(data);
}
});
});
function drawTable(data) {
for (var i = 0; i < data.length; i++) {
drawRow(data[i]);
}
}
console.log("test");
function drawRow(rowData) {
var row = $("<tr />")
$("#personDataTable").append(row);
row.append($("<td>" + rowData.id + "</td>"));
row.append($("<td>" + rowData.firstName + "</td>"));
row.append($("<td>" + rowData.lastName + "</td>"));
}
Any assistance to be pointed in the correct direction would be greatly appreciated thanks.
Try This-
$result =$con->query("SELECT * FROM tableName");
$array = $result ->fetch_all(MYSQLI_ASSOC);
foreach($array as $array)
{
$array['example'];
//another
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I made a simple application php & ajax and I don't know why it is not working.
My code:
<?php
$grId = $_GET["groupId"];
$limit = $_GET["limit"];
if ($limit <= 0) {
$limit = 10;
}
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "productsdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, displayName, role, groupId FROM user where groupId = ? limit ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ii", $grId, $limit);
$stmt->execute();
$stmt->bind_result($id, $displayName, $role, $groupId);
$users = array();
while($stmt->fetch()) {
$user = new StdClass();
$user->id = $id;
$user->displayName = $displayName;
$user->role = $role;
$user->groupId = $groupId;
array_push($users, $user);
}
echo json_encode($users);
$stmt->close();
$conn->close();
?>
json-client-get.html:
<html>
<head>
<script src="jquery-2.1.4.js"></script>
<script>
$(document).ready(function() {
$('#students').hide();
$("#getStudentsButton").click(function() {
$.ajax({
dataType: "json",
type: "GET",
url: "getStudentsJson.php",
data: {
groupId: 1,
limit: 7
},
success: renderTable
});
});
function renderTable(data) {
var trHTML = '';
$.each(data, function(i, item) {
trHTML += '<tr><td>' + item.id + '</td><td>' + item.displayName + '</td><td>' + item.role + '</td> <td> ' + item.groupId + ' </td></tr>';
});
$('#students').append(trHTML);
$('#students').show();
}
});
</script>
</head>
<body>
Lista studentilor din grupul 1:
<div id="maindiv">
<table id="students" border="1">
<tr>
<th>Id</th>
<th>Name</th>
<th>Role</th>
<th>GroupId</th>
</tr>
</table>
</div>
<input id="getStudentsButton" type="button" value="Load students" />
</body>
</html>
I craete in phpmyadmin a new database productsdb with the table user and a single value inserted.
When I run localhost/folder/json-client-get.html and press the button Load student nothing is happening.
EDIT(picture with my db but I don't know why the photo is not working)
I tested your code and there is an issue with SQL which you have:
$sql = "SELECT id, displayName, role, groupId FROM user where groupId = ? limit ?";
check table structure and ensure which you have these fields
for sure run this query in your phpmyadmin and see result
SELECT id, displayName, role, groupId FROM user where groupId = 1 limit 7
This answer will not solve your issue but simply show you how to debug your ajax call. I think you will benefit more from knowing how to solve it than getting it solved.
Take a look at the following ajax call:
$(document).ready(function(e) {
$.ajax({
url: 'ajaxScript.php',
type: 'POST',
data: {
'somevar': 'somevalue'
},
success: function(result)
{
alert('Successfully called');
},
error: function(exception)
{
alert('Exeption:'+exception);
}
})
})
I have a webpage http://skywateryachts.com/disp_new.php where I formatted the currency with no problem.
However, the sorting of the listed price appears to be by order of the first several digits rather than total value. Example, $110,000 appears before $110,900,000 when sorted descending.
The MySQL field type is INT and I just formatted the SELECT statement for the currency symbol.
I'm using the dataviewer extension in the WYSISWYG Webbuilder and custom formatting the code. But I am new to customizing MySQL.
I'm thinking it would be better to eliminate the sort feature and do it myself but would like first to know what the issue could be with the sorting of the digits.
Thanks
Pertinent code:
<script type="text/javascript">
$(document).ready(function()
{
$.fn.alternateRowColors = function()
{
$('tbody tr:odd', this).removeClass('even').addClass('odd');
$('tbody tr:even', this).removeClass('odd').addClass('even');
return this;
};
$('table.sortable').each(function()
{
var $dataviewer = $(this);
$dataviewer.alternateRowColors();
$('th', $dataviewer).each(function(column)
{
var $header = $(this);
var findSortKey;
findSortKey = function($cell)
{
return $cell.find('.sort-key').text().toUpperCase() + ' ' + $cell.text().toUpperCase();
};
if (findSortKey)
{
$header.addClass('clickable').hover(function()
{
$header.addClass('hover');
}, function()
{
$header.removeClass('hover');
}).click(function()
{
var sortDirection = 1;
if ($header.is('.sorted-asc'))
{
sortDirection = -1;
}
var rows = $dataviewer.find('tbody > tr').get();
$.each(rows, function(index, row)
{
var $cell = $(row).children('td').eq(column);
row.sortKey = findSortKey($cell);
});
rows.sort(function(a, b)
{
if (a.sortKey < b.sortKey) return -sortDirection;
if (a.sortKey > b.sortKey) return sortDirection;
return 0;
});
$.each(rows, function(index, row)
{
$dataviewer.children('tbody').append(row);
row.sortKey = null;
});
$dataviewer.find('th').removeClass('sorted-asc').removeClass('sorted-desc');
if (sortDirection == 1)
{
$header.addClass('sorted-asc');
}
else
{
$header.addClass('sorted-desc');
}
$dataviewer.find('td').removeClass('sorted').filter(':nth-child(' + (column + 1) + ')').addClass('sorted');
$dataviewer.alternateRowColors();
});
}
});
});
<div id="dataviewer" style="position:absolute;overflow:auto;left:269px;top:390px;width:803px;height:980px;z-index:46">
<?php
$mysql_host = 'localhost';
$mysql_user = 'xxxx';
$mysql_password = 'xxxx';
$mysql_database = 'xxxx';
$mysql_table = 'boats';
$db = mysql_connect($mysql_host, $mysql_user, $mysql_password);
mysql_select_db($mysql_database, $db);
$sql = "SELECT Date_Listed, Est_DOM, LOA, Builder, Built, Currency, concat('$', format(Listing_Price, 0)), NFS_USA FROM ".$mysql_table;
$result = mysql_query($sql, $db);
?>
<table cellpadding="0" cellspacing="1" width="100%" class="sortable paginated">
<thead>
<tr>
<th>List Date</th>
<th> Est DOM</th>
<th> Length</th>
<th> Builder</th>
<th> Year Built</th>
<th> Currency</th>
<th> Listing Price</th>
<th> NFS USA</th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysql_fetch_row($result))
{
echo " <tr>\n";
foreach ($row as $cell)
{
echo " <td>" . $cell . "</td>\n";
}
echo " </tr>\n";
}
?>
</tbody>
</table>
</div>
You probably are sorting by your formatted column in the field list of your SELECT. Instead, in your ORDER BY reference the name of the integer column directly from your table.
So if you have this:
SELECT FORMAT(foo, '$99,999,999.99')
FROM bar
ORDER BY 1
instead do this
SELECT FORMAT(foo, '$99,999,999.99')
FROM bar
ORDER BY foo
(Ignore the actual syntax of the formatting - I always have to look that stuff up to get the right function and syntax and I'm just doing it for an example.)
I am trying to get several sections of data in json in one go like
<?php
$host = "localhost";
$user = "root";
$pass = "";
$databaseName = "world";
$tableName = "city";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$result = mysql_query("SELECT * FROM $tableName limit 15"); //query
//fetch result
$jsonData = array();
while ($array = mysql_fetch_row($result)) {
$jsonData[] = $array;
}
//first section
echo '<section id="stuff">';
echo json_encode($jsonData);
echo '</section>';
//section two ....
?>
I return json wrapped in html5 section tag
<section id="stuff">[["1","Kabul","AFG","Kabol","1780000"],["2","Qandahar","AFG","Qandahar","237500"],["3","Herat","AFG","Herat","186800"],["4","Mazar-e-Sharif","AFG","Balkh","127800"],["5","Amsterdam","NLD","Noord-Holland","731200"],["6","Rotterdam","NLD","Zuid-Holland","593321"],["7","Haag","NLD","Zuid-Holland","440900"],["8","Utrecht","NLD","Utrecht","234323"],["9","Eindhoven","NLD","Noord-Brabant","201843"],["10","Tilburg","NLD","Noord-Brabant","193238"],["11","Groningen","NLD","Groningen","172701"],["12","Breda","NLD","Noord-Brabant","160398"],["13","Apeldoorn","NLD","Gelderland","153491"],["14","Nijmegen","NLD","Gelderland","152463"],["15","Enschede","NLD","Overijssel","149544"]]</section>
This is my jquery
$.ajax({
url: 'getdata.php',
data: "",
dataType: 'html',
success: function(data)
{
//console.log(data);
var thedata = $(data).filter($("#stuff"));
console.log(thedata);
}
});
This does not work.How can i select only the data inside the section tag?.
To get the inner of an element use .html()
$(data).filter('#stuff').html();
To get back the json
$.ajax({
url: 'getdata.php',
data: "",
dataType: 'html',
success: function(data)
{
var thedata = $(data).filter('#stuff').html();
var jobject = JSON.parse(thedata);
for(var i = 0; i < jobject.length; i++) {
var item = jobject[i];
console.log(item[0] + ':' + item[1] + ':' + item[2] + ':' + item[3] + ':' + item[4] );
}}
});
I have a question about loading multiple fields from the database and use them in javascript.
This is my table "deaths" with fields:
- district
- year_1999
- year_2000
- year_2001
- year_2002
- year_2003
- year_2004
- year_2005
- year_2006
- year_2007
- year_2008
- year_2009
Now I want to load the fields year_.... when district = 'districtname'
This is what I have: (PHP)
$host = "localhost";
$user = "root";
$pass = "root";
$databaseName = "testdatabase";
$tableName = "deaths";
//--------------------------------------------------------------------------
// 1) Connect to mysql database
//--------------------------------------------------------------------------
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
//--------------------------------------------------------------------------
// 2) Query database for data
//--------------------------------------------------------------------------
$result = mysql_query("SELECT year_1999,year_2000,year_2001,year_2002,year_2003,year_2004,year_2005,year_2006,year_2007,year_2008,year_2009 FROM $tableName WHERE district = 'Binnenstad'"); //query
$data = array();
while ( $row = mysql_fetch_row($result) )
{
$data[] = $row;
}
echo json_encode( $data );
Javascript:
$(function ()
{
//-----------------------------------------------------------------------
// 2) Send a http request with AJAX http://api.jquery.com/jQuery.ajax/
//-----------------------------------------------------------------------
$.ajax({
url: './api4.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(rows) //on recieve of reply
{
//--------------------------------------------------------------------
// 3) Update html content
//--------------------------------------------------------------------
for (var i in rows)
{
var row = rows[i];
var data = row[0];
$('#districts ul').append("<li>" + data + "</li>")
.append();
}
}
});
});
But this only shows the first column data (year_1999).
How can I fix this?
Instead for (var i in rows) ... try :
UPDATE. Looking your php closer try something like this to draw each year:
$.each(rows, function(i, data) {
$.each(data, function(j, year) {
$('#districts ul').append("<li>" + year + "</li>")
});
});
my this php code is working for the $.ajax call which is below this code
$family = mysql_real_escape_string($_REQUEST['send_txt'], $link);
$query = "SELECT imgurl FROM images WHERE family='$family'";
//Query database
$result = mysql_query($query, $link);
//Output result, send back to ajax as var 'response'
$imgurl=array();
//$i=0;
if(mysql_num_rows($result) > 0){
//Fetch rows
while($row = mysql_fetch_array($result)){
$imgurl[]=$row['imgurl'];
}
}
echo $imgurl;
jquery code
$(document).ready(function() {
$('ul.sub_menu a').click(function() {
var txt = $(this).text();
$.ajax({
type: "POST",
url: "thegamer.php",
data:{send_txt: txt},
success: function(data){
$('#main-content').html(data);
}
});
});
});
it outputs just Array written at the #main-content div how to work with that array which are basically image paths
Why you create array from mysql result ? your code can be simpler like this:
<?php
$family = mysql_real_escape_string($_REQUEST['send_txt'], $link);
$query = "SELECT imgurl FROM images WHERE family='$family'";
//Query database
$result = mysql_query($query, $link);
//Output result, send back to ajax as var 'response'
if(mysql_num_rows($result) > 0)
{
//Fetch rows
while($row = mysql_fetch_array($result))
{
echo $row['imgurl'];
}
}
?>
Try you page from the browser directly. Using JSON can help here:
echo json_encode($imgurl);
and using getJSON instead of plain ajax:
$.getJSON('thegamer.php', {send_text:text}, function(data) { … });