0

我有一个包含两个表的数据库:“用户”和“费用”。表用户:id - 主要,自动增量;用户名密码等...

表费用:id(这不是自动增量)、用户名、金额、日期原因 -> 其他字段。

我正在使用一个名为 getuserfields() 的函数从 USERS 表中获取字段(它存储在我在每个 php 中都需要的 core.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>

我很新,所以......有什么建议吗?谢谢

4

1 回答 1

1

id isn't a variable in your expenses query. You should add error messages to your queries to help you debug them in the future.

$query = mysql_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)."'
   )")
or die ('Sorry, we couldn\'t add your expense for the moment: ' . mysql_error());

header ('Location: register_success.php');

Also you really should be using mysqli or pdo, mysql is deprecated as of php 5.5.x so you should save yourself the trouble of re-writing everything in the future.

于 2013-11-01T15:52:02.483 回答