mysql 从数据库获取ID时出错[已关闭]

zrfyljdw  于 2023-06-28  发布在  Mysql
关注(0)|答案(1)|浏览(115)

**关闭。**此题需要debugging details。目前不接受答复。

编辑问题以包括desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将帮助其他人回答这个问题。
2天前关闭。
Improve this question
我目前正在创建一个类似于magistream和dragoncave的可采用站点(供参考),但在Node.js中使用html,css和js使用jquery。

app.post('/breed', (req, res) => {
  const { femaleAdoptableId, maleAdoptableId } = req.body;

  connection.connect(function (err) {
    if (err) {
      console.error('Error connecting to database:', err);
      return;
    }
    console.log('Connected to the database!');
  });

    const getAdoptableQuery = `SELECT id FROM owned_adopts WHERE username= ? ;`;
    connection.query(getAdoptableQuery, [femaleAdoptableId, maleAdoptableId], (err, results) => {
      
      console.log(femaleAdoptableId, maleAdoptableId)

      if (err || results.length !== 2) {
        res.json({ message: 'Invalid adoptables.' });
        return;
      }

      const femaleAdoptable = results.find((adoptable) => adoptable.id === femaleAdoptableId);
      const maleAdoptable = results.find((adoptable) => adoptable.id === maleAdoptableId);

      // Check if the adoptables are breedable
      if (!areAdoptablesBreedable(femaleAdoptable, maleAdoptable)) {
        res.json({ message: 'Adoptables are not breedable.' });
        return;
      }

      // Check if the adoptables are on cooldown
      if (isOnCooldown(femaleAdoptable) || isOnCooldown(maleAdoptable)) {
        res.json({ message: 'Adoptables are on cooldown.' });
        return;
      }

      // Check if the player has enough gold to breed based on rarity
      const femaleRarity = femaleAdoptable.rarity;
      const maleRarity = maleAdoptable.rarity;
      const breedingCost = getBreedingCost(femaleRarity, maleRarity);

      // Retrieve the player's gold from the database
      const playerId = '';
      const getPlayerGoldQuery = `SELECT gold FROM users WHERE id = ?`;
      connection.query(getPlayerGoldQuery, playerId, (err, playerResult) => {
        if (err || playerResult.length !== 1) {
          res.json({ message: 'Failed to retrieve player data.' });
          return;
        }

        const playerGold = playerResult[0].gold;

        if (playerGold < breedingCost) {
          res.json({ message: 'Insufficient gold to breed.' });
          return;
        }

        // Deduct the breeding cost from the player's gold
        const deductGoldQuery = `UPDATE users SET gold = gold - ? WHERE id = ?`;
        connection.query(deductGoldQuery, [breedingCost, playerId], (err) => {
          if (err) {
            res.json({ message: 'Failed to deduct gold from player.' });
            return;
          }

          // Perform the breeding process
          const children = performBreeding(femaleAdoptable, maleAdoptable);

          // Insert the mother and father IDs into the children's records
          const childrenWithLineage = insertLineageInformation(children, femaleAdoptableId, maleAdoptableId);

          // Update the mother and father's cooldown
          updateAdoptableCooldown(femaleAdoptableId, connection);
          updateAdoptableCooldown(maleAdoptableId, connection);

          // Insert the children into the database
          insertChildrenIntoDatabase(childrenWithLineage, connection);

          // Return the breeding result to the client
          res.json({ message: 'Breeding successful!', children: childrenWithLineage });
        });
      });
    });
  });
;

// Helper functions

function areAdoptablesBreedable(femaleAdoptable, maleAdoptable) {
  // Check if the adoptables have the same species
  if (femaleAdoptable.species !== maleAdoptable.species) {
    return false;
  }

  // Check any additional requirements or compatibility rules for breeding
  // Add your logic here...

  // Return true if all conditions pass
  return true;
}

function isOnCooldown(adoptable) {
  // Get the current timestamp
  const currentTimestamp = new Date().getTime();

  // Check if the adoptable's last breeding timestamp is within the cooldown period
  const lastBreedingTimestamp = new Date(adoptable.last_breeding_timestamp).getTime();
  const cooldownPeriod = 24 * 60 * 60 * 1000; // 24 hours in milliseconds

  if (currentTimestamp - lastBreedingTimestamp < cooldownPeriod) {
    return true;
  }

  return false;
}

function getBreedingCost(femaleRarity, maleRarity) {
  // Calculate the breeding cost based on the rarity of the adoptables
  // You can define your own rules or calculations based on your game mechanics
  const rarityMultiplier = 10;
  const breedingCost = (femaleRarity + maleRarity) * rarityMultiplier;

  return breedingCost;
}

function performBreeding(femaleAdoptable, maleAdoptable) {
  // Generate the children based on the parents' attributes, species, etc.
  // You can use randomization or predefined rules to determine the child's characteristics

  const children = [];

  // Determine the number of children to produce (1 or 2)
  const numberOfChildren = Math.random() < 0.5 ? 1 : 2;

  for (let i = 0; i < numberOfChildren; i++) {
    // Create a new child object
    const child = {};

    // Inherit the species from the parents
    child.species = femaleAdoptable.species;

    // Add more logic here to determine the child's characteristics, attributes, etc.

    // Random breeding check
    const isInterested = Math.random() < 0.5; // 50% chance of being interested in breeding

    if (!isInterested) {
      console.log("These adoptables aren't interested in each other.");
      return children;
    }

    // Add the child to the children array
    children.push(child);
  }

  return children;
}

function insertLineageInformation(children, motherId, fatherId) {
  // Insert the mother and father IDs into the children's records
  return children.map((child) => {
    return {
      ...child,
      motherId,
      fatherId,
    };
  });
}

function updateAdoptableCooldown(adoptableId, connection) {
  // Update the adoptable's cooldown timestamp in the database
  const updateCooldownQuery = `UPDATE owned_adopts SET last_breeding_timestamp = CURRENT_TIMESTAMP WHERE id = ?`;
  connection.query(updateCooldownQuery, adoptableId, (err) => {
    if (err) {
      console.error('Failed to update adoptable cooldown:', err);
    }
  });
}

function insertChildrenIntoDatabase(children, connection) {
  // Insert each child into the database
  const insertChildQuery = `INSERT INTO owned_adopts (name, species, mother_id, father_id) VALUES (?, ?, ?, ?)`;

  children.forEach((child) => {
    const { name, species, motherId, fatherId } = child;

    connection.query(insertChildQuery, [name, species, motherId, fatherId], (err) => {
      if (err) {
        console.error('Failed to insert child adoptable:', err);
      }
    });
  });
}

这就是繁殖后的脚本。
我已经尝试将id表名改回“id”,以防出现问题。我甚至确保数字是以整数的形式传递的。

jdgnovmf

jdgnovmf1#

我想你想要的是这样的,首先将连接移到外面,然后选择*获取所有字段,然后通过接收到的id进行过滤,将id作为数组的数组传递:

connection.connect(function (err) {
  if (err) {
    console.error('Error connecting to database:', err);
    return;
  }
  console.log('Connected to the database!');
});

app.post('/breed', (req, res) => {
  const { femaleAdoptableId, maleAdoptableId } = req.body;

  const getAdoptableQuery = `SELECT * FROM owned_adopts WHERE id IN (?);`;
  connection.query(getAdoptableQuery, [[femaleAdoptableId, maleAdoptableId]], (err, results) => {

    console.log(femaleAdoptableId, maleAdoptableId)

    if (err || results.length !== 2) {
      res.json({ message: 'Invalid adoptables.' });
      return;
    }

相关问题