mysqli_query()期望参数1为mysqli,给定布尔值

时间:2018-11-03 21:57:48

标签: php html mysqli

嘿,大家能帮我这个忙,因为我不知道这里是错误。

[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 个答案:

答案 0 :(得分:1)

要回答您的问题:它不起作用,因为您将列名包装在方括号中,请将其删除,它应该可以工作。您也有错字。 ($comapnyname = $_POST['companyname'];)应该为$companyname

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

接下来,您应该使用prepared statementsbind_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);
}