繁体   English   中英

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

[英]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.

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