【问题标题】:Posting into database using mysqli使用 mysqli 发布到数据库
【发布时间】:2016-02-06 00:32:15
【问题描述】:

我正在学习 php 并尝试完成以下工作:

<?php
require_once("db_connect.php");

    // TODO - Check that connection was successful.

    $dname = $_POST["dname"];
    $daddress = $_POST["daddress"];


    $stmt = $mysqli->prepare("INSERT INTO test (dname, daddress) VALUES (?, ?)");

    // TODO check that $stmt creation succeeded

    // "s" means the database expects a string
    $stmt->bind_param("s", $dname, $daddress);

    $stmt->execute();

    $stmt->close();

    $mysqli->close();
?>

它只适用于一个 bind_param 而不是 2。如果 $daddress 从代码中删除,则它会发布。该表单有 26 个帖子到数据库中,我目前正在使用 2 个帖子来保持它的最小化。

提交表单时出现以下错误。

警告:mysqli_stmt::bind_param() [mysqli-stmt.bind-param]:类型定义字符串中的元素数与 /home/mymotorsportco/public_html/entry/actions/entry 中的绑定变量数不匹配。第15行的php

【问题讨论】:

    标签: php mysql mysqli


    【解决方案1】:

    根据PHP manual

    类型

    包含一个或多个指定相应绑定变量类型的字符的字符串

    i - 对应变量的类型为整数

    d - 对应变量的类型为 double

    s - 对应变量的类型为字符串

    b - 对应的变量是一个 blob,会以数据包的形式发送

    您必须为要绑定的所有参数添加类型。所以如果第二个参数是字符串,就必须这样做

    $stmt->bind_param("ss", $dname, $daddress);
    

    【讨论】:

    • 谢谢你的回答,它也帮助我理解了我做错了什么。
    • @JosephThomasMallinson 非常欢迎您。如果它真的对您有帮助,请接受它:) 享受您的编码
    【解决方案2】:

    您需要将相同数量的字符传递到第一个参数中,因为您需要将值注入到查询中。例如:

     $stmt->bind_param("ss", $dname, $daddress);
    

    会说第一个参数是一个字符串,第二个也是。此外,以下将告诉数据库期待一个字符串,然后是一个 int:

     $stmt->bind_param("si", $dname, $daddress);
    

    使用准备好的语句的大道具,大多数新手会在绝对没有卫生的情况下投入变量。你在正确的轨道上!

    【讨论】:

    • 感谢您的详细回答和肯定的评价!
    【解决方案3】:

    你有 2 个字符串而不是 1 个。

    $stmt->bind_param("ss", $dname, $daddress);
    

    【讨论】:

      猜你喜欢
      • 2013-07-29
      • 2016-10-22
      • 1970-01-01
      • 2015-08-04
      • 2013-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-06
      相关资源
      最近更新 更多