我有一个包含两个表的数据库:“用户”和“费用”。 表用户: id - 主,自动递增; 用户名密码 ,等等将值写入数据库中的另一个表
表开支: ID(这不是自动增量), 用户名,ammount的,日期的原因 - >等领域。
我使用了一个名为getuserfields()函数来获得从用户表中的字段(它是存储在一个文件core.php中我每一个PHP都需要):
if (!function_exists('getuserfield')) {
function getuserfield($field) { //
//echo $_SESSION['user_id'];
$query = "SELECT `$field` FROM `users` WHERE `id`='".$_SESSION['user_id']."'";
/*$query2 = "SELECT `$field` FROM `expenses` WHERE `id`='".$_SESSION['user_id']."'";*/
if ($query_run = mysql_query($query)) {
if($query_result = mysql_result($query_run, 0, $field)){ // get the result form the query, row 0 (1 row) cause that is gonna return 1 row/
return $query_result;
}
}
}
}
在我的index.php文件我已经声明的变量:
if (loggedin()){
$firstname = getuserfield('firstname');
.....
$spent = getuserfield('spent'); //until here they work as these are variables from users table
$ammount = getuserfield('ammount'); //the following are variables from expenses table, and are not working
$date = getuserfield('date');
$reason = getuserfield('reason');
$username = getuserfield('username');
我试图把它们写到通过此功能,数据库:
$query = "INSERT INTO `expenses` VALUES (id,'".mysql_real_escape_string($username)."','".mysql_real_escape_string($ammount)."','".mysql_real_escape_string($date)."','".mysql_real_escape_string($reason)."')";
if ($query_run = mysql_query($query)) {
header ('Location: register_success.php');
} else {
echo 'Sorry, we couldn\'t add your expense for the moment.';
}
当然,当查询没有发生时,我会从查询中得到回显消息。 我使用_POST从形式得到他们,就像这样:
<form action="register.php" method="POST">
<strong>Add expense</strong> <br/>
Ammount: <br/>
<input type="text" placeholder="Ammount" name="ammount" value="<?php echo isset($_POST['ammount'])?$_POST['ammount']:null; ?>"><br/>
Date: <br/>
<input type="date" placeholder="Enter Date" name="date" value="<?php echo isset($_POST['date'])?$_POST['date']:null; ?>"><br/>
Reason of expense: <br/>
<input type="text" placeholder="Reason for expense" name="reason" value="<?php echo isset($_POST['reason'])?$_POST['reason']:null; ?>"><br/>
<input type="submit" name="Submit">
</form>
我很新,所以......任何建议吗?谢谢
此外,错误消息“对不起,我们暂时无法添加您的费用。”当索引文件加载时弹出,只有当我点击提交按钮时才会弹出。 – Cataneo
你真的为每个变量做了一个单独的查询吗?为什么不做一个'select *'然后访问'$ row ['field']'? – Barmar
您正在使用非常糟糕的方法获取用户数据。取数据一次,而不是为每个字段运行查询 – Ibu