Pallavi Prasad
Pallavi Prasad

Reputation: 587

php variable not getting substituted with value

I have an issue. I am sending data from javascript to PHP. In PHP the value is extracted into a variable. This value has to be substituted in the create statement. It is not getting substituted. On echoing the php variable is being read. why isn't it getting passed to the create statement? The relevant code snippets are below:

AJAX call:

$.ajax({
    type: "POST",
    url: "createTableInDB.php",
    data: 'pTblName=' + filename,
    success: function(msg){
        alert(msg);
    }
});

When I check in PHP, the filename is taken into the variable correctly.

PHP code:

$username="root";
$pass="";

try {
    $db_conn = new PDO("mysql:host=localhost;dbname=test", $username, $pass);
    // set the PDO error mode to exception
    $db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db_conn->setAttribute(PDO::ATTR_EMULATE_PREPARES , false);

    $tblName = stripcslashes($_POST['pTblName']);

    $sql = "CREATE table If Not Exists $tblName (
            Sl_No varchar(4) Primary Key,
            E_Name varchar(100) not null,
            EXP varchar(10) not null);";

    $db_conn->exec($sql);

    echo("Created Table");


    }
catch(PDOException $e)
{
    echo "Connection failed: " . $e->getMessage();
}

Can anyone guide me where I am wrong? I am not getting any error messages. The page just reloads and everything resets.

The function calling the function with ajax: function extractName(){ fullPath = document.getElementById('testInputFile').value;

    if (fullPath) {
        var startIndex = (fullPath.indexOf('\\') >= 0 ? fullPath.lastIndexOf('\\') : fullPath.lastIndexOf('/'));
        filename = fullPath.substring(startIndex);
        if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
            // filename = filename.substring(1);
            filename = filename.substring(1, filename.lastIndexOf('.'));
        }

        //console.log(filename);
        createTableInDB(filename);
    //  Excel = readExcelFile(fullpath);
    }
   }

This function is called in the submit button of the html form

Upvotes: 1

Views: 82

Answers (2)

Pallavi Prasad
Pallavi Prasad

Reputation: 587

The issue got resolved. In the PHP code, I just added the following lines:

$sql="use test";
$db_conn->exec($sql);

I added this before the create statement and it is working.

Everyone's help and guidance is much appreciated.

Upvotes: 0

BENY
BENY

Reputation: 41

try this :

$.ajax({
    type: "get",
    url: "createTableInDB.php",
    data: 'pTblName=' + filename,
    success: function(msg){
        alert(msg);
    }
});

And your php cod edit this line :

$tblName = stripcslashes($_GET['pTblName']);

Upvotes: 1

Related Questions