【问题标题】:Why $con has no value in funciones.php为什么 $con 在 funciones.php 中没有价值
【发布时间】:2016-10-03 08:49:53
【问题描述】:

这是musica.php

               $sentencia = $con->prepare("SELECT url_img,nombre FROM discos");
                $sentencia->execute();
                while ($fila = $sentencia->fetch()) {
                   print '<div class="disco"><img src="'.$fila["url_img"].'">'
                           .$fila["nombre"]
                           . '</div>';

                }
               cargarDiscos();
             ?>

这在这里工作得很好,但是当我尝试使用 cargarDiscos() 函数时似乎失败并且它的代码相同。这是带有 cargarDiscos() 函数的 funciones.php,其代码与 musica.php 相同

<?php
     include 'conexion.php'; // El compilador coga el archivo y lo incluya   

     function cargarDiscos(){
            $sentencia = $con->prepare("SELECT url_img,nombre FROM discos");
                    $sentencia->execute();
                    while ($fila = $sentencia->fetch()) {
                       print '<div class="disco"><img src="'.$fila["url_img"].'">'
                               .$fila["nombre"]
                               . '</div>';

                    }
     }
?>

funciones.php 包含数据库 conexion。这是我的错误:

注意:未定义的变量:con in C:\xampp\htdocs\spotifake\funciones.php 在第 5 行

致命错误:未捕获的错误:调用成员函数 prepare() on C:\xampp\htdocs\spotifake\funciones.php:5 中的 null 堆栈跟踪:#0 C:\xampp\htdocs\spotifake\musica.php(42): cargarDiscos() #1 {main} 在第 5 行的 C:\xampp\htdocs\spotifake\funciones.php 中抛出

【问题讨论】:

  • 一个函数是不同的作用域,你需要将$con变量传递给函数(或者使用全局变量,但不要这样做)。

标签: php mysql apache


【解决方案1】:

您应该像这样将 $con 作为参数传递:

<?php
     include 'conexion.php'; // El compilador coga el archivo y lo incluya   

     function cargarDiscos($c){
            $sentencia = $c->prepare("SELECT url_img,nombre FROM discos");
                    $sentencia->execute();
                    while ($fila = $sentencia->fetch()) {
                       print '<div class="disco"><img src="'.$fila["url_img"].'">'
                               .$fila["nombre"]
                               . '</div>';

                    }
     }
?>

然后像这样调用函数:

cargarDiscos($con);

如果这不起作用,请仔细检查是否使用正确的路径调用了“conexion.php”,这取决于第二个脚本所在的位置。

致敬!

【讨论】:

  • 也这样做了,解决了这个问题。谢谢。
【解决方案2】:

你应该将 con 声明为全局

function cargarDiscos(){
      global $con; // <<<<<<<<<<<
            $sentencia = $con->prepare("SELECT url_img,nombre FROM discos");
                    $sentencia->execute();
                    while ($fila = $sentencia->fetch()) {
                       print '<div class="disco"><img src="'.$fila["url_img"].'">'
                               .$fila["nombre"]
                               . '</div>';

                    }
     }

【讨论】:

  • 使其全局修复它。谢谢伊利亚斯。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
  • 2018-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多