【发布时间】: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变量传递给函数(或者使用全局变量,但不要这样做)。