PHP array into Javascript Array - php

Afternoon all. The code below works perfectly, however, I need to pull each row of the php sql array out and into the script var. Any ideas on how to write a while loop that could do this? Thanks for any help
var enableDays = ["<?php echo mysql_result($result, 0, 'date'); ?>"];
enableDays.push("<?php echo mysql_result($result, 1, 'date'); ?>");
Additional Code::
$rows = array();
while ($row = mysql_fetch_assoc($result))
{
$rows[] = $row;
}
var enableDays = [<?php echo json_encode($rows); ?>];
console.log(enableDays[1]);

You can get the rows using mysqli_fetch_assoc and then encode it to JSON:
<?php
$rows = array();
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
?>
var enableDays = <?php echo json_encode($rows); ?>;

Pull your data out into a PHP array, then transfer that to JavaScript with
var enableDays = <?php echo json_encode($enableDays); ?>;
As an aside, the obligatory recommendation that you should stop using the PHP mysql extension immediately because it is not very safe and has been deprecated; switch to something better (mysqli and PDO are both good choices).

This can't work. Once the page is loaded, all the PHP has run already. But if you're really just adding the next mysql_result for each push, you could have PHP create the entire enableDays array for you:
<?php
echo 'var enableDays = ["' . mysql_result(...) . '", "' . mysql_result(...) . '"];'
?>

Hope this would help
<?php
$res = mysql_fetch_assoc($result)
foreach($res as $key => $val){ ?>
enableDays.push('<?php echo $val; ?>');
<?php }
?>

Related

Returning an array from a PHP query

I query my database with a PHP script that looks like this:
$query = "SELECT * FROM JKFactory WHERE ronde = '$ronde' AND moment = '$moment' AND klas = '$klas'";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
while($row = mysql_fetch_array($result))
{
echo $row['afzetAG'];
echo ",";
}
This gives a result something like this:
10000,20000,30000,
I need this data to build a piegraph with chart.js.
chart.js works with arrays for the data. So the numbers should be returned as an array which I can put into an JavaScript variable which I can use with chart.js.
Another problem is the last comma. I have no idea how I can get rid of this comma.
Maybe these question are straightforward but I am relatively new in this field I really get stuck on this part.
You have the array and you'd put the comma after the results yourself. so try to declare an array like $arr before while and use array_push($arr,$row['afzetAG']) inside the while
To print your result like 1000,2000,3000... You can save the content into an Array and print it using implode:
$data = array();
while($row = mysql_fetch_array($result))
{
array_push($data, $row['afzetAG']);
}
echo implode(",",$data);
But if you want to use an Array from PHP to JavaScript you can do this:
<script type="text/javascript">
<?php
$data = array();
while($row = mysql_fetch_array($result))
{
array_push($data, $row['afzetAG']);
}
?>
var obj = <?php echo json_encode($data); ?>;
</script>
So now obj contains the Array ready to use in your JavaScript code.
$types = array();
while(($row = mysql_fetch_assoc($result))) { $types[] = $row['type']; }
ok i made it. To echo the result i used this:
$a = array();
while($row = mysql_fetch_array($result))
{
$b = $row['afzetAG'];
array_push($a,$b);
}
echo implode(",",$a);
This gives not an array i can use in javascript. In javascript i put the result in a variable myResult and than i used:
myResult = myResult.split(',');
this i could use in chart.js to build a pie chart.
Thanks guys. Now i can sleep.

Encoding MySQL array result in JSON array notation

$markers =array();
$getmap = $mysqli->query("SELECT `desc`,`lat`,`long` FROM map");
$i=0;
$markers = $getmap->fetch_all(MYSQLI_ASSOC);
echo $markers[1]["desc"];
echo $markers;
$markers = json_encode($markers);
How is it possible such that these will flow properly and it will be read by the JS?
var position = (markers[i][lat], markers[i][long]);
Please try this way:
Hopefully it will help:
foreach($markers as $i=>$arrMarkes)
{
$finalArray[$i] = $arrMarkes;
}
echo json_encode($finalArray);

Set PHP Variables from values returned in DB

Newbie to PHP and trying to learn it. I have returned data from my DB.
So the rows may look something like below
ID--------Name--------PhoneNo
1 Joe 1234
2 Jane 5678
3 Tom 0000
I am using the msql_fetch_array to return the data as below:
<?php
while($row = mysql_fetch_array($result))
{
$NameOne = $row['Name'];
}
?>
This is placing the name 'Joe' in the variable name NameOne as expected. What is the best way however to get Jane and Tome into variables called $NameTwo and $NameThree that I can then echo these variables further down in my html and similary I want to place the phone number retrieved into seperate variables and refer to them later in my html.
The ideal approch will be saving them inside an array, which can be achieved like this:
$Names = array();
$i = 0;
while($row = mysql_fetch_array($result)) {
$Names[$i] = $row['Name'];
$i++;
}
Now you can retrieve your data this way:
echo $Names[0]; // Will output the first name saved.
Rather than creating so many new variables, why not create an array?
<?php
$i=1;
while($row = mysql_fetch_array($result))
{
$Names[$i]= $row['Name'];
$i++;
}
?>
You can then use the array in your code
echo $Names[1]; // 1 or 2 or 3 etc
For multiple attributes you can use a multidimensional array
$i=1;
while($row = mysql_fetch_array($result))
{
$Data[$i]["Name"]= $row['Name'];
$Data[$i]["Phone"]= $row['Phone'];
$i++;
}
You can then use the array in your code
echo $Data[1]["Name"]; // 1 or 2 or 3 etc
If you want to really persist the results, store them in an array:
<?php
$data = array();
// Note that I've changed "mysql_fetch_array" to "mysql_fetch_assoc" to decrease the number of saved data.
while($row = mysql_fetch_assoc($result))
{
$data[] = $row['Name'];
}
/* Now you can use the data wherever you want, like: $data[0]['Name'] for first name, $data[1]['Name'] for second name and so on */
?>
To strictly answer KOL's question:
<?php
$i = 0;
$numbers = array('One', 'Two', 'Three', 'Four', 'Five');
while($row = mysql_fetch_array($result)) {
if($i++ > count($numbers) {
throw new NotMoreNumbersSupportedException();
}
$varname = 'Name' . $numbers[$i++];
$$varname = $row['Name'];
}
var_dump($NameOne, $NameTwo, $NameThree, $NameFour, $NameFive); //etc
?>
Now shoot me.
You can directly place html inside your while loop
<?php
while($row = mysql_fetch_array($result))
{
?>
<div><?php echo $row['Name']; ?> </div>
<div><?php echo $row['PhoneNo']; ?> </div>
<?php }
?>
You can add the details to another array
<?php
$names = array();
$phnos = array();
while($row = mysql_fetch_array($result))
{
$names[] = $row['Name']; //$names[0] , $names[1] etc..
$phnos[] = $row['PhoneNo']; //$phnos[0] , $phnos[1] etc..
}
?>

php array into javascript array document.write javascript_array

I have a problem with my javascript array. Bellow my code:
$namen = array();
$mainimg = array();
$sql1 = mysql_query("SELECT * FROM image WHERE id = ".$id.";");
echo "<div class='normal'>";
while($row = mysql_fetch_array($sql1))
{
$namen[] = $row['bild'];
$mainimg[] = $row['mainimg'];
$number_array = count($namen);
?>
<script type='text/javascript'>
<?php
for($a=1; $a <= count($namen); $a++){
$php_array = array($a => $row['bild']);
$js_array = json_encode($php_array);
echo "var javascript_array = ". $js_array . ";\n";
echo "document.write(javascript_array + '<br />');";
}
?>
</script>
}
Now I get [object][Object] in the browser, but I wanted to printout the elements, the name of the pictures. What can I do?
Thanks for your help in advance.
Regards, Yanick
You're trying to print a Object as a string. What you need to do is to access your properties directly from the object.
<script>
<?php $data = array('foo' => 'bar'); ?>
var my_js_var = <?php echo json_encode($data); ?>;
</script>
With this script, you can access your values like this:
document.write(my_js_var.foo); // writes 'bar'
You'll need to loop through the array and output the fields you want for each item. You're currently printing out the string version of an object in JavaScript, which is always [object Object].

Handling PHP array of unknown size

I have the following code that should select all the users in the relevant table in my database:
$hof = mysql_query("SELECT * FROM users");
$name = array();
$website = array();
$i=0;
while($result = mysql_fetch_array($hof)){
$name[$i] = $result['company'];
$website[$i] = $result['website'];
}
$i++;
I want to echo out the names and websites of all in the html section of my script (below the php) which will be a Hall of Frame of sorts. How would i do is? The fact that i do not know the size of the array deters me.
Usually, if i knew the size, i would so something like:
<?php echo $name[1];?>
<?php echo $name[2];?>
//and so on
Many thanks in advance. P.S. I plan to move across to MySQLi when i have the functionality of the website sorted first on localhost. Cheers
Your $i++; statement should be inside while loop
while($result = mysql_fetch_array($hof)){
$name[$i] = $result['company'];
$website[$i] = $result['website'];
$i++;
}
Better You do it like this,
$rows = array();
while($result = mysql_fetch_assoc($hof)){
$rows[] = $result;
}
and you echo them like this,
<?php
$len = count($name);
for($i=0;$i<$len;$i++){
echo $name[1];
}
?>
And for the alternative method use this,
<?php
foreach($rows as $row){
echo $row['name']; // use $row['website'] to echo website.
}
?>
foreach($name as $key=>$value){
echo $name[$key];
echo $website[$key];
}
Also there no need to take $i++, you can use following way
while($result = mysql_fetch_array($hof)){
$name[] = $result['company'];
$website[] = $result['website'];
}
See array in manual
First off the $i++ should be inside the loop.
To output them all, you could use implode(), or maybe foreach.
First, take your data into array
$data = array();
$sql = "SELECT * FROM users";
$res = mysql_query($sql) or trigger_error(mysql_error()."[$sql]");
while($row = mysql_fetch_array($res)){
$data[] = $row;
}
then use it anywhere you wish, say, in the template:
<ul>
<? foreach($data as $row): ?>
<li><?=$row['company']?></li>
<? endforeach ?>
</ul>
How about:
foreach ($name as $val)
{
echo $val;
}
you can use mysql_num_rows() to know the number of results returned by your query
$arrarySize = mysql_num_rows($hof);

Categories