我在使用MySQLI代码生成注册时遇到问题。表/连接变量匹配,并且通过查询传递的正确变量填充了预期的字符串,在执行任何类型的查询时运行query
或prepare & execute
时,我会返回以下:
致命错误:在非对象中调用成员函数query() 第40行/var/www/New/API/FormValidations.php
我的代码如下:
$Query = $STD->prepare("SELECT * FROM Users WHERE Username='$Username'");
$Query->execute();
$Number = $Query->num_rows;
if ($Number !== 0)
{
echo "Username Already In Use";
}
else
{
$Insert_User = $STD->prepare("INSERT INTO Users ('Username', 'Password') VALUES ('$Username', '$Password)");
$Insert_User->execute();
echo "Account Created!";
}
这是我的连接脚本:
$STD = new mysqli('localhost', 'root', 'xxxxx', 'SLMS');
$AccessCon = new mysqli('localhost', 'root', 'xxxxx', 'DBAccess');
if ($AccessCon->connect_error) {
die("Access Has Been Revoked. Please Contact Administration");
}
if ($STD->connect_error) {
die("Standard Access Has Been Revoked. Please Contact Administration");
}
和我的用户SQL表:
CREATE TABLE IF NOT EXISTS `Users` (
`ID` int(255) NOT NULL AUTO_INCREMENT,
`Username` varchar(255) NOT NULL,
`Password` text NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
我试过评论我的所有查询代码,然后运行
$Query = $STD->query("SHOW TABLES");
$Results = $STD->fetch_array(MYSQLI_ASSOC);
这仍然会在我的$Query
变量上返回错误。
我还尝试修改我的代码以搜索数据库中已存在的内容:
$Query = $STD->prepare("SELECT * FROM Users WHERE Username='Test'");
并尝试将我的$Username
括起来:
$Query = $STD->prepare("SELECT * FROM Users WHERE Username='{$Username}'");
这已经取得了成功。我想知道是否有人可以对这种情况有所了解?
修改
评论整个脚本并运行:
$Query = $STD->query("SHOW TABLES");
$test = $Query->fetch_array(MYSQLI_ASSOC);
print_r($test);
返回结果。
更新
我已将代码修改为:
$Query = $STD->prepare("SELECT * FROM Users WHERE Username=?");
$Query->bind_param("s", $Username);
$Query->execute();
最终更新:
致命错误:在非对象上调用成员函数bind_param() 在第45行的/var/www/New/Register.php中
这是新错误。
违规行:
$Insert_User = $STD->prepare("INSERT INTO Users ('Username', 'Password') VALUES (?, ?)");
$Insert_User->bind_param("ss", $Username, $Password);
$Insert_User->execute();
答案 0 :(得分:1)
使用prepare时,您必须绑定包含值的变量。
示例:
$city = "Amersfoort";
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $city);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($district);
/* fetch value */
$stmt->fetch();
printf("%s is in district %s\n", $city, $district);
/* close statement */
$stmt->close();
}
此处链接指向prepared statements
<强>更新强>
这样:
$Query = $STD->prepare("SELECT * FROM Users WHERE Username=s");
应该是:
$Query = $STD->prepare("SELECT * FROM Users WHERE Username=?");
这样:
$Insert_User = $STD->prepare("INSERT INTO Users ('Username', 'Password') VALUES ('U', 'P)");
应该是:
$Insert_User = $STD->prepare("INSERT INTO Users ('Username', 'Password') VALUES (?, ?)");
这个:
$Insert_User->bind_param('U', $Username);
$Insert_User->bind_param('P', $Password);
应该是这样的:
$Insert_User->bind_param('ss', $Username,$Password);