我想用这个函数插入sql,但这不起作用,任何想法都可以解决这个问题
错误是警告:mysqli_query() 期望参数 1 是 mysqli,在第 29 行的 C:''WampServer''www''test.php 中给出空
<html>
<body>
<?php
$Connection = mysqli_connect('localhost', 'root', '', 'pytshqip');
$contact_method = 'aaaaa';
$form_data = array
(
'text' => $contact_method,
'from' => $contact_method,
'user_1' => $contact_method,
'user_2' => $contact_method,
'date' => time()
);
dbRowInsert('chat', $form_data);
function dbRowInsert($table_name, $form_data)
{
// retrieve the keys of the array (column titles)
$fields = array_keys($form_data);
// build the query
$sql = "INSERT INTO ".$table_name."
(`".implode('`,`', $fields)."`)
VALUES('".implode("','", $form_data)."')";
// run and return the query result resource
return mysqli_query($Connection, $sql);
}
?>
</body>
</html>
当你使用变量$Connection时,它是在函数 dbRowInsert() 之外定义的,你需要使用 global 关键字。
function dbRowInsert($table_name, $form_data)
{
global $Connection;
// retrieve the keys of the array (column titles)
$fields = array_keys($form_data);
// build the query
$sql = "INSERT INTO ".$table_name."
(`".implode('`,`', $fields)."`)
VALUES('".implode("','", $form_data)."')";
// run and return the query result resource
return mysqli_query($Connection, $sql);
}
您可以在此处找到更多信息:http://php.net/manual/en/language.variables.scope.php
您的变量在函数范围之外。先在 dbRowInsert()
函数中添加global $Connection;
,然后再使用 $Connection
访问函数范围内的变量。