我理解有一种方法可以从select语句中插入一个常量,我从here找到了来源,如:
INSERT INTO MyTable(ColA,ColB,ColC)
SELECT 1,colBB,colCC FROM MyTable2
但是是否可以添加用户输入值(使用php)而不是常量值?如果可能,请提供示例。提前谢谢。
更新: 我试图创建一个简单的网页,但有一些语法错误,我不知道解决它:
解析错误:语法错误,意外''(T_ENCAPSED_AND_WHITESPACE),期望标识符(T_STRING)或变量(T_VARIABLE)或数字(T_NUM_STRING)在第10行的C:\ xampp \ htdocs \ webservice \ result.php
以下是我的代码:
<?php
//start a session
require("config.inc.php");
$username = $_SESSION["username"];
if(!empty($_POST)){
//check if user choose non-required drop down list
if(empty($_POST['subcategory'])){
if(empty($_POST['yearofstudy'])) {
$query = "INSERT INTO comments ( username, title, message, tousername )
SELECT :username, :title, :message, username
FROM utarstudents WHERE faculty = :faculty";
$query_params = array(
':faculty' => $_POST['category'],
':username' =>$username,
':title' =>$_POST['title'],
'message' =>$_POST['message']
);
}
else {
$query = "INSERT INTO comments ( username, title, message, tousername )
SELECT :username, :title, :message, username
FROM utarstudents WHERE faculty = :faculty AND year_of_study = :yearofstudy";
$query_params = array(
':faculty' => $_POST['category'],
'yearofstudy' => $_POST['yearofstudy'],
':username' =>$username,
':title' =>$_POST['title'],
'message' =>$_POST['message']
);
}
}
else {
if(empty($_POST['yearofstudy'])) {
$query = "INSERT INTO comments ( username, title, message, tousername )
SELECT :username, :title, :message, username
FROM utarstudents WHERE faculty = :faculty AND course = :course";
$query_params = array(
':faculty' => $_POST['category'],
':course' => $_POST['subcategory'],
':username' =>$username,
':title' =>$_POST['title'],
'message' =>$_POST['message']
);
}
else {
$query = "INSERT INTO comments ( username, title, message, tousername )
SELECT :username, :title, :message, username
FROM utarstudents WHERE faculty = :faculty AND year_of_study = :yearofstudy AND course = :course";
$query_params = array(
':faculty' => $_POST['category'],
'yearofstudy' => $_POST['yearofstudy'],
':course' => $_POST['subcetagory'],
':username' =>$username,
':title' =>$_POST['title'],
'message' =>$_POST['message']
);
}
}
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
die("Failed to run query: " . $ex->getMessage());
}
}
答案 0 :(得分:-1)
以下是我编辑过的代码片段,可以完成您的尝试。所以在我的表单文件中,我有这样的东西来为项目做贡献:
<form name="contribute" method="post" action="contribute-dbquery.php" onsubmit="return validateForm()">
First Name:
<input name="nameValue" type="text" size="40" maxlength="12" required/>
<input name="Submit" type="submit" value="Add"/>
</form>
所以它说的是当Add使用nameValue的值转到Tcontribute-dbquery.php时。然后在我的contrib-dbquery.php中,我将表单中的nameValue分配给$ name,然后将其插入到我的数据库中。我将它分配给变量,因为我也在该页面上使用过它。如果需要,您可以将其插入数据库中。
$name = $_POST['nameValue'];
$insert_sql = "INSERT INTO mastertable (name) VALUES (' " . $name . " ')";
如果这有助于将其标记为已回答。如果您需要任何帮助,请告诉我。