PHP选择多行MYSQL数据库

时间:2016-10-06 00:05:40

标签: mysql

我需要一些PHP代码来从Xampp的mysql数据库中提取。然后我需要将no1和no2的值传递给javascript进行计算。附加了mysql数据。这个程序只选择最后一行,但是,我想让它遍历所有行并显示变量no1和no2的新值。

我的代码如下:

<[enter image description here][1]?php

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";



$conn = new mysqli($servername, $username, $password, $dbname);


if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT s_num, movie, no1, no2 FROM table_1";
$result = $conn->query($sql);

if ($result->num_rows > 0) {

while($row = $result->fetch_assoc()) {
echo "Name: " . $row["s_num"]. " Movie: " . $row["movie"]. $row["no1"].                

$row["no2"]. "<br>";

$no1 = $row['no1'];

$no2 = $row['no2'];

echo "Number 1 is $no1"; 
echo "Number 2 is $no2"; 

echo $no1 + $no2;
}
} else {
echo "0 results";
}

$conn->close();
?>

<script type="text/javascript">

var no_1 = <?php echo $no1 ?>; 
var no_2 = "<?php echo $no2 ?>"; 

alert (no_1);

alert ("The value is:"+no_1);

alert (no_2);

</script>

1 个答案:

答案 0 :(得分:0)

您可以尝试使用fetch_all()函数将结果集提取到数组中并在以下情况下迭代它:

//Copy result into a associative array
$resultArray = $result->fetch_all(MYSQLI_ASSOC);

//Copy result into a numeric array
$resultArray = $result->fetch_all(MYSQLI_NUM);

//Copy result into both a associative and numeric array
$resultArray = $result->fetch_all(MYSQLI_BOTH);

所以使用关联选项,您的代码将如下所示:

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT s_num, movie, no1, no2 FROM table_1";
$result = $conn->query($sql);
?>
<script type="text/javascript">
    var values = [];
<?php
if ($result->num_rows > 0) {
    $resultArray = $result->fetch_all(MYSQLI_ASSOC);

    foreach ($resultArray as $row){
        echo "values.push({no1: ".$row['no1'].", no2: ".$row['no2']."});";
    }
}

$conn->close();
?>
</script>

现在你在javascript-array values中拥有你的值,你可以迭代它并获得行的值行