我向数据库发送一个字符串以写入数据库。我有两个字段,一个叫做num,它设置为自动递增,另一个叫做写入我的字符串的卡片。到目前为止,我已经能够让我的php将变量写入数据库,但现在我希望它返回与之关联的num,所以我可以在我的页面上使用它。任何人都可以帮我写这个,我是php的新手。我想我需要另一个SQL查询? (我希望它能回显我刚刚写入的行的num列,而不是"记录添加成功。")。
PHP:
// Attempt MySQL server connection *
$link = mysqli_connect
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$cards = mysqli_real_escape_string($link, $_GET['cards']); //get data from javascript
$sql = "INSERT INTO drafts (cards) VALUES ('$cards')"; }
mysqli_query($link, $sql);
if(mysqli_query($link, $sql)){
echo mysqli_insert_id($link);
} else {
echo "failed!";
}
// Close connection
mysqli_close($link);
?>
JS:
function writeDraft() {
$.ajax({
url: 'php/write.php',
type: 'get', //data type post/get
data: {
cards: output
},
complete: function (response) {
$('#draftNum').text(response.responseText);
},
error: function () {
console.log('Bummer: there was an error!');
}
});
return false;
}
writeDraft();
答案 0 :(得分:0)
mysqli_insert_id()将完成这项工作
if(mysqli_query($link, $sql)) {
echo "Records added successfully with id: ".mysqli_insert_id($link);
}
答案 1 :(得分:0)
$sql = "SELECT * FROM drafts";
$result = mysqli_query($link, $sql);
$num = mysqli_num_rows($result);
$sql = "INSERT INTO drafts (cards) VALUES ('$cards')"; }
if(mysqli_query($link, $sql)){
echo $num+1, " Records added successfully.";
}
// Close connection
mysqli_close($link);
?>