第一次构建网站,我希望这个“跟踪器页面”(index.php) 成为一个 HTML 表单,我可以在其中提交我的锻炼信息。提交后,我希望页面刷新并为下一次提交做好准备。我的问题是我有一个 login.php 页面,它从 login.php 到我的 index.php 的第二个页面将空行插入数据库。
我最近的解决方案尝试使 $excercisename 不能为 null,但作为 VARCHAR,它会自动以 '' 形式提交到数据库中。我已经尝试在一些评论中修复这个问题,但没有成功:(请问有人有任何理想的解决方案来解决这个问题吗?没有发布 HTML,因为我认为这是 PHP 问题?但我是菜鸟。
<?php
//Connect to database
include('database.php');
//grab user logged in for database insertion
$user_check = $_SESSION['login_user'];
$ses_sql = mysqli_query($dbcon,"select username from t_login where username = '$user_check' ");
$row = mysqli_fetch_array($ses_sql,MYSQLI_ASSOC);
$login_session = $row['username'];
// Create DB Variable
$login_session = $row['username'];
//if(empty($_POST['exercisename'])) {return null;} ELSE {$_POST['excercisename'];}
//$excercisename = (empty($_POST['$excercisename']) ? $_POST['$excercisename'] : null);
$excercisename = (isset($_POST['excercisename']) ? $_POST['excercisename'] : null);
$setcount = (isset($_POST['setcount']) ? $_POST['setcount'] : null);
$rep1 = (isset($_POST['rep1']) ? $_POST['rep1'] : null);
$weight1 = (isset($_POST['number1']) ? $_POST['number1'] : null);
$comments = (isset($_POST['comments']) ? $_POST['comments'] : null);
$sql = "INSERT INTO t_workout (username, excercisename, setcount, set1reps, set1weight, comments)
VALUES ('$login_session', '$excercisename', '$setcount', '$rep1', '$weight1', '$comments')";
if ($dbcon->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Waiting for entry.";
//echo "Error: " . $sql . "<br>" . $dbcon->error;
}
$dbcon->close();
?>
最佳答案
试试这个:
if(isset($excercisename) and !empty($excercisename)){
$sql = "INSERT INTO t_workout (username, excercisename, setcount, set1reps, set1weight, comments)
VALUES ('$login_session', '$excercisename', '$setcount', '$rep1', '$weight1', '$comments')
}
注意安全,我看到你没有使用 pdo 或 sql-li 来防止注入(inject)攻击,这是基本的!!
关于PHP 自动将数据插入数据库的烦恼,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45644851/