doutui4649 2016-01-01 04:31
浏览 63
已采纳

为什么这不插入mysqli数据库?

So I can not figure out why this is not adding the content to the DB. I need to add the itemcode and item into the database then be able to read it. This is what i have:

add.php

include('dbconnect.php');
function get_posts() {
    $txtitemcode = (!empty($_POST['itemcode']) ? $_POST['itemcode'] : null);
    $txtitem = (!empty($_POST['item']) ? $_POST['item'] : null);
    $sql1 = "INSERT INTO barcode (itemcode, item) VALUES ('".$txtitemcode."','".$txtitem."')";
    if(!mysqli_query($con, $sql1))
    {
        die('Error:'.mysqli_error());
    }
    echo "<h1>record added</h1>;
    window.location.href='index.php';</script>";
}

mysqli_close($con);

dbconnect.php

$con = mysqli_connect("localhost","root","root","db1");

// Check connection
if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
    echo "Connected to Database. Please Continue.";
}

Is anyone able to help?? This is weird to me that it is not working.

  • 写回答

1条回答 默认 最新

  • dongtangjie0495 2016-01-01 04:35
    关注

    It looks like you are calling your insert query from inside of a function yet $con is in the global scope. To include $con within your function you must do this:

    include('dbconnect.php');
    function get_posts() {
        global $con;
        $txtitemcode = (!empty($_POST['itemcode']) ? $_POST['itemcode'] : null);
        $txtitem = (!empty($_POST['item']) ? $_POST['item'] : null);
        $sql1 = "INSERT INTO barcode (itemcode, item) VALUES ('".$txtitemcode."','".$txtitem."')";
        if(!mysqli_query($con, $sql1))
        {
            die('Error:'.mysqli_error());
        }
        echo "<h1>record added</h1>;
        window.location.href='index.php';</script>";
    }
    get_posts(); // you can call get_posts() here
    
    mysqli_close($con);
    

    Basically, global is a PHP keyword that will allow you to access variables that have been defined in the global scope. Read about in the documentation by clicking here

    [..] within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope.

    And, be sure to call your function, it is as simple as typing the following:

    get_posts();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器