我使用以下PHP代码来回显数据库中的值: 以下内容来自数据库:
BOLERO DI NON AC WHITE BS3
587247
BOLERO DI NON AC SILVER BS3
599524
是否可以像
那样分别存储每一个var 1=BOLERO DI NON AC WHITE BS3
var 2=587247
var 3=BOLERO DI NON AC SILVER BS3
var 4=599524
PHP代码:
<?php
$query2="SELECT ABS(price - $new_loan_amount) AS nearest, model, price FROM car_pricing WHERE state = '".$state."' ORDER BY nearest ASC LIMIT 2;
";
$result2 = mysqli_query($db,$query2);
while ($row = mysqli_fetch_assoc($result2)){
$i=1;
echo $database_model = $row['model'];
echo "<br>";
echo $database_price = $row['price'];
echo "<br>";
$i++;
}
if (!$result2) {
echo("Error, the query could not be executed: " .
mysqli_error($db) . "</p>");
mysqli_close($db);
}
$query1 = "SELECT state FROM states";
$result1 = mysqli_query($db,$query1);
?>
答案 0 :(得分:0)
您需要在循环外初始化$i
,否则每次都会重置。而且你必须在每个echo
之间递增它。
$i = 1;
while ($row = mysqli_fetch_assoc($result2)) {
echo "var $i = {$row['model']}<br>";
$i++;
echo "var $i = {$row['price']}<br>";
$i++;
}
答案 1 :(得分:0)
我会
echo 'var data = '.json_encode($result2);
而不是
while ($row = mysqli_fetch_assoc($result2)){
$i=1;
echo $database_model = $row['model'];
echo "<br>";
echo $database_price = $row['price'];
echo "<br>";
$i++;
}
然后javascript变量data
将包含结果数组
答案 2 :(得分:0)
您可以动态创建变量:
$i=1;
while ($row = mysqli_fetch_assoc($result2)){
${'var' . $i++} = $row['model'];
${'var' . $i++} = $row['price'];
}
然后在你的脚本中你应该有:
echo $var1; // model #1
echo $var2; // price #1
echo $var3; // model #2
echo $var4; // price #2
我希望我会这样做:
$i=1;
while ($row = mysqli_fetch_assoc($result2)){
${'model' . $i} = $row['model'];
${'price' . $i++} = $row['price'];
}
这给了我:
echo $model1; // model #1
echo $price1; // price #1
echo $model2; // model #2
echo $price2; // price #2