我有一个问题,我试图做可以执行sql语法的函数,但是当我试图执行它时mysqli_querry丢弃一个错误,导致这个函数需要两个参数。但我有另一个连接到数据库的功能,我该如何解决这个问题呢?
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())");
答案 0 :(得分:2)
您需要声明变量“global”:
<?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
来访问这些值。
答案 1 :(得分:0)
这样做:
mysqli_query
需要两个参数而且只提供一次,所以为execute
函数提供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);
}
//return connection or define connection as global and use as global scenario
return $conn;
}
function execute($get_sql, $connect) {
$sql[0] = $get_sql;
mysqli_query($connect, $sql[0]);
}
$connection = connect_to_database("localhost","root","root","m1_14");
execute("INSERT INTO teszt_1 (email,username,order,createdate) VALUES ('test@gmail.com','test','test',NOW())", $connection);