gpt4 book ai didi

php - 连接数据库后执行函数

转载 作者:行者123 更新时间:2023-11-29 06:06:32 26 4
gpt4 key购买 nike

我有一个问题,我正在尝试执行可以执行 SQL 语法的函数,但是当我尝试执行它时,mysqli_query 会导致错误,因为此函数需要两个参数。但是我有另一个连接数据库的功能,我该如何解决这个问题?

function connect_to_database($servername, $username,$password,$dbname) {
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
}

function execute($get_sql) {
$sql[0] = $get_sql;
mysqli_query($sql[0]);
}

connect_to_database("localhost","root","root","m1_14");
execute("INSERT INTO teszt_1 (email,username,order,createdate) VALUES ('test@gmail.com','test','test',NOW())");

最佳答案

您需要将变量声明为“全局”:

<?php
$conn = null; // ◄■■■
$result = null; // ◄■■■

function connect_to_database($servername, $username,$password,$dbname)
{ global $conn; // ◄■■■
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
}

function execute($get_sql)
{ global $conn; // ◄■■■
global $result; // ◄■■■
$sql[0] = $get_sql;
$result = mysqli_query($conn,$sql[0]); // ◄■■■ $CONN AND $RESULT.
}

connect_to_database("localhost","root","root","m1_14");
execute("INSERT INTO teszt_1 (email,username,order,createdate) " .
"VALUES ('test@gmail.com','test','test',NOW())");

execute("select * from teszt_1");

foreach ( $result as $row ) // ◄■■■ USE $RESULT HERE.
echo $row["email"];

全局变量可让您将值从一个函数传递到另一个函数。

如果是“插入”,您不需要 $result,如果是“选择”,您可以使用 $result 来访问值。

关于php - 连接数据库后执行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41225440/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com