简体   繁体   English

将mysql数据输出到jquery的变量中

[英]output mysql data into variables for jquery

I have a 2 field database (daynumber & datavalue), the data of which I am retrieving with php then creating and passing variables into jquery for use with a graph. 我有一个2字段数据库(daynumber和datavalue),我正在用php检索其数据,然后创建变量并将其传递到jquery中以与图一起使用。

I am not doing this as an array because I need to apply a formula to the datavalue field. 我不是这样做的数组,因为我需要将一个公式应用于datavalue字段。 The formula can be altered by the user. 公式可以由用户更改。

In jquery, I need to be able to do this: 在jQuery中,我需要能够做到这一点:

cday_1 = <?php echo $day_1?>;
cday_2 = <?php echo $day_2?>;
tday_1 = (<?php echo $day_1 ?> * formula1 / formula2;
tday_2 = (<?php echo $day_2 ?> * formula1 / formula2;

The cday series and the tday series will be plotted separately on the graph. cday系列和tday系列将在图表上单独绘制。

My problem is that I could manually name each var in php, ie: 我的问题是我可以在php中手动命名每个var,即:

$day_1=mysql_result($result,$i,"datavalue");

but I have 30 rows and I'd prefer to do it with a loop. 但我有30行,我宁愿用循环来做。 So far, I've got this far: 到目前为止,我已经走到了这一步:

$i=0;
while ($i < $num) {
$datavalue=mysql_result($result,$i,"datavalue");
echo "\$day_";
echo $i;
echo " = ";
echo $datavalue;
echo "<br>";
$i++;
}

So there are a couple of problems I'm having with this. 所以我遇到了一些问题。

The first problem is that while everything is echoing, I'm not sure how to actually create variables like this(!). 第一个问题是,虽然一切都在呼应,但我不确定如何实际创建这样的变量(!)。

The second problem is that there are only 30 rows in the db, but 34 are actually outputting and I can't work out why. 第二个问题是数据库中只有30行,但实际上有34行正在输出,我无法解决原因。

I'm self-taught, so apologies for clumsy coding and/or stupid questions. 我是自学成才的,因此对笨拙的编码和/或愚蠢的问题表示歉意。

You could just store them in a PHP-side array: 您可以将它们存储在PHP端数组中:

$days = array(
    'cday' => 'the cday value',
    'dday' => 'the dday value',
    etc...
);

and then via json_encode() translate them to a Javascript array/object automatically. 然后通过json_encode()将它们自动转换为Javascript数组/对象。 This object could be sent to your page as an AJAX response, or even embedded into the page directly: 该对象可以作为AJAX响应发送到您的页面,甚至可以直接嵌入到页面中:

<script type="text/javascript">
    var days = <?php echo json_encode($days) ?>;
</script>

after which you just access the values as you would any other array in JS. 之后,您只需访问JS中的任何其他数组。

Have ended up doing this: 结束了这样做:

$i=0;
while ($i < $num) {
${"day_$i"}=mysql_result($result,$i,"datavalue");
$i++;
}

I have a feeling this was a basic issue and I just didn't explain myself properly. 我觉得这是一个基本问题,只是我没有正确地解释自己。 I am unable to use an array as I needed to fiddle with formulas so this solution worked fine. 我无法使用数组,因为我需要弄弄公式,因此此解决方案效果很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM