PHP issue: mysqli_error() expects exactly 1 parame

2020-02-07 11:45发布

问题:

I'm just working from some tutorials in a book, and I'm trying to put a 'Filter' option on my page. So when the page loads it should list all the values but if anything is selected from the dropdown list filter option then the list should change on the page. Here's my code:

<?php
require_once 'login.php'; 

$conn = new mysqli ($host, $user, $password, $database) or die("Connection Failed");

$col = 'Blue';

$sql = 'SELECT * FROM users ORDER BY user_creation_date desc';
$result = $conn->query($sql) or die(mysqli_error());

$columns = array('Blue', 'Pink', 'Yellow');


if (isset($_GET['column']) && in_array($_GET['column'], $columns)) {
  $col = $_GET['column'];


// prepare the SQL query
$sql = "SELECT * FROM users
        WHERE user_pref = $col";
// submit the query and capture the result
$result = $conn->query($sql) or die(mysqli_error());
}

?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Filter by User Pref</title>
</head>

<body>
<form id="form1" method="get" action="">
  <label for="column">Order by:</label>
  <select name="column" id="column">
    <option <?php if ($col == 'Blue') echo 'selected'; ?>>Blue</option>
    <option <?php if ($col == 'Pink') echo 'selected'; ?>>Pink</option>
    <option <?php if ($col == 'Yellow') echo 'selected'; ?>>Yellow</option>
  </select>
  <input type="submit" name="change" id="change" value="Change">
</form>
<table>
  <tr>
    <th scope="col">User name</th>
    <th scope="col">User pref</th>
    <th>&nbsp;</th>
    <th>&nbsp;</th>
  </tr>
  <?php while($row = $result ->fetch_assoc()) { ?>
  <tr>
    <td><?php echo $row['user_name']; ?></td>
    <td><?php echo $row['user_pref']; ?></td>

  </tr>
  <?php } ?>
</table>
</body>
</html>

The error I'm getting is

Warning: mysqli_error() expects exactly 1 parameter, 0 given on line 23.

This is line 23:

$result = $conn->query($sql) or die(mysqli_error());

回答1:

As you can see on the manual http://php.net/manual/en/mysqli.error.php , you need to pass the connection to mysqli_error(), so that line should be

$conn->query($sql) or die(mysqli_error($conn));


回答2:

You're mixing OOP and functional syntax.

mysqli_error();

should be:

$conn->error;


标签: php mysqli