我的表类别包含以下列:
idcategory categorySubject users_idusers
我有一个带有简单单选按钮和文本框的表单。 我有一个select all语句类别,需要将idcategory存储到变量($ getCatId)中,所以我可以使用这个语句:
main
获取和存储categoryid的最佳方法是什么?
$sql="INSERT INTO topic(subject, topicDate, users_idusers, category_idcategory, category_users_idusers) VALUES('($_POST[topic])', '$date', '$_SESSION[userid]', '$getCatId', '$_SESSION[userid]');";
答案 0 :(得分:0)
如果我正确理解了这个问题,那么您的$getCatId
(发送表单后)中的$_POST['category']
(类别的ID)就会出现
答案 1 :(得分:0)
您应该做的第一件事就是在SQL injection来拜访您之前通过参数化查询来保护自己免受Bobby Tables的侵害。
您可能还会考虑使用PDO,因为它是一个与许多不同数据库管理系统配合使用的一致API,因此这为您带来了非常便携的代码。 Here's an annotated working example on Github:
<?php
// returns an intance of PDO
// https://github.com/jpuck/qdbp
$pdo = require __DIR__.'/mei_DV59j8_A.pdo.php';
// dummy signin
session_start();
$_SESSION['signedIn'] = true;
$_SESSION['userid'] = 42;
//show form if not posted
if($_SERVER['REQUEST_METHOD'] != 'POST'){
$sql = "SELECT * FROM category;";
// run query
$result = $pdo->query($sql);
?>
<form method="post" action="createTopic.php">
Choose a category:
</br>
</br>
<?php
// get results
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo "
<div class= 'choice'>
<input type='radio' name='category' value='$row[idcategory]'/>
$row[categorySubject]
</div>
</br>
";
}
echo '
Topic: <input type="text" name="topic" minlength="3" required>
</br></br>
<input type="submit" value="Add Topic" required>
</form>
';
}
if ($_POST){
if(!isset($_SESSION['signedIn']) && $_SESSION['signedIn'] == false){
echo 'You must be signed in to contribute';
} else {
// simulate your date input
$date = date("Y-m-d");
// bind parameters
$sql = "
INSERT INTO topic (
subject, topicDate, users_idusers, category_idcategory, category_users_idusers
) VALUES(
:subject, :topicDate, :users_idusers, :category_idcategory, :category_users_idusers
);
";
// prepare and execute
$statement = $pdo->prepare($sql);
$statement->execute([
'subject' => "($_POST[topic])",
'topicDate' => $date,
'users_idusers' => $_SESSION['userid'],
// to answer your question, here's your variable
'category_idcategory' => $_POST['category'],
'category_users_idusers' => $_SESSION['userid'],
]);
echo "Added!";
}
}