我正在尝试创建一个函数,使用mysqli(对我来说是全新的)来检查mysql中的重复条目,但我无法理解这个错误。我有3个php文件:db.php - db连接functions.php和我的函数(需要db.php)和submit.php - 接受输入的文件。
db.php中:
<?php
define("HOST", "localhost"); // The host you want to connect to.
define("USER", "user"); // The database username.
define("PASSWORD", "pass"); // The database password.
define("DATABASE", "db_list"); // The database name.
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
?>
的functions.php:
require 'db.php';
function check($str, $mysqli) {
$checkdupe = $mysqli->prepare("SELECT name FROM list WHERE str = ?"); //line giving me error
$checkdupe->bind_param("s", $str);
$checkdupe->execute();
$checkdupe->store_result();
if ($checkdupe->num_rows > 0) {
//dupe found
return true;
} else {
//no dupe
return false;
}
}
submit.php
require 'functions.php';
if (isset($_POST['name'])) {
if (check($_POST['name'], $mysqli) == true) { //added $mysqli parameter
echo "success!";
} else {
echo "fail;
}
} else {
echo 'invalid post';
}
?>
答案 0 :(得分:2)
你的功能定义是
function check($str, $mysqli) {
但你只用第一个参数调用它。因此,第二个参数为null。
check($_POST['name'])
所以使用,
check($_POST['name'], $mysqli)
此外,您不会检查db.php中的连接确实成功。在文件末尾添加:
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
答案 1 :(得分:0)
您的函数check
需要2个参数。您只为其分配1个属性:
if (check($_POST['name']) == true)
应该是
if (check($_POST['name'], $mysqli) == true)
答案 2 :(得分:-1)
db.php中:
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
define("HOST", "localhost"); // The host you want to connect to.
define("USER", "user"); // The database username.
define("PASSWORD", "pass"); // The database password.
define("DATABASE", "db_list"); // The database name.
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
var_dump('db:',is_object($mysqli));
的functions.php:
<?php
require 'db.php'
var_dump('functions:',is_object($mysqli));
function check($str, $mysqli) {
var_dump('check:',is_object($mysqli));
$checkdupe = $mysqli->prepare("SELECT name FROM list WHERE str = ?");
$checkdupe->bind_param("s", $str);
$checkdupe->execute();
$checkdupe->store_result();
return $checkdupe->num_rows;
}
submit.php
<?php
require 'functions.php';
var_dump('submit:',is_object($mysqli));
if (isset($_POST['name'])) {
if (check($_POST['name'], $mysqli)) {
echo "success!";
} else {
echo "fail";
}
} else {
echo 'invalid post';
}
答案 3 :(得分:-2)
尝试:
global $mysqli;
check($mysqli, ...);