0

I'm using a function in which I'm assigning a variable a tablename value like:

function mshirt(){
    var tbname='m_shirts';
}

Then in PHP form action section:

include 'database_connection.php';
$tablename=tbname;
if(isset($_POST['submit'])){

    $Size=$_POST['size'];
    $Color=$_POST['color'];
    $Code=$_POST['code'];
    $Brand=$_POST['brand'];

    $sql="INSERT INTO `$tablename` (size,color,code,brand) VALUES('$Size','$Color','$Code','$Brand')";

    if(mysqli_query($conn,$sql)){
        echo("Added Succesfully");
    }
    else 
        echo("Failed to Add");

The problem is that it assumes tbname to be undefined constant.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Saad Basit
  • 43
  • 1
  • 5

2 Answers2

0

PROBLEM

The error is because of the line:

$tablename=tbname;

tbname is a JS (client-side) variable: you cannot simply enter it into PHP (server-side) and expect it to work. You need to instead send it over as POST data to PHP, just like you would other data.


SOLUTION

If you were doing this by AJAX and jQuery, for example:

var tbname = 'm_shirts';

$.ajax({
    url: "path_to_php_file.php",
    method: "post",
    data: {
        tbname: tbname,
        // the rest of form data (the request) to be sent
    }
});

And in PHP, you would get this as a regular $_POST variable index:

$tbname = $_POST["tbname"];

(If you were sending the data using a regular form or some other method, you would need to modify this... this is just an example for demonstration.)

Jonathan Lam
  • 16,831
  • 17
  • 68
  • 94
-1

You are trying to mix languages...

You should send the name of the table via ajax or form and then catch your value with $_GET or $POST

Mirdrack
  • 780
  • 12
  • 28