dqrnsg6439 2018-09-19 02:14 采纳率: 100%
浏览 60

当php函数从mysql数据值中选择时,“未定义的变量”

A newbie question. There must be an easy answer to this but I have spent hours searching, including here in StackOverflow (also in Duplicate Questions), to no avail. Please help.

I have a Table inside a Database which I am trying to iterate.

Simplified Table is as follows:
id(int,auto-increment), product_name(varchar), price1(int)

1, widget1, 1000
2, widget2, 900
etc.

when I use this code, it works

    <?php
    $connection = mysqli_connect("localhost", "root", "", "test");

    $item = 'widget1';
    $sql = "SELECT * FROM gym_eqpt WHERE product_name = '$item' ";
    $results = mysqli_query($connection, $sql);
    while($result = mysqli_fetch_array($results)) {
    echo "<p>item name: " . ($result['product_name']) . "<br />" . "<p>item price: " . number_format($result['price1']) . " </p>";
}
?>

However, when I try to use the same code inside a function, there is an "Undefined variable" error.

<?php
function iteratePrice($item) {
    $sql = "SELECT * FROM gym_eqpt WHERE product_name = '$item' ";
    $results = mysqli_query($connection, $sql);
    while($result = mysqli_fetch_array($results)) {
    echo "<p>item name: " . ($result['product_name']) ."<p>item price: " . number_format($result['price1']) . " </p>";
    }   
}

iteratePrice('widget1');
?>

Eventually, I would like to use this function inside different html div's on the same page, calling each product name and price in each div.

  • 写回答

1条回答 默认 最新

  • douwo6738 2018-09-19 02:22
    关注

    All external variables are unknown inside a function so, it will be better if you pass external values as parameters:

    function iteratePrice($connection, $item) {
        $sql = "SELECT * FROM gym_eqpt WHERE product_name = '$item' ";
        $results = mysqli_query($connection, $sql);
        while($result = mysqli_fetch_array($results)) {
        echo "<p>item name: " . ($result['product_name']) ."<p>item price: " . number_format($result['price1']) . " </p>";
        }   
    }
    

    And then call it as:

    iteratePrice($connection, 'widget1');
    

    This is the documentation about php functions and scope: http://php.net/manual/en/language.variables.scope.php

    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法