php - 无法从 html 代码访问 php-mysql 连接
问题描述
我在 html 代码中调用 php 函数。但是mysql和php之间的连接失败了。
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
</head>
<body>
<h1><a href="index.php">go to main page</a></h1>
<?php actorList()?>
</body>
</html>
<?php
$conn = mysqli_connect("localhost", "root", "*","final");
if(!$conn) die("Connection failed!");
function actorList(){
global $conn;
$result = mysqli_query($conn, "SELECT * FROM actor_list");
}
?>
为什么我不能$conn
在actorList中使用?
解决方案
为什么不传递给参数呢?
<?php
$conn = mysqli_connect("localhost", "root", "qotktk12","final");
if(!$conn) die("Connection failed!");
?>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
</head>
<body>
<h1><a href="index.php">go to main page</a></h1>
<?php actorList($conn)?>
</body>
</html>
<?php
function actorList($conn){
$result = mysqli_query($conn, "SELECT * FROM actor_list");
}
?>
或者这种方式会起作用
<?php
$conn = mysqli_connect("localhost", "root", "","test");
if(!$conn) die("Connection failed!");
function actorList(){
global $conn;
$result = mysqli_query($conn, "SELECT * FROM actor_list");
}
?>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
</head>
<body>
<h1><a href="index.php">go to main page</a></h1>
<?php actorList()?>
</body>
</html>
推荐阅读
- google-sheets - Google 电子表格 - 无法通过 importhtml 和 importxml 获取域 linkedin.com
- java - Spring Boot 应用程序与独立工作者交互
- java - 使用 Jni4Net 从 C# 调用 Java 默认方法实现
- amazon-s3 - HashiCorp Consul 与 AWS S3 作为 HashiCorp Vault 的后端存储?
- apache-kafka - Kafka Streams stateStores 只容错一次?
- c# - 需要帮助理解这种继承层次结构
- docker - Hyperledger Fabric - 商业票据教程 - 链码实例化错误
- ios - Swift firebase .observe or .observeSingleEvent won't work
- chart.js - Chart.js 条的宽度不统一
- php - 如何在遍历使用 mysqli_use_result 返回的行时执行 mysqli 查询?(PHP)