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 "

record added

; window.location.href='index.php';"; } 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.

Drake Madigan

Ответов: 1

Ответы (1)

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 "

record added

; window.location.href='index.php';"; } 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();

2022 WebDevInsider