How to create this array? (Php)

I got a little stuck on how to create this array.

My details:

category_id | category_name
     1              bikes
     2              cars
     3              books
     4              computers

Array:

$category=array();
$query = "SELECT * FROM categories ORDER BY name ASC";
$result = $db->query($query);
$category=array('category_id'=>$category_id, 'category_name'=>$category_name);
while ($row = $result->fetch_array()){
    $category_id=$row['category_id'];
    $category_name=$row['name'];
}

I want to create an array so that I can echo data in a radio list, like ...

<input type='radio' value='<?PHP echo $category['category_id']; ?>' 
name='category[]'><?PHP echo $category['category_name']; ?>

o bikes
o cars
o books
o computers 

The problem is that the array consists of only one pair (1, bikes) and not all data. How can I create an array with all the data?

Thank!

+3
source share
3 answers

You are doing three things wrong, at first you are not actually setting the $ category to anything — only the values ​​of the two undefined values, which are zero by default. So you get an array like:

array('category_id' => null, 'name' => null)

-, $category_id $category_name, . , , , . , .

. , PHP , ..

$query = "SELECT * FROM categories ORDER BY name ASC";
$result = $db->query($query);

$categories=array();

while ($row = $result->fetch_array()){
    $categories[] = array('category_id' => $row['category_id'], 'category_name' => $row['name']);
}

, :

foreach ( $categories as $category ) {
    ?>
    <input type='radio' value='<?php echo $category['category_id']; ?>' name='category[]'><?php echo $category['category_name']; ?>
    <?php
}

, , .

+3

, , , , , :

$category=array();
$query = "SELECT * FROM categories ORDER BY name ASC";
$result = $db->query($query);
$category=array('category_id'=>$category_id, 'category_name'=>$category_name);
while ($row = $result->fetch_array()){
    $category_id=$row['category_id'];
    $category_name=$row['name'];
?>
<input type='radio' value='<?PHP echo $category['category_id']; ?>' 
name='category[]'><?PHP echo $category['category_name']; ?>
<?php
}
+2

$category_id $category_name, $category, , .

PDO :

<?php
  $db = ...
  $sql = 'SELECT * FROM categories ORDER BY category_name ASC';
  $categories = $db->query($sql);
?>

<html>
<body>
<? foreach ($categories as $category): ?>
<input type="radio" name="category[]" value="<?= $category->category_id ?>">
  <?= $category->category_name ?>
</input>
<? endforeach ?>
</body>
</html>
+1

Source: https://habr.com/ru/post/1746912/


All Articles