首页 > 解决方案 > 无法从 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中使用?

标签: phpsql

解决方案


为什么不传递给参数呢?

<?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>

推荐阅读