我對此很陌生,我知道我可能以錯誤的方式來做這件事,但我一整天都在試圖弄清楚它。我意識到編寫我自己的一個真正的項目有很大的區別,而不僅僅是在線練習小的語法代碼。所以,我缺乏如何合併/傳遞不同變量/範圍在一起的經驗。瞭解如何在大圖中融入一切,對我來說是完全不同的故事。提前致謝。將函數結果傳遞到sqli中
我想要做的是讓功能「selectyacht」輸出數據在與被調用位置不同的位置(在viewship.php中)。輸出數據(在viewship.php中)只需要返回某些字段(不是所有內容),這些結果將分散在整個html頁面(而不是表格)。除此之外,我有這個變量:「$ sqlstatement」(在sqlconn.php中),我試圖帶外函數,因爲我不想每次重複連接函數。我嘗試了一個全局變量,就像我不應該這樣做,並且幸好它給了我一個錯誤,這意味着我必須找到一個更好的方法。
基本上我的鬥爭,是在理解,我應該如何基於兩個因素構建這整個事情:
- 要允許sqlconn.php第二條件語句中鍵入 爲最經常地爲不同的「 selectyacht「功能 將在未來。
- 允許sqlconn.php中的連接實例駐留在該函數之外,因爲它將被多次用於不同的功能。
- 將數據返回到與viewship.php中被調用位置不同的地方,因爲該調用將是按鈕按下,而不是要顯示的結果。
這可能很簡單,但它卻沒有我。 P.S.其中一些代碼是來自互聯網上其他資源的複製/粘貼,我試圖將其與我自己的需求合併。
sqlconn.php
<?php
$servername = "XXXXXXXX";
$username = "XXXXXXXX";
$password = "XXXXXXXX";
$dbname = "XXXXXXXX";
// Instantiate the connection object
$dbconn = new mysqli($servername, $username, $password, $dbname);
// Check if the connection works or show an error
if ($dbconn->connect_error) {
die("Connection failed: " . $dbconn->connect_error);
}
// Create a query based on the ship's name
function selectyacht($shipname) {
global $sqlstatement;
$sqlstatement = "SELECT * FROM ships WHERE Name=" . "'" . $shipname . "'";
}
// Put the sql statement inside the connection.
// Additional sql statements will be added in the future somehow from other functions
$query = $dbconn->query($sqlstatement);
// Return the data from the ship to be repeated as less as possible for each future function
if ($query->field_count > 0) {
while($data = $query->fetch_assoc()) {
return $data;
}
}
else {
echo "No data found";
}
// Close the connection
$dbconn->close();
?>
viewship.php
<html>
<body>
<?php include 'sqlconn.php';?>
<!-- ship being selected from different buttons -->
<?php selectyacht("Pelorus");?>
<br>
<!-- This is the output result -->
<?php echo $data["Designer"];?>
<?php echo $data["Length"];?>
<?php echo $data["Beam"];?>
<?php echo $data["Height"];?>
</body>
</html>
謝謝你把我在正確的方向上的其它頁面! – Alex