Hi I'm trying to make an array " events" in javascript that is filled with objects of two properties {Title: , Date:}
But, the value of those two properties is brought from the database using PHP!
Here's my code but I don't know why it doesn't work..
var events = [
<?php
//Connect to mysql server
//Select database
$result=mysql_query("SELECT * FROM event");
$count = mysql_num_rows($result);
if($count>0){
for($i=0;$i<$count-1;$i++){
$row= mysql_fetch_row($result);
echo "{ Title: ".$row['title'].", Date: ".$row['date']." },";
}
$row= mysql_fetch_row($result);
echo "{ Title: ".$row['title'].", Date: ".$row['date']." }";
}
?>];
Let's first take the building of your results:
Use array_push to create your data from your SQL (this is called an associative arrays:
var events =
<?php
$json = array();
$result=mysql_query("SELECT * FROM event");
$count = mysql_num_rows($result);
for($i=0;$i<$count;$i++) {
$row= mysql_fetch_row($result);
$item = array();
$item['Title'] = $row['title'];
$item['Date'] = $row['date'];
$json[] = $item;
}
Now echo the results as JSON using json_encode:
echo json_encode($json);
?>;
Tested in PHP 5.3.2
Related
i want to convert my array into string i mean i want to echo only array value
i use this code
$query = "SELECT `message` FROM `appstickers`";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
$jsonArray = array();
while($row = $result->fetch_assoc()) {
$jsonArray[]= $row;
}
//echo $string;
echo json_encode($jsonArray);
i get this output
[{"message":"welcome to team with us"},{"message":"this is for light dispatch"}]
but i want this output
[welcome to team with us,this is for light dispatch"]
so please give me proper solution with example
So why are you using json_encode() ?
use implode() instead:
// ... previous code
while($row = $result->fetch_assoc()) {
$jsonArray[]= $row;
}
echo '[' . implode(',', $jsonArray) . ']';
I'm going on a limb here, and assuming your required array is not what you actually want, but you do want this:
$jsonArray = array();
while($row = $result->fetch_assoc()) {
$jsonArray[]= $row['messsage'];
}
echo json_encode($jsonArray);
which will result in
["welcome to team with us", "this is for light dispatch"]
<?php
echo implode(" ",$jsonArray);
?>
Just you need to use implode() function.
$query = "SELECT `message` FROM `appstickers`";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
$jsonArray = array();
while($row = $result->fetch_assoc()) {
$jsonArray[]= $row;
}
//echo $string;
$ans = implode(",",$jsonArray);
echo $ans;
This shows all the elements from an array in a string but without a separator. I used ',' as a separator in this code. And it does not work. How can i separate them with separator.
$con = mysql_connect("localhost","root","");
if(!$con)
{
die("Database Connection failed.".mysql_error());
}
$db = mysql_select_db("test1",$con);
if(!$db)
{
die("Database selection failed.".mysql_error());
}
$query = "select * from menu limit 10";
$result = mysql_query($query,$con);
while($row = mysql_fetch_array($result))
{
$id = $row['id'];
//$menu_name = $row['m_name'];
//$menu_image = $row['m_image'];
$menu_name = array($row['m_name']);
$menu_image = array($row['m_image']);
echo implode(',',$menu_name);
//echo "<img src='images/$menu_image' style='height:200px;width:200px;'>";
}
if(!$result)
{
echo mysql_error;
}
?>
you are storing array into variable . so if you will use imploade on an variable it will not show the result so best way is to store your result into an array and then use implode .
Don't use depricated mysql_* function use mysqli_* or pdo
instead
$menu_image=array(); // start array to store
$menu_name=array();
while($row = mysql_fetch_array($result))
{
$id = $row['id'];
$menu_name[] = $row['m_name']; // store menu name
$menu_image[] = $row['m_image']; // store menu image
}
echo implode(',',$menu_name); // finaly use implode
You can try this:
$menu_name[];
$menu_image[];
while($row = mysql_fetch_array($result)) {
$id = $row['id'];
$menu_name[] = $row['m_name']; // I change your $menu_name into an array so that when you fetch $row['m_name'] it returns an array
$menu_image[] = $row['m_image']; //same thing
}
echo implode(',',$menu_name);
//echo "<img src='images/$menu_image' style='height:200px;width:200px;'>";
try this in place of your while loop
$menu_name = array();
$menu_image = array();
while($row = mysql_fetch_array($result))
{
$id = $row['id'];
$menu_name[] = $row['m_name'];
$menu_image[] = $row['m_image'];
}
echo implode(',',$menu_name);
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.
$query = "SELECT * FROM main";
if ($result = $db->query($query)) {
while ($row = $result->fetch_assoc()) {
$name= $row["name"];
$image = $row["image"];
}
}
then somewhere in my code I print it out using like echo $name; but I got only one result, which is the last row. I know I have to do foreach but what variable should I put?
foreach($result as $results) ? like this?
On every iteration, you reassign the values to $name and $image, causing it to show only the last value when it leaves the loop.
You can either echo them right away in the loop, or populate an array or an object with them, so they will be available later.
Example:
$data = array();
while ($row = $result->fetch_assoc()) {
$data[] = array('name'=>$row["name"], 'image'=>$row["image"]); // push into the array
}
var_dump($data); // it's all here now
And to echo the data later, one of the ways is foreach:
foreach($data as $row) {
echo "Name: ", $row['name'], "; Image: ", $row['image];
}
$query = "SELECT * FROM main";
$result = $db->query($query);
$row = $result->fetch_assoc();
foreach ($row as $rows) {
echo $rows['name'] ." ". $rows['image'];
}
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
Referring to the title. I have an array which I coded like this:-
$query = "SELECT * FROM server";
$result = mysql_query($query);
$dServer = array();
while($row = mysql_fetch_assoc($result)) {
$dServer[] = $row['model'];
}
Now, how do I pass the $dServer array into a Javascript array?
For example, this array:
var a = new Array();
$query = "SELECT * FROM server";
$result = mysql_query($query);
$dServer = array();
while($row = mysql_fetch_assoc($result)){
$dServer[] = $row['model'];
}
?>
<script type="text/javascript">
var a = <?php echo json_encode($dServer); ?>;
</script>
Encode it as a json object.
<?
$arr = array('entry' => 'content');
?>
<script>
var data = <?=json_encode($arr);?>;
alert(data['entry']);
</script>
Try to get use of ajax request and json_encode.
Second variant
<?php
$query = "SELECT * FROM server";
$result = mysql_query($query);
$dServer = array();
while($row = mysql_fetch_assoc($result))
{
$dServer[] = $row['model'];
}
?>
var a = <?php echo json_encode($dServer);?>;
In addition to the ajax / json methods mentioned, you can directly print out the values:
<?php
$query = "SELECT * FROM server";
$result = mysql_query($query);
?>
<script type="text/javascript">
var a = new Array();
<?php
while($row = mysql_fetch_assoc($result)){
echo "a['model'] = " . $row['model'] . ";";
echo "a['nextField'] = " . $row['nextField'] . ";";
}
?>
</script>