如何解决“参数必须是实现Countable的数组或对象?”

时间:2019-02-01 15:48:06

标签: php

  

警告:count():参数必须是数组或对象,   在第30行的C:\ xampp \ htdocs \ try \ process.php中实现Countable。

这就是我的代码所说的。似乎很好,但是当我按编辑时,将显示此错误。我不明白有人可以指出我在第30行发生的情况吗?

这是我的process.php

<?php
require("1password.php");
$id = 0;
$update = false;
$username='';
$password='';

 if (!session_id()) { session_start(); }
    $mysqli = new mysqli("localhost","root","","id7508046_isalon") or die(mysqli_error($mysqli));
    if(isset($_POST['save'])){
        $username = $_POST['username'];
        $password = $_POST['password'];
        $passwordHash = password_hash($password, PASSWORD_DEFAULT);
        $mysqli->query("INSERT INTO isalonusers (username, password) values ('$username', '$passwordHash')") or die($mysqli->error);
        $_SESSION['message'] = "New account saved!";
        $_SESSION['msg_type'] = "success"; 
        header("location: userlist.php");
    }
    if(isset($_GET['delete'])){
        $id = $_GET['delete'];
        $mysqli->query("DELETE FROM isalonusers WHERE user_id=$id") or die($mysqli->error());
        $_SESSION['message'] = "User Account Deleted!";
        $_SESSION['msg_type'] = "danger";
        header("location: userlist.php");
    }
    if(isset($_GET['edit'])){
        $id = $_GET['edit'];
        $update = true;
        $result = $mysqli->query("SELECT * FROM isalonusers WHERE user_id=$id") or die($mysqli->error());
        if(count($result)==1){
            $row = $result->fetch_array();
            $username = $row['username'];
            $password = $row['password'];
        }

    }
    if(isset($_POST['update'])){
        $id = $_POST['id'];
        $username = $_POST['username'];
        $password = $_POST['password'];
        $passwordHash = password_hash($password, PASSWORD_DEFAULT);
        $mysqli->query("UPDATE isalonusers SET username ='$username', password='$passwordHash' WHERE user_id=$id") or die($mysqli->error());
        $_SESSION['message'] = "User Account has been updated!";
        $_SESSION['msg_type'] = "warning";

        header("location: userlist.php");
    }

?>

2 个答案:

答案 0 :(得分:1)

$result->num_rows用这种方式怎么样?

if(isset($_GET['edit'])){
    $id = $_GET['edit'];
    $update = true;
    $result = $mysqli->query("SELECT * FROM isalonusers WHERE user_id=$id") or die($mysqli->error);
    if(isset($result->num_rows) && $result->num_rows > 0){
        $row = $result->fetch_array(MYSQLI_ASSOC);
        $username = $row['username'];
        $password = $row['password'];
    }
  }

参见参考号:http://php.net/manual/en/mysqli.query.php

答案 1 :(得分:1)

事实上,您无需计数。这只是多余的步骤。

如果您有所考虑,可以先简单地获取数据,然后在条件中使用它。更重要的是,必须使用参数化查询。所以代码应该是

$stmt = $mysqli->prepare("SELECT * FROM isalonusers WHERE user_id=?");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
// here goes your problem with "count" 
$row = $result->fetch_array(MYSQLI_ASSOC)
if($row) {
    $username = $row['username'];
    $password = $row['password'];
}

您也不应使用该terrible practice with or die