This is the code below,
First I get the data from database:
<?php
//getDBConnect function
require 'dbfunction.php';
//Get ID from form
$id = $_GET['staffid'];
//connect to database
$con = getDBConnect();
if(!mysqli_connect_errno($con)){
$sqlQueryStr =
"SELECT a.ai_Name, r.duration " .
"FROM report AS r, academicinstitution AS a " .
"WHERE r.staff_Id = '$id' " .
"AND r.ai_Id = a.ai_Id ";
$result = mysqli_query($con,$sqlQueryStr);
mysqli_close($con);
} else {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Get data into array
$emparray = array();
while ($row = mysqli_fetch_assoc($result)) {
$emparray[] = $row;
}
//Group array by ai_Name
$grouparray = array();
foreach($emparray as $item)
{
if(!isset($grouparray[$item["ai_Name"]]))
$grouparray[$item["ai_Name"]] = 0;
$grouparray[$item["ai_Name"]] += $item["duration"];
}
?>
Then I proceed to making the data for the chart:
<script>
var dataBar=
<?php
foreach($grouparray as $keys => $value){
echo $value.',';
}
?>;
window.onload=function(){
zingchart.render({
id:'chartBar',
height:400,
width:600,
data:{
"graphset":[
{
"type":"bar",
"title":{"text":"BarChart"},
"series":[
{
"values":[dataBar]
}
]
}
]
}
});
};
</script>
<div id="chartBar"></div>
I have tried many ways to input the data, however the graph still does not load. What is causing this and how do I fix it?
The issue is how you're creating your dataBar array. Iterating over the values is fine but this is what you're actually outputting:
var dataBar=1,2,3,4,5,;
which is not a well-formed array. Try this instead:
var dataBar=[
<?php
foreach($grouparray as $keys => $value){
echo $value.',';
}
?>];
Then reference it in your JSON like so:
"series":[
{
"values":dataBar
}
]
I'm on the ZingChart team. Holler if you have more ZC questions.
Related
At the moment i get the following JSON:
["1Sales & Consulting","2Pyments","3Investing","4Financing","5Cross Functional"]
but i would like to have a proper JSON like:
[{"id":1, "name": "Sales & Consulting"}{"id": 2, "name": "Pyments"}{"id": 3, "Investing"}{"id": 4, "name": "Financing"}{"id": 5, "name": "Cross"}]
The code i used to generate the first output is:
<?php
define('servername','localhost');
define('username','root');
define('password','');
define('dbname','integration');
// Create connection
$conn = new mysqli(servername, username, password, dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name FROM capability_level1";
$result = $conn->query($sql);
$test = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$test[] = $row["id"] . $row["name"];
}
echo json_encode($test);
} else {
echo json_encode("0 results");
}
$conn->close();
?>
what do i have to change? this echo is needed to pass to ajax in a second step
Change the lines
while($row = $result->fetch_assoc()) {
$test[] = $row["id"] . $row["name"];
}
to
while($row = $result->fetch_assoc()) {
$test[] = array(
'id' => $row["id"],
'name' => $row["name"]
);
}
Hope this helps.
Try this instead:
while($row = $result->fetch_object()) {
array_push($test, $row);
}
echo json_encode($test);
Use the following code changes:-
<?php
$result = $conn->query($sql);
$test = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
array_push($test, $row);
}
echo json_encode($test);
} else {
echo json_encode("0 results");
}
$conn->close();
?>
I have the following php code (in a file returndata.php) to retrieve messages for a user:
$sql = 'SELECT * FROM usertimes WHERE receiver ="'. $messagesforaccount. '"';
$result = $conn->query($sql);
$response = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$response['message'] = $row["message"];
$response['date'] = $row["date"];
$response['sender'] = $row["sender"];
$response['receiver'] = $row["receiver"];
}
echo json_encode($response);
} else {
echo " 0 results";
}
Then the javascript is as follows (displays the message and some information on it such as the sender, date etc. on the webpage):
$.post(
"returndata.php",
{ messagesforaccount: userAccount },
function(response) {
var sender = response.sender;
var receiver = response.receiver;
var message = response.message;
var date = response.date;
console.log('Retreived data: ', sender, receiver, message, date);
p = document.createElement('p')
p.innerHTML = message + '<br>' + 'sent by ' + sender + ' at ' + date
listmessages.appendChild(p)
}, 'json'
);
This only adds one message to the page (the last one in the database). What should the php be so it loops through all results, and for each result it adds the message to the webpage?
You did a little bit mistake there. If you want associative array for multiple data then you should have a two dimensional array and you must have an index for second dimensional array as well
<?php
$sql = 'SELECT * FROM usertimes WHERE receiver ="'. $messagesforaccount. '"';
$result = $conn->query($sql);
$response = array();
$index = 0;
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$response[$index]['message'] = $row["message"];
$response[$index]['date'] = $row["date"];
$response[$index]['sender'] = $row["sender"];
$response[$index]['receiver'] = $row["receiver"];
$index++;//incrementing index variable
}
echo json_encode($response);
} else {
echo " 0 results";
}
?>
In return you can iterate that array in this way
for ($i=0;$i<count($response);$i++)
{
echo $response[$i]['message'] . "<br>" ;
echo $response[$i]['date'] . "<br>" ;
echo $response[$i]['sender'] . "<br>" ;
echo $response[$i]['receiver'] . "<br>" ;
}
You need to respond with all of them in an array like this:
$sql = 'SELECT `message`, `date`, `sender`, `receiver` FROM `usertimes` WHERE `receiver` ="'. $messagesforaccount. '"';
You should only request the fields you need. This improves performances and reduces overhead. Later, you can just push the whole row to the response.
$result = $conn->query($sql);
$response = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$response[] = $row;
}
echo json_encode($response);
} else {
echo " 0 results";
}
I have store labels and numeric values of same form in two arrays, pass these arrays using AJAX to php. now I want to store each array in two different fields of the same table mysql.
var arr = [];
var arr1 = [];
$('.cat').each(function() {
arr.push($(this).text());
});
$('.cat_value').each(function() {
arr1.push($(this).val());
});
$.ajax({
url:'rs_insert.php',
data:{categories: arr, cat_values:arr1},
type:'POST',
success:function() {
alert("data has been sent");
document.getElementById('exampleModal1').style.display = "none";
}
});
php file
$con=mysqli_connect("localhost","root","","test");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$values = array();
foreach($_POST['categories'] as $key => $name) {
$values[] = $name;
}
$sql1 = "INSERT INTO rs (Category) VALUES ";
foreach($values as $cat) {
$sql1 .= "('" . $cat . "'),";
}
$sql1_trimmed = rtrim($sql1,',');
////
$values1 = array();
foreach($_POST['cat_values'] as $key => $value) {
$values1[] = $value;
}
$sql2 = "INSERT INTO rs (Value) VALUES ";
foreach($values1 as $val) {
$sql2 .= "('" . $val . "'),";
}
$sql2_trimmed = rtrim($sql2,',');
if (!mysqli_query($con,$sql1_trimmed)) {
die('Error: ' . mysqli_error($con));
}
if (!mysqli_query($con,$sql2_trimmed)) {
die('Error: ' . mysqli_error($con));
}
the problem is, it does not inserted values parrallel. first it insert values in category field with 0 under value field. the filled value field with blank categories name.
you can try this:
$con=mysqli_connect("localhost","root","","test");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$values = array();
foreach($_POST['categories'] as $key => $name) {
$values[] = $name;
}
////
$values1 = array();
foreach($_POST['cat_values'] as $key => $value) {
$values1[] = $value;
}
$sql1 = "INSERT INTO rs (Category,Value) VALUES ";
for($i=0;$i<count($values);$i++) {
$sql1 .= "('" . $values[$i] . "','". $values1[$i] ."'),";
}
$sql1_trimmed = rtrim($sql1,',');
if (!mysqli_query($con,$sql1_trimmed)) {
die('Error: ' . mysqli_error($con));
}
How Can I Split This json Object to 3 Part id awnser and type ?
[{"id":"26","answer":[{"option":"3","text":"HIGH"}],"type":"a"},
{"id":"30","answer":[{"option":"3","text":"LOW"}],"type":"b"},
{"id":"31","answer":[{"option":"3","text":"LOW"}],"type":"c"}]
And db Name: array Table Name: user_survey_start JSON Column Name: survey_answers, This is my code:
<?php
$con=mysqli_connect("localhost","root","","arrayy");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT `survey_answers` FROM `user_survey_start`";
if ($result=mysqli_query($con,$sql)){
while ($row = mysqli_fetch_row($result)){
}
mysqli_close($con);
?>
Try using json_decode()
<?php
$sql="SELECT `survey_answers` FROM `user_survey_start`";
if ($result=mysqli_query($con,$sql))
{
while ($row = mysqli_fetch_row($result))
{
$json = $row[0];
$jason_array = json_decode($json,true);
foreach ($jason_array as $data){
$id[] = $data['id'];
$answer[] = $data['answer'];
$type[] = $data['type'];
// here code to insert/update values to db column
}
echo implode(',',$id);
echo implode(',',$answer);
echo implode(',',$type);
}
}
I have a table
Now.i have a function in my JS
function add()
{
<?php
include('conn.php');
$rs = mysql_query("select * from position");
$row = mysql_fetch_array($rs);
$ss=$row['Name'];
$sss=$row['nowb'];
$ssss=$row['totalb'];
$sssss=$row['nowc'];
$ssssss=$row['totalc'];
echo "add2()";
?>}
function add2(){
AddAddress("<?php echo $ss;?>","<?php echo $sss;?>/<?php echo $ssss;?><br /><?php echo $sssss;?>/<?php echo $ssssss;?>");
}
How to get the every date from my table?
Something like this?
function add() {
<?php
include('conn.php');
$rs = mysql_query("select * from position");
while ( $row = mysql_fetch_array($rs) ) {
$ss=$row['Name'];
$sss=$row['nowb'];
$ssss=$row['totalb'];
$sssss=$row['nowc'];
$ssssss=$row['totalc'];
echo 'AddAddress("' . $ss . '","' . $sss . '/' . $ssss . '<br />' . $sssss . '/' . $ssssss . '");';
}
?>
}
Didn't text the echo 'AddAddress....' line so I hop eI got all the single and double quotes in the right place??
Performing POST requests using Ajax here is an example of sending data from js to php.
also stop naming your vars s,ss,sss,ssss you will have no idea what they mean when you read your code tomorrow..
and try not to use mysql_* functions they have been deprecated switch to mysqli or pdo
I got what would you like to do. In your PHP file:
function add(){
<?php
include('conn.php');
$rs = mysql_query("select * from position");
echo "var data = [] ; "
while($row = mysql_fetch_assoc($rs)){
echo "
data.push({
name: '{$row['Name']}',
nowb: '{$row['nowb']}',
totalb: '{$row['totalb']}',
nowc: '{$row['nowc']}',
totalc: '{$row['totalc']}'
}); \n\r " ;
}
?>
add2(data);
}
function add2(data){
for (var i in data){
var row = data[i] ;
AddAddress(row.name, row.nowb, row.totalb, row.nowc, row.totalc);
}
}
If I understand the question correctly you want to know how to loop through an array in php.
$row = mysql_fetch_array($rs);
foreach($row as $value){
//Do something
}
Read up on it in the docs
http://php.net/manual/en/control-structures.foreach.php