我在向数据库中插入下拉值时遇到问题

I'm having a problem inserting a dropdown value to database

我有这个代码:

if (isset($_POST['save'])) {
    $name = $_POST['name'];
    $price = $_POST['price'];
    $description = $_POST['description'];
    $new_description = str_replace("'", "\'", $description);
    $cat_name = $_POST['dropdown'];

    $cat_id = mysqli_query($db, "SELECT cat_id FROM category where cat_name = '$cat_name';");

    mysqli_query($db, "INSERT INTO products (item_name, item_price, item_cat_id, item_descr) VALUES ('$name', '$price', '$cat_id', '$new_description')"); 
    $_SESSION['message'] = "Le produit a été ajouté avec succès!"; 
    header('location: admin.php');
}

我想使用类别名称获取类别 ID,并用它来设置产品 table 中 item_cat_id 列的值。

但是当我点击保存时,我得到了这个错误:

Fatal error: Uncaught Error: Object of class mysqli_result could not be converted to string in C:\xampp\htdocs\jst\server.php:23
Stack trace:
#0 {main} thrown in C:\xampp\htdocs\jst\server.php on line 23

参见 mysqli_query return values

它 returns 是 falsetruemysqli_result 对象,取决于查询以及是否成功。显然结果是一个 mysql_result 对象,因此错误“...class mysqli_result 的对象无法转换为字符串... " 在你的第二个 mysqli_query() 中。参见 mysql_result

但首先,不要直接使用用户提供的数据。这导致 SQL 注入。请改用 prepared statements

$cat_id = null;
$stmt = mysqli_prepare($db, 'SELECT cat_id FROM category where cat_name = ?');
mysqli_stmt_bind_param($stmt, 's', $cat_name);
mysqli_stmt_execute($stmt);  // true on success, otherwise false
mysqli_stmt_bind_result($stmt, $cat_id);  // true on success, otherwise false;
mysqli_stmt_fetch($stmt);  // true on success, false if not, null if no more data
...
$stmt = mysqli_prepare($db, 'INSERT INTO products (item_name, item_price, item_cat_id, item_descr) VALUES (?, ?, ?, ?)');
mysqli_stmt_bind_param($stmt, 'sdis', $name, $price, $cat_id, $new_description);
...

您实际上不需要在给定类别名称的情况下查询类别 ID。而是传递类别 ID。例如 HTML:

<form ...>
    <select ...>
        <option value="1" ...>Some category name</option>
        ...
    </select>
</form>

虽然这并不意味着您不需要查询类别。您仍然需要确保类别 ID 有效或无效。当然,如果你不控制 frontend/html/ui/etc.

这可能是不可能的