这是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 include。这是我的错误:
注意:未定义的变量:con in 第5行的C:\ xampp \ htdocs \ spotifake \ funciones.php
致命错误:未捕获错误:调用成员函数prepare() C:\ xampp \ htdocs \ spotifake \ funciones.php中的null:5堆栈跟踪:#0 C:\ xampp \ htdocs \ spotifake \ musica.php(42):cargarDiscos()#1 {main} 在第5行的C:\ xampp \ htdocs \ spotifake \ funciones.php中抛出
答案 0 :(得分:0)
你应该传递$ 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',它取决于第二个脚本所在的位置。
Saludos!
答案 1 :(得分:0)
你应该将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>';
}
}