我有一个正在创建的本地Web应用程序,当前正在运行wamp服务器。 MySQL表已创建,php正在工作。我将php扩展名放在我的文件中,而不是html。我有一个简单的网页,带有用于输入名字的文本框和一个按钮,该按钮运行一个函数以将变量传递给连接到我的数据库的外部php文件。我正在尝试使用该变量将其插入到数据库中,但无法弄清楚。
我的带有文本框的php页面看起来像这样:
<!DOCTYPE HTML>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script type = "text/javascript">
function myAjax () {
$.ajax( { type : 'POST',
data : {'action':document.getElementById('FirstName').value},
url : 'queue.php',
success: function ( data ) {
alert( data );
},
error: function ( xhr ) {
alert( "error" );
}
});
}
</script>
</head>
<body>
<center><input type="text" name="FirstName" id = "FirstName" value="" ></input></center><br>
<center><button id = "addUser" type="button" onclick = "myAjax()" disabled>+Add User</button></center><br>
</body>
</html>
现在我的外部php文件位于与我的网页相同的目录中。
<?php
session_start();
$_SESSION["my_data"] = $_POST['action']; // STORE VALUE IN VARIABLE.
echo "data received = " . $_SESSION["my_data"]; // RETURN VALUE TO CONFIRM.
$servername = "localhost";
$database = "Users";
$username = "root";
$password = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$sql = "INSERT INTO queue (singer) VALUES ('I can insert a value here but want the value of my variable that was passed over')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
?>
答案 0 :(得分:0)
我的插入语句现在看起来像这样并且可以正常工作!
$ sql =“ INSERT INTO queue(singer)VALUES('”。$ _ SESSION [“ my_data”]。“')”;