简体   繁体   English

从GET变量从PHP中的数组打印?

[英]Printing from an array in PHP from a GET variable?

This code gets an array of 2 items from a Database. 这段代码从数据库中获得了包含2个项目的数组。 I want to set the $_GET variable values based on that array. 我想基于该数组设置$_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';
}   
?>

The above is what I tried: the url localhost/hello.php?id=1 should retrieve the variable id and set it in the $_GET variable. 以上是我尝试的方法:url localhost/hello.php?id=1应该检索变量id并将其设置在$_GET变量中。 However, the last echo statement does not work as expected. 但是,最后一个echo语句不能按预期方式工作。

Try this as a working example: 尝试将此作为工作示例:

Link to: page.php?color=2 链接到:page.php?color = 2

page.php 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';
}

Should output "Selected colour is Blue"; 应输出“所选颜色为蓝色”;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM