[英]Printing from an array in PHP from a GET variable?
這段代碼從數據庫中獲得了包含2個項目的數組。 我想基於該數組設置$_GET
變量值。
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// create connection
$conn = new mysqli($servername, $username, $password);
// check connection
if ($conn->connect_error){
die("connection failed: " . $conn->connect_error);
}
// connect to DB
$db_selected = mysqli_select_db($conn, 'article');
if (!$db_selected){
die("can't use article : " .mysqli_error());
}
// extract databases table to PHP array
$query = "SELECT * FROM `articles`";
$result = $conn->query($query);
$article_array = array();
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$artic = $row['name'];
$amount = $row['quantity'];
$article_array[$artic] = $amount;
}
// test array
//print_r($article_array); ---> works!
// print the array in the pos of id
if(isset($_GET['id']){
echo 'id is: '.$article_array[$_GET['id'];
} else {
echo 'soemthing is wrong';
}
?>
以上是我嘗試的方法:url localhost/hello.php?id=1
應該檢索變量id並將其設置在$_GET
變量中。 但是,最后一個echo語句不能按預期方式工作。
嘗試將此作為工作示例:
鏈接到:page.php?color = 2
page.php
$colours = array();
$colours[] = 'Red';
$colours[] = 'White';
$colours[] = 'Blue';
if(isset($_GET['color']){
echo 'Selected colour is: '.$colours[$_GET['color'];
} else {
echo 'Something is wrong';
}
應輸出“所選顏色為藍色”;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.