当前位置: 首页 > 知识库问答 >
问题:

mysqli_query()要求参数1为mysqli,给定布尔值[duplicate]

宋晋
2023-03-14

嘿,你们能帮我解决这个问题吗,因为我搞不清楚,这里是错误。

[04-Nov-2018 15:21:52 UTC] PHP Warning:  mysqli_connect(): (HY000/1045):
Access denied for user 'freeload_retain'@'vps28004.inmotionhosting.com'
(using password: NO) in /home/freeloadboard/public_html/insert.php on 
line 7
[04-Nov-2018 15:21:52 UTC] PHP Warning:  mysqli_select_db() expects 
parameter 1
to be mysqli, boolean given in /home/freeloadboard/public_html/insert.php 
on line 21
[04-Nov-2018 15:21:52 UTC] PHP Warning:  mysqli_query() expects parameter 
1 to be mysqli, boolean given in 
/home/freeloadboard/public_html/insert.php on line 45

节目:

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$con = mysqli_connect('##.##.###.##','freeload_retain','');

if(!$con)
{
    echo "Not Connected to Server. ";
}
if(!mysqli_select_db($con, 'freeload_retain'))
{
    echo "Database Not Selected. ";
}

$Companyname = $_POST['companyname'];
$Username = $_POST['username'];
$Password = $_POST['password'];
$Email = $_POST['email'];

$sql = "INSERT INTO clients (companyname, username, password, email) 
VALUES ('$Companyname', '$Username', '$Password', '$Email')";

if(!mysqli_query($con, $sql))
{
    echo "Not Inserted. ";
}
else
{
    echo "Inserted. ";
}
?>

希望你们能尽快找到答案!另外,我重复这个问题,因为我迫不及待地想再问一个问题,但谢谢你帮我解决这个问题!

共有1个答案

许毅
2023-03-14

要回答您的问题:它不起作用,因为您将列名包装在括号中,请删除这些,它应该会起作用。你也有打字错误。($comapnyname=$\u POST['companyname'];)应该是$companyname

然而,您的代码还有一些其他更大的问题。您正在使用的mysql函数已被弃用,并已从PHP7中完全删除。

接下来,您应该使用prepared语句bind_param来防止SQL注入,转义字符串无法实现这一点。

这就是使用预准备语句的样子。

// ... Set your database connection variables

/*
 * Create the database connection, notice the
 * usage of mysqli instead of mysql
 */
$connect = new mysqli($host, $user, $password, $database);

/*
 * The query, notice the usage of a question mark
 * on the place of the variables to be inserted
 */
$sql = "INSERT INTO client (cname, tname, pname, ename) VALUES (?, ?, ?, ?)";

// Prepare the query using $connect->prepare()
$stmt = $connect->prepare($sql);

// Check if the query was prepared
if(!$stmt) {
  // ... Handle your error
}

// Get $_POST variables
$companyname = $_POST['companyname'];
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];

if(!$stmt->bind_param('ssss', $companyname, $username, $password, $email)) {
  // ... Handle your error
}

if(!$stmt->execute()) {
  // ... Handle your error
} else {
  echo 'Record inserted.';
}

似乎您正在将密码以明文形式插入数据库,这是一个大问题。你应该把它们切碎。编写两个函数,一个用于散列密码,另一个用于在用户登录时验证密码。

第一个函数将返回密码散列,如果密码正确或不正确,第二个函数将返回TRUEFALSE

function hashPassword($password) {
  return password_hash($password, PASSWORD_DEFAULT);
}

function verifyPassword($password, $hash) {
  return password_verify($password, $hash);
}
 类似资料: