PHP wants to retrieve from database array, but only one character can be retrieved

Asked 1 years ago, Updated 1 years ago, 341 views

Prerequisite
Excuse me.
I am a beginner in PHP.
We are currently creating a product listing page to create an EC site.

What do you want to do
I want to get the data stored in the database in an array.

problems/error messages you are experiencing
When you try to retrieve an array, you can only retrieve a single character string.

example

 var_dump($pro_name[[0])

// Result
Only "i" with the name "item1" is printed

Affected Source Code

<?php
    $dsn='mysql:dbname=shop;host=localhost;charset=utf8';
    $user='root';
    $password=';
    $dbh = new PDO($dsn, $user, $password);
    $dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);

    $sql = 'SELECT name, price, image FROM mst_product';
    $stmt = $dbh->prepare($sql);
    $stmt->execute();

    $rec=$stmt->fetch(PDO::FETCH_BOTH);
    $pro_name = $rec ['name'];
    $pro_price = $rec ['price'];
    $pro_image_name = $rec ['image'];

  
    
    $dbh = null;


?>
<!DOCTYPE html>
<html lang="ja">
<head>
    <metacharset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="/css/style.css">
    <title> </title>
</head>
<body>

<div class="inner-wrap">
<h2class="itemarea-list">Product List</h2>
<div class="item-area">


<div class="item-area-item">
<?php for ($i=0;$i<10;$i++)
    {
?>
    <?phpecho$pro_image_name[$i].'<br>';?>
 <?phpecho$pro_name[$i].'<br>';?> 
    <?phpecho$pro_price[$i].'<br>';?>
<?php
    }
?>
    </div>

</div>
</div>
<br>
<a href="shop_cartlook.php">View Cart</a>
</body>
</html>

Tried
I tried $rec=$stmt->fetch(PDO::FETCH_BOTH); to (PDO::FETCH_ASSOC) or fetchall, but it didn't change.
I apologize for the inconvenience, but I would appreciate it if someone could let me know.

php

2022-10-22 09:13

1 Answers

If the variables are not arrays,
without offset access access Normally var_dump($pro_name) will print a string.

You can extract characters one character at a time by offsetting variables such as $pro_name[0] that contain strings, such as arrays.
https://www.php.net/manual/ja/language.types.string.php#language.types.string.substr


2022-10-22 09:13

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.