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 深度学习残差模块模型
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)