简体   繁体   中英

Printing from an array in PHP from a GET variable?

This code gets an array of 2 items from a Database. I want to set the $_GET variable values based on that array.

<?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. However, the last echo statement does not work as expected.

Try this as a working example:

Link to: 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';
}

Should output "Selected colour is Blue";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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