2016-10-06 107 views
1

我需要一些php代碼來從Xampp中的mysql數據庫中提取。然後我需要將no1和no2的值傳遞給javascript進行計算。 mysql數據已附加。這個程序只選擇最後一行,但是,我希望它通過所有行並顯示變量no1和no2的新值。PHP選擇多行MYSQL數據庫

我有下面這段代碼:

<[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> 

回答

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> 

現在你有你的價值在javasc ript-array values你可以遍歷它,並獲得你的值行

+0

我對mysql相當新。我需要使用哪一個,我在哪裏放置它?另外,它會取代什麼? – Todd

+0

我添加了一個示例 – JohnnyAW

+0

btw。你的代碼的最後一部分不在循環中,所以變量'$ no1'' $ no2'將被設置爲最後一次循環迭代的值。這可能是原因,爲什麼你只能得到最後一行的值。我實際上不確定你想用'