Reputation: 35
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.
Upvotes: 0
Views: 45
Reputation: 4760
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();
Upvotes: 1