如何正确地使用ajax插入javascript变量到mysql数据库


How to properly Insert javascript variable to mysql database using ajax

我试图实现这个问题的解决方案最好的方法添加记录到数据库使用php/ajax/mysql?

目前我的代码是这样的

JS

function FromFlash(m1, m2, m3, m4){ 
    var postData = {
        theStream: m1,
        theLabel: m2,
        theLocation: m4,
        theStatus: m3
    };
    $.post('add_stream.php', postData)
    .done(function(response) {
        alert("Data Loaded: " + response);
    });
}
PHP

//Connect to DB
...
// INSERT DATA
$data = validate($_POST);
$stmt = $dbh->('INSERT INTO Streams (theStream, theLabel, theLocation, theStatus) 
    VALUES (:theStream, :theLabel, :theLocation, :theStatus)');
$stmt->execute($data); 

if ($conn->query($sql) === TRUE) {
    echo "New stream added successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();

我得到这个错误。(第21行指支撑美元= $ dbh -> )

Data Loaded: <br />
<b>Parse error</b>:  syntax error, unexpected '(', expecting T_STRING or T_VARIABLE or '{' or '$' in <b>add_stream.php</b> on line <b>21</b><br />
我不知道我的代码出了什么问题。我检查了开/闭括号的配对,它是正确配对的

我错过了什么?

你忘了准备你的查询:)

替换:

$stmt = $dbh->('INSERT INTO Streams (theStream, theLabel, theLocation, theStatus) 
VALUES (:theStream, :theLabel, :theLocation, :theStatus)');

With this:

$stmt = $dbh->prepare('INSERT INTO Streams (theStream, theLabel, theLocation, theStatus) 
VALUES (:theStream, :theLabel, :theLocation, :theStatus)');

您错过了prepare(),并且$data应该是占位符数组。

$data = array(
':theStream'=>$_POST['theStream'],
':theLabel'=>$_POST['theLabel'],
':theLocation'=>$_POST['theLocation'],
':theStatus'=>$_POST['theStatus']
);
$stmt = $dbh->prepare('INSERT INTO Streams (theStream, theLabel, theLocation, theStatus) 
VALUES (:theStream, :theLabel, :theLocation, :theStatus)');
$stmt->execute($data); 
ajax:

var postData = {
theStream: m1,
theLabel: m2,
theLocation: m4,
theStatus: m3
};
$(".form").submit(function(){
$.ajax({
type:'post',
url:'target.php',
data: postData,
success:function(data){
//code to run after success
}
})
})
总代码:

    <?php
    include 'PDODB.php';    
    if(isset($_POST['submit'])){
    $data = array(
    ':theStream'=>$_POST['theStream'],
    ':theLabel'=>$_POST['theLabel'],
    ':theLocation'=>$_POST['theLocation'],
    ':theStatus'=>$_POST['theStatus']
    );
    $stmt = $dbh->prepare('INSERT INTO Streams (theStream, theLabel, theLocation, theStatus) 
    VALUES (:theStream, :theLabel, :theLocation, :theStatus)');

    $stmt->execute($data);
    }

?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="form">Form</button>
<script>
    var postData = {
    theStream: 'qq',
    theLabel: 'ww',
    theLocation: 'ee',
    theStatus: 'rr',
    submit: 'submit'
    };
    $(".form").click(function(){
    $.ajax({
    type:'post',
    url:this.url,
    data: postData,
    success:function(data){
    //code to run after success
    }
    })
    })
</script>