不向数据库添加数据?

toiithl6  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(420)

所以我对php还比较陌生,我有一些php代码,可以确认一个用户已经被添加到一个组中,然后将他们的信息提交到数据库中,但它似乎没有添加所有的信息

<?php
/* Verifies member being added

* /

require 'db.php';
session_start();

 // Make sure join code and email aren't empty
 if(isset($_GET['joincode']) && !empty($_GET['joincode']) AND isset($_GET['memberemail']) && !empty($_GET['memberemail']))
{ 
$joincode = $link->escape_string($_GET['joincode']);
$memberemail = $link->escape_string($_GET['memberemail']);

  // Select user with matching email
  $result = $link->query("SELECT * FROM logins WHERE Email='$memberemail'");

    if ( $result->num_rows !==1 )
    {
    $_SESSION['message'] = "You need to create an account or the URL is invalid!";

    header("location: error.php");

    }
   else {
    $_SESSION['message'] = "You have been added!";

   while ($id = $result->fetch_assoc()){

    $id['unique_id'];
    }

    $leagueinfo = $link->query("SELECT * FROM leagues WHERE joincode='$joincode'");

    $info = $leagueinfo->fetch_assoc();
      $info['league_id'];
      $info['league_name'];
      $info['start_date'];
      $info['end_date'];

    $sql = "INSERT INTO leagues (unique_id, league_id, league_name, role, start_date, end_date, joincode) "
  . "VALUES ('".$id['unique_id']."','".$info['league_id']."','".$info['league_name']."','MEMBER',
  '".$info['start_date']."','".$info['end_date']."','".$joincode."')";

      mysqli_query($link,$sql);

    //  header("location: success.php");
   }
  }
else {
 $_SESSION['message'] = "Invalid parameters provided for account verification!";
header("location: error.php");
}
  ?>

我已经更改了不同查询的名称,它现在正在提取所有信息,除了唯一的\u id,它正确地回显,但没有被添加到数据库中。

frebpwbc

frebpwbc1#

您正在覆盖 $row$leagueinfo 查询。
应该为这些结果集使用不同的名称。
还要注意,这是一种非常奇怪的获取结果集的方法:


# Why are you using $row = $row = ... ?

while ($row = $row = $result->fetch_assoc()){
    $row['unique_id'];
}

循环中的行不会做任何事情,而您将始终以 $row 包含循环最后一次迭代的结果。
检查行数是否为1,如果不是,则抛出一个错误,这样做更有意义。然后只需获取一行,而不使用循环:

if ($result->num_rows !== 1) {
    # Handle error for example by throwing an exception
}

# You need an else if you don't return from a method or throw an exception

$row = $result->fetch_assoc();

您还有一个sql注入问题:您正在转义select语句的值,而不是insert语句的值。我建议在任何地方都使用准备好的语句,而不是使用转义。

相关问题