将值写入数据库中的另一个表

时间:2013-11-01 15:40:32

标签: php html mysql database

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

表费用: id(这不是自动增量), 用户名,ammount,日期原因 - >其他领域。

我正在使用一个名为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.';
    }

当然,我从查询中获取echo消息,该消息在查询未发生时触发。 我正在使用_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>

我很新,所以...任何sugestions?谢谢

1 个答案:

答案 0 :(得分:1)

id不是费用查询中的变量。您应该在查询中添加错误消息,以帮助您将来调试它们。

$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');

此外,您确实应该使用mysqlipdomysql is deprecated as of php 5.5.x,这样您就可以省去将来重写所有内容的麻烦。